Give name to a constraint - constraints

Is it possible to name the constraints in a table?
The problem I am facing is that when a constraints does not succeed I get a cryptic message instead of a clear name of which constraint it failed.
I tried something like :
primer_nombre varchar(25) NOT NULL CHECK 'is_it_valid?' (primer_nombre MATCHES '^[a-zA-Z]$' )
But this fails. So Im stuck here.
CREATE TABLE Usuarios
(
CI INT PRIMARY KEY,
primer_nombre varchar(25) NOT NULL CHECK (primer_nombre MATCHES '^[a-zA-Z]$' ),
segundo_nombre varchar(25),
primer_apellido varchar(25) NOT NULL,
segundo_apellido varchar(25),
grado INT CHECK ( grado > 0 AND grado < 8),
fecha_nacimiento DATE NOT NULL,
nota INT CHECK ( nota > 0 AND nota < 13),
email varchar(80),
hace_proyecto boolean,
tipo varchar(20) CHECK (tipo IN ('Admin', 'Docente', 'Alumno')),
encriptacion_hash varchar(250),
encriptacion_sal varchar(250),
baja boolean
);
Output I get :
530: Check constraint (admin_proyecto.c106_43) failed.
Error in line 7
Near character position 127
I would like to get a clearer message than that.

The SQL standard positions constraint names before the constraint 'body', whereas Informix positions the constraint names after the constraint body.
Thus, in standard SQL, you might write:
…
grado INT CONSTRAINT usuarios_grado CHECK (grado > 0 AND grado < 8),
…
but in Informix's dialect, you need to write:
…
grado INT CHECK (grado > 0 AND grado < 8) CONSTRAINT usuarios_grado,
…

To expand on Erwin's answer:
CREATE TABLE Usuarios
(
CI INT PRIMARY KEY,
primer_nombre varchar(25) NOT NULL CHECK (primer_nombre MATCHES '^[a-zA-Z]$' ) CONSTRAINT constraint_primer_nombre
);
> insert into Usuarios values (1,'asd');
530: Check constraint (Administrator.constraint_primer_nombre) failed.
Error in line 1
Near character position 36
>

In general SQL is devised so that all supported constraints can be assigned a name. For the particular SQL dialect of the engine you're using, refer to your engine's SQL Syntax manual.

Related

sqlite integer primary key not null constraint failed

According to the SQLite documentation / FAQ a column declared INTEGER PRIMARY KEY will automatically get a value of +1 the highest of the column if omitted.
Using SQLite version 3.22.0 2018-01-22 18:45:57
Creating a table as follows:
CREATE TABLE test (
demo_id INTEGER PRIMARY KEY NOT NULL,
ttt VARCHAR(40) NOT NULL,
basic VARCHAR(25) NOT NULL,
name VARCHAR(255) NOT NULL,
UNIQUE(ttt, basic) ON CONFLICT ROLLBACK
) WITHOUT ROWID;
Then inserting like this:
INSERT INTO test (ttt, basic, name) VALUES ('foo', 'bar', 'This is
a test');
gives:
Error: NOT NULL constraint failed: test.demo_id
sqlite>
When it is expected to create a record with a demo_id value of 1. Even if the table already contains values, it'll fail inserting the row without explicitly specifying the id with the same error.
What am I doing wrong?
The documentation says that you get autoincrementing values for the rowid. But you specified WITHOUT ROWID.

How can I use IF statements in Teradata without using BTEQ

I'm trying to create some deployment tools and I don't want to use BTEQ. I've been trying to work with the Teradata.Client.Provider in PowerShell but I'm getting syntax errors on the creation of a table.
[Teradata Database] [3706] Syntax error: expected something between
';' and the 'IF' keyword.
SELECT * FROM DBC.TablesV WHERE DatabaseName = DATABASE AND TableName = 'MyTable';
IF ACTIVITYCOUNT > 0 THEN GOTO EndStep1;
CREATE MULTISET TABLE MyTable ,
NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO
(
MyColId INTEGER GENERATED ALWAYS AS IDENTITY
(START WITH 1
INCREMENT BY 1
MINVALUE 0
MAXVALUE 2147483647
NO CYCLE)
NOT NULL,
MyColType VARCHAR(50) NULL,
MyColTarget VARCHAR(128) NULL,
MyColScriptName VARCHAR(256) NULL,
MyColOutput VARCHAR(64000) NULL,
isMyColException BYTEINT(1) NULL,
ExceptionOutput VARCHAR(64000) NULL,
MyColBuild VARCHAR(128) NULL,
MyColDate TIMESTAMP NOT NULL
)
PRIMARY INDEX PI_MyTable_MyColLogId(MyColLogId);
LABEL EndStep1;
I would rather not use BTEQ as I've not found it has worked well in other deployment tools we have created and requires a bit of hacks. Is there anything I can use that would avoid using that tool?
What Parse error?
The CREATE will fail due to double INTEGER in MyColId and VARCHAR(max) in ExceptionOutput, it's an unknown datatype in Teradata.

Why result of a query is OK in sql-server run, but has an error when I use it in a ASP.Net page?

I have a Table with GUID date type field as Primery Key. when I run the query in DataSet window of ASP.net, the result is OK, but when I use it in ASP.Net Page it will return an error page like below :
Failed to enable constraints. One or more rows contain values violating non-null,unique, or foreign-key constraints.
The query has not any type of join, and a simple SUM query that add up daily work amounts in a filed based on date range which pass as a parameter to the query and Group by activities that exist in another filed.
This is the table :
CREATE TABLE [dbo].[DailyReport] (
[ReportDate] DATETIME NULL,
[ReportId] UNIQUEIDENTIFIER NOT NULL,
[ConstructionType] NVARCHAR (50) NULL,
[Zone] NVARCHAR (50) NULL,
[BuildingName] NVARCHAR (50) NULL,
[ActivityId] INT NULL,
[TodayWork] REAL NULL,
[Decription] NTEXT NULL,
PRIMARY KEY CLUSTERED ([ReportId] ASC)
);
And this is the query :
SELECT SUM(TodayWork) AS SumWork, ActivityId, COUNT(ReportId) AS RecordCount
FROM DailyReport
WHERE (ConstructionType = N'1') AND (ReportDate >= #DateStart) AND
(ReportDate <= #DateFinish)
GROUP BY ActivityId
Normally in c# int does not allow null values but that can do in sqlserver, that mean null values can be allowed by sql server but not in c#.
so it can be solved in 2 ways
1) either use allow null to false in database
2) or use nullable int type in c# code by using like "int? a=null"

ORA-00907: missing right parenthesis when creating tables

I am trying to create 3 tables but I am getting this error:
CREATE TABLE dj_abonent
(
dj_klientID INT NOT NULL PRIMARY KEY,
emer_klienti varchar2(10),
mbiemer_klienti VARCHAR2(10),
sasia_cel INT
);
CREATE TABLE dj_phones
(
phone_number varchar2(12),
activated number(1) default 0,
activation_date date default null,
CONSTRAINT dj_phone_number_check
CHECK (substr(phone_number,1,5) in( '35566','35567','35568','35569') ),
CONSTRAINT dj_activated_check
CHECK (activated in(1,0) )
dj_KlientID int FOREIGN KEY REFERENCES dj_Abonenti(dj_KlientID)
);
CREATE TABLE dj_telef
(
start_time date,
end_time date,
abonent_1 varchar2(10),
abonent_2 varchar2(10)
);
Error at Command Line : 26 Column : 17
Error report -
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
*Cause:
*Action:
The line number is from your SQL Developer script window, which isn't entirely helpful as it doesn't seem to align with the issue. There may be other things too but you're missing a comma after your check constraint (just like a previous question). But you should put the constraints at the end of the command:
CREATE TABLE dj_phones
(
phone_number varchar2(12),
activated number(1) default 0,
activation_date date default null,
dj_KlientID int FOREIGN KEY REFERENCES dj_Abonenti(dj_KlientID)
CONSTRAINT dj_phone_number_check
CHECK (substr(phone_number,1,5) in( '35566','35567','35568','35569') ),
CONSTRAINT dj_activated_check
CHECK (activated in(1,0) )
);
You might find it easier to debug these issues if you ran one statement at a time, either with the run statement command (control-enter), or by highlighting the text one one command and using run script (F5).

SQLite: Constraint failed on Insert

I have one Auto Increment Field, rest are Integer,Text and Datetime field. How do I fix it out?
The Table Structure is given below:
CREATE TABLE "q1" (
"sb_id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"sb_title" text(100,0) NOT NULL,
"sb_details" text(300,0) NOT NULL,
"sb_image" text(30,0) NOT NULL,
"sb_type" integer(4,0) NOT NULL DEFAULT '1',
"sb_date" datetime NOT NULL
)
It could be because in your insert command
connection.execute("INSERT INTO q1(sb_title,sb_details)VALUES(?,?)",a,b);
you didn't insert any values for sb_image or sb_date, both of which are NOT NULL and have no default defined. SQLite doesn't know what to put in there. You should either take away the NOT NULL constraint on those columns, define a default for the columns, or insert something explicitly.

Resources