hope you're having a good day.
I want to do something like this.
CREATE TABLE Certificat
(
num_certificat SMALLINT NOT NULL,
description TEXT NOT NULL,
Date_depot DATE NOT NULL CHECK(Date_depot <= GETDATE()),
Date_validation DATE NOT NULL CHECK(Date_validation > Date_depot),
num_auteur SMALLINT NOT NULL,
num_innovation SMALLINT NOT NULL,
CONSTRAINT pk_numc PRIMARY KEY(num_certificat),
CONSTRAINT fk_au FOREIGN KEY(num_auteur) REFERENCES Auteur(num_auteur) ON
DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_inn FOREIGN KEY(num_innovation) REFERENCES
Innovation(num_innovation) ON DELETE CASCADE ON UPDATE CASCADE,
);
But I get this error:
Msg 8141, Level 16, State 0, Line 4
Column CHECK constraint for column 'Date_validation' references another column, table 'Certificat'.
Msg 1750, Level 16, State 0, Line 4
Could not create constraint or index. See previous errors.
So how can I reference another column into a CHECK clause? I want the table to reject entries with the Date_depot greater than Date_validation.
You need to create it at the table level - not inline next to a column.
CREATE TABLE Certificat
(
num_certificat SMALLINT NOT NULL,
description TEXT NOT NULL,
Date_depot DATE NOT NULL CHECK(Date_depot <= GETDATE()),
Date_validation DATE NOT NULL,
num_auteur SMALLINT NOT NULL,
num_innovation SMALLINT NOT NULL,
CHECK(Date_validation > Date_depot), /*<----- Moved here*/
CONSTRAINT pk_numc PRIMARY KEY(num_certificat),
CONSTRAINT fk_au FOREIGN KEY(num_auteur) REFERENCES Auteur(num_auteur) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_inn FOREIGN KEY(num_innovation) REFERENCES Innovation(num_innovation) ON DELETE CASCADE ON UPDATE CASCADE,
);
You should also consider giving it an explicit name. For example
CONSTRAINT ck_validation_after_depot CHECK(Date_validation > Date_depot)
Related
I am trying to create some tables in SQL but when I am running these queries, I am getting the following exception:
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Couple' that match the referencing column list in the foreign key 'FK__wedding__CoupleN__2739D489'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
CREATE TABLE Person
(
FirstName nvarchar (25) NOT NULL,
SurName nvarchar (25) NOT NULL,
id char(9) PRIMARY KEY
CHECK (id LIKE REPLICATE('[0-9]',9)),
PhoneNumber char(10)
CHECK (PhoneNumber LIKE REPLICATE('[0-9]',10)),
Birthday date
CHECK ((GETDATE() - YEAR(Birthday)) > 10)
);
CREATE TABLE Couple
(
Number int identity(1000,1),
Partner1 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
Partner2 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
CoupleName varchar(25) NOT NULL,
CONSTRAINT PK_Couple1 CHECK (Partner1 <> Partner2),
CONSTRAINT PK_Couple PRIMARY KEY (Partner1, Partner2, Number)
);
CREATE TABLE weddinghall
(
Name varchar (25) PRIMARY KEY,
SeveralSeats int
CHECK (SeveralSeats >= 50 AND SeveralSeats <= 5000),
Kosher char(1)
CHECK (works = 'Y' OR not = 'N'),
PlaceType varchar(25)
CHECK (PlaceType IN s, 'b', 'd', 'doif')),
NumberOfParkingSpaces int
);
CREATE TABLE wedding
(
WeddingHallName varchar (25)
REFERENCES weddinghall(Name) ON DELETE CASCADE,
CoupleNumber int
REFERENCES Couple (Number) ON DELETE CASCADE,
WeddingDate date,
NumberOfGuests Int ,
CONSTRAINT PK_Wedding PRIMARY KEY (CoupleNumber, WeddingHallName)
);
CREATE TABLE WeddingGuests
(
GuestId char(9) references Person (Id) ON DELETE cascade,
CoupleNumber int references Couple (Number) ON DELETE cascade,
WeddingDate date,
WeddingHallName varchar (25) references weddinghall(Name) ON DELETE cascade,
ArrivalConfirmation CHAR(1),
ArrivingToWedding Char(1),
CONSTRAINT PK_WeddingGuests
PRIMARY KEY (GuestId, CoupleNumber, WeddingDate, WeddingHallName)
);
Can you please help?
The error message is telling you that you don't have a unique constraint or primary key on dbo.Couple.Number. That is the third key column in your primary key constraint, and you can't point a foreign key there. You can either:
Add a unique constraint on dbo.Couple.Number
Change the PK to a unique constraint and make dbo.Couple.Number the single-column primary key.
I have this table
CREATE TABLE [dbo].[EmployeesEmployeeDepartments]
(
[EmployeeId] INT NOT NULL,
[EmployeeDepartmentId] INT NOT NULL,
[UpdatedBy] NVARCHAR(50) NOT NULL CONSTRAINT [DF_EmployeesEmployeeDepartments_UpdatedBy] DEFAULT N'system',
[FromDate] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL CONSTRAINT [DF_EmployeesEmployeeDepartments_FromDate] DEFAULT SYSUTCDATETIME(),
[ToDate] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL CONSTRAINT [DF_EmployeesEmployeeDepartments_ToDate] DEFAULT CONVERT(DATETIME2, '9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME ([FromDate], [ToDate]),
CONSTRAINT PK_EmployeesEmployeeDepartments PRIMARY KEY (EmployeeId,EmployeeDepartmentId),
CONSTRAINT FK_EmployeesEmployeeDepartments_Employee FOREIGN KEY (EmployeeId) REFERENCES Employees([EmployeeId]),
CONSTRAINT FK_EmployeesEmployeeDepartments_EmployeeDepartment FOREIGN KEY (EmployeeDepartmentId) REFERENCES EmployeeDepartments([EmployeeDepartmentId])
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeesEmployeeDepartmentsHistory));
And I am trying to update the PK constraint to only have 1 field as primary key
I have this post deployment script in my database project
ALTER TABLE [dbo].[EmployeesEmployeeDepartments]
DROP CONSTRAINT PK_EmployeesEmployeeDepartments
ALTER TABLE [dbo].[EmployeesEmployeeDepartments]
ADD CONSTRAINT PK_EmployeesEmployeeDepartments PRIMARY KEY (EmployeeId)
When I publish the db project. I am getting this error
SQL72014: .Net SqlClient Data Provider: Msg 13557, Level 16, State 1, Line 759 Cannot drop PRIMARY KEY constraint from a system-versioned temporal table 'Employees.dbo.EmployeesEmployeeDepartments'.
CREATE TABLE Loan
(
Customerid Char(9) NOT NULL,
EquipmentCode Char(5) NOT NULL,
StartDate DateTime NOT NULL,
EndDate DateTime NULL,
CONSTRAINT CHK_ID
CHECK (Customerid LIKE '[ST][0-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]'),
CONSTRAINT CHK_Date CHECK (EndDate >= StartDate),
CONSTRAINT Loan_PK PRIMARY KEY(Customerid),
CONSTRAINT CUST_FK
FOREIGN KEY(Customerid) REFERENCES CUST(CustomerID)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE EQUIPMENT
(
EquipmentCode CHAR(5) NOT NULL,
EquipmentName VARCHAR(50) NOT NULL,
Description VARCHAR(255) NULL,
RentalRatePerDay DECIMAL(4,2) NOT NULL,
CONSTRAINT EQP_PK PRIMARY KEY(EquipmentCode),
CONSTRAINT CHK_Rate CHECK (RentalRatePerDay BETWEEN 4 AND 50),
CONSTRAINT LOAN_FK
FOREIGN KEY(EquipmentCode) REFERENCES Loan(EquipmentCode)
ON UPDATE CASCADE
ON DELETE CASCADE
);
I was able to reference earlier on in the above loan.table but for the equipment table it states
Msg 1776, Level 16, State 0, Line 49
There are no primary or candidate keys in the referenced table 'Loan' that match the referencing column list in the foreign key 'LOAN_FK'.
Msg 1750, Level 16, State 1, Line 49
Could not create constraint or index. See previous errors.
Please advise.
When we create a ForeignKey on a dependent table, it MUST refer back to the PrimaryKey (or a Unique Key see: https://stackoverflow.com/a/18435114/1690217) on the principal table.
In your case, EQUIPMENT is the principal end of the relationship, and Loan is the dependent. What this means is that the FK needs to be on the Loan table instead, so you should have this:
CREATE TABLE EQUIPMENT
(
EquipmentCode CHAR(5) NOT NULL,
EquipmentName VARCHAR(50) NOT NULL,
Description VARCHAR(255) NULL,
RentalRatePerDay DECIMAL(4,2) NOT NULL,
CONSTRAINT EQP_PK PRIMARY KEY(EquipmentCode),
CONSTRAINT CHK_Rate CHECK (RentalRatePerDay BETWEEN 4 AND 50),
);
CREATE TABLE Loan
(
Customerid Char(9) NOT NULL,
EquipmentCode Char(5) NOT NULL,
StartDate DateTime NOT NULL,
EndDate DateTime NULL,
CONSTRAINT CHK_ID
CHECK (Customerid LIKE '[ST][0-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z]'),
CONSTRAINT CHK_Date CHECK (EndDate >= StartDate),
CONSTRAINT Loan_PK PRIMARY KEY(Customerid),
CONSTRAINT CUST_FK
FOREIGN KEY(Customerid) REFERENCES CUST(CustomerID)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT EQUIPMENT_FK
FOREIGN KEY(EquipmentCode) REFERENCES EQUIPMENT(EquipmentCode)
ON UPDATE CASCADE
ON DELETE CASCADE
);
A foreign key references a primary key on another table. You have the FK on the wrong table
I only have this error now.. I cant seem to see where it is too long (ERROR at bottom of page)
CREATE TABLE Menu_Item_Ingredient
(
Menu_Item_Number Number(5,0)CONSTRAINT NN_MenuItemIngredient_MenuItemNumber Not null,
CONSTRAINT FK_MenuItemIngredient_MenuItemNumber Foreign Key(Menu_Item_Number) References Bill_Item(Menu_item_Number),
Ingredient_Number Number(5,0) CONSTRAINT NN_MenuItemIngredient_IngredientNumber Not null,
CONSTRAINT FK_MenuItemIngredient_IngredientNumber Foreign Key(Ingredient_Number) References Ingredient(Ingredient_Number),
Quantity_Needed Number(5,2) DEFAULT 0 CONSTRAINT NN_MenuItemIngredient_QuantityNeeded Not null
CONSTRAINT CK_MenuItemIngredient_QuantityNeeded CHECK(Quantity_Needed >= 0),
CONSTRAINT PK_BillItem_Ingredient Primary key(Menu_Item_Number,Ingredient_Number)
)
Error report -
SQL Error: ORA-00972: identifier is too long
00972. 00000 - "identifier is too long"
*Cause: An identifier with more than 30 characters was specified.
*Action: Specify at most 30 characters.
Do something below. In your query, a comma is missing when you are declaring discount column in bill_item table.
CREATE TABLE Bill_Item3
(
Bill_Number NUMBER(6,0) CONSTRAINT NN_BillItem_BillNumber NOT NULL,
Menu_Item_Number NUMBER(5,0) CONSTRAINT NN_BillItem_MenuItemNumber NOT NULL,
Discount NUMBER(5,2) CONSTRAINT N_BillItem_Discount NULL,
--colum Discount format '%'00.00,
Quaintity_Sold NUMBER(3,0)CONSTRAINT NN_BillItem_QuaintitySold NOT NULL,
Selling_Price NUMBER(6,2) default 0 CONSTRAINT NN_BillItem_SellingPrice NOT NULL,
CONSTRAINT CK_BillItem_SellingPrice CHECK (Selling_Price >= 0 ),
CONSTRAINT PK_Bill_MenuItem PRIMARY KEY (Bill_Number,Menu_Item_Number),
CONSTRAINT FK_BillItem_Bill FOREIGN KEY (Bill_Number) REFERENCES bill (Bill_Number),
CONSTRAINT FK_BillItem_MenuItemNumber FOREIGN KEY (Menu_Item_Number) REFERENCES Menu_Item_Ingredient(Menu_Item_Number),
CONSTRAINT CK_BillItem_Discount CHECK (Discount BETWEEN 0 AND 100)
);
Your problem is with the constraints,
A foreign key constraint will be used to give reference to a column in another table, in your queries you have given constraints like below -
"CONSTRAINT FK_BillItem_Bill Foreign key (Bill_Number) References Primary(Bill_Number), what are you trying to do with this?
The syntax you need to use should be -
CONSTRAINT constraint_name FOREIGN KEY (column_in_current_table) REFERENCES Other_Table_Name(column_name_you_want_to_refer_in_other_table)
As far as I've seen, this will not work, you cannot use DEFAULT in a check constraint.
constraint CK_BillItem_SellingPrice check (Selling_Price >= 0 OR DEFAULT = 0)
If you want to enforce a DEFAULT constraint, you have to use something as below -
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
Your final table can be as follows -
CREATE TABLE Bill_Item
(
Bill_Number Number(6,0) constraint NN_BillItem_BillNumber not null,
--CONSTRAINT FK_BillItem_Bill Foreign key (Bill_Number) References Primary(Bill_Number),
Menu_Item_Number Number(5,0) CONSTRAINT NN_BillItem_MenuItemNumber Not null,
--CONSTRAINT FK_BillItem_MenuItemNumber Foreign Key (Menu_Item_Number) References Primary(Menu_Item_Number),
Discount Number(5,2) CONSTRAINT N_BillItem_Discount Null
CONSTRAINT CK_BillItem_Discount Check (Discount BETWEEN 0 and 100),
--colum Discount format '%'00.00,
Quaintity_Sold Number(3,0)CONSTRAINT NN_BillItem_QuaintitySold not null,
Selling_Price Number(6,2) DEFAULT 0.0 CONSTRAINT NN_BillItem_SellingPrice not null, -- You can remove "DEFAULT 0.0" if you do not want to default your Selling_Price to 0.0
constraint CK_BillItem_SellingPrice check (Selling_Price >= 0),
CONSTRAINT PK_Bill_MenuItem Primary key (Bill_Number,Menu_Item_Number)
);
All of your other tables also have the same issue, remove the DEFAULT from check constraint as I did in the above example, and specify "Default" constraint at the column definition itself.
Also, create the table which will be referenced in other tables first, for example, your second table "Bill" has a foreign key constraint which is referencing to "Waiter" table, so you have to create "Waiter" table first.
If you are still having concerns let me know.
CREATE TABLE Usuario
(
id int identity not null,
usuario char(20) unique not null,
senha char(10) not null,
tipo_usuario char(15) not null,
primary key (id),
foreign key (tipo_usuario) references TpoUsuario
on update cascade on delete set default
);
CREATE TABLE TpoUsuario
(
id int identity not null,
tipo_usuario char(15) not null,
primary key(id)
);
This use a codes to top, and received this message error.
First I created table TpoUsuario, then I created table Usuario.
Msg 1778, Level 16, State 0, Line 1
Column 'TpoUsuario.id' is not the same data type as referencing column 'Usuario.tipo_usuario' in foreign key 'FK__Usuario__tipo_us__60A75C0F'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
TpoUsuario.id is an int data type column while Usuario.tipo_usuario is char type column
Could you link Usuario.id with TpoUsuario.id or Usuario.usario with TpoUsuario.tipo_usuario
See how to define foreign-keys:
SQL FOREIGN KEY
You say
foreign key (tipo_usuario) references TpoUsuario on update cascade on delete set default
Syntax is FOREIGN KEY (column col1, column col2, ...) REFERENCES table_name(column col1, column col2,...)