REFERENCING ISSUE - sql

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

Related

SQL queries - There are no primary or candidate > keys in the referenced table

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.

SQL Server - Referencing another column in a CHECK clause

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)

I want to create a table with "WITH CHECK OPTION"

create table STAFF
(StaffID TINYINT IDENTITY NOT NULL,
fName varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk foreign key (Mentor) references staff(StaffID)
For the Gender column I want to insert ONLY 'M','F','O' characters only.
How can I do with this the "WITH CHECK OPTION"
I don't think you want with check option. You want a check constraint:
alter table staff
add constraint chk_staff_gender check (gender in ('M', 'F', 'O'));
(You can put this in the create table statement as well.)
with check option is an option on views that ensures that data remains consistent even when the data in underlying tables changes (see here) .
add , constraint gender_chk check (Gender in ('M','F','O'))
the with check option is on by default.
create table STAFF
(StaffID TINYINT IDENTITY NOT NULL,
fName varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID)
constraint staff_fk foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk foreign key (Mentor) references staff(StaffID)
, constraint gender_chk check (Gender in ('M','F','O'))
)
From the MSDN Documentation for ALTER TABLE (emphasis added):
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.
If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. We do not recommend doing this, except in rare cases. The new constraint will be evaluated in all later data updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.
The query optimizer does not consider constraints that are defined WITH NOCHECK. Such constraints are ignored until they are re-enabled by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.
You are refering to check constraint
create table STAFF
(StaffID TINYINT IDENTITY NOT NULL,
fName varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01) NOT NULL,
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk foreign key (Mentor) references staff(StaffID),
constraint Gender_ck check (Gender in ('M','F','O'))
)
"WITH CHECK OPTION" is an optional clause for of a view definition
Any attempt to update/insert a record, through the view, that cannot be selected by the view, will raise an error.

Why can't I reference in the column list?

This is my first database, I created HOTEL, ROOM and GUEST tables, but when I execute the BOOKING table, it's not working.
The error is:
There are no primary or candidate keys in the referenced table 'ROOM'
that match the referencing column list in the foreign key
'FK_BOOKING_ROOM'
Scripts:
CREATE DATABASE HOTEL
USE HOTEL
CREATE TABLE HOTEL
(
HolCode varchar(20) UNIQUE NOT NULL,
Name varchar(30),
City varchar(20) DEFAULT 'Ha noi',
CONSTRAINT PK_HOLEL PRIMARY KEY (HolCode)
)
CREATE TABLE ROOM
(
RoomNo int,
HolCode varchar(20),
TypeRoom char(1) DEFAULT 'S',
Price double precision,
CONSTRAINT CHK_TYPE CHECK (TypeRoom = 'D' OR TypeRoom = 'S' OR TypeRoom = 'F'),
CONSTRAINT CHK_PRICE CHECK (10 <= Price AND Price <= 200),
CONSTRAINT PK_ROOM PRIMARY KEY (RoomNo, HolCode),
CONSTRAINT FK_ROOM FOREIGN KEY (HolCode) REFERENCES HOTEL(HolCode)
)
-- TAO BANG GUEST
CREATE TABLE GUEST
(
GuestNo int,
GuestName varchar(30),
Address varchar(50),
CONSTRAINT PK_GUEST PRIMARY KEY (GuestNo)
)
--TAO BANG BOOKING
CREATE TABLE BOOKING
(
HolNo varchar(20) NOT NULL,
GuestNo int NOT NULL,
DateFrom DateTime DEFAULT GETDATE(),
DateTo DateTime,
RoomNo int NOT NULL,
CONSTRAINT PK_BOOKING PRIMARY KEY (HolNo, DateFrom, RoomNo),
-- CONSTRAINT FK_BOOKING_HOTEL FOREIGN KEY (HolNo) REFERENCES HOTEL(Code),
CONSTRAINT FK_BOOKING_GUEST FOREIGN KEY (GuestNo) REFERENCES GUEST(GuestNo),
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo, HolCode)
REFERENCES ROOM(RoomNo, HolCode)
)
DROP TABLE BOOKING
Try:
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo,HolNo)
REFERENCES ROOM(RoomNo,HolCode)
Rooms aren't uniquely identified by just a RoomNo so the foreign key needs to have the hotel code also. I'd also suggest, just as a stylistic point, that you try to use the same names in every table where the contents should be the same - so either HolNo or HolCode, but not both.

how do i cascade updates and deletions in oracle?

I'm trying to follow the examples in my book to cascade updates and deletions but the problem is their syntax doesnt work in oracle DB..
I understand to cascade an update would mean an update to a parent would also update its child and same with deletions.. but i cant figure out the syntax for oracle.. the specific questions from my book are:
7.5 -- Write a CREATE TABLE statement for the EMPLOYEE table. Email is
required and is an alternate key, and the default value of Department is
Human Resources. Cascade updates but not deletions from DEPARTMENT to EMPLOYEE.
7.6 -- Write a CREATE TABLE statement for PROJECT table. The default value for
MaxHours is 100. Cascade updates but not deletions from DEPARTMENT to EMPLOYEE.
7.7 -- Write a CREATE TABLE statement for the ASSIGNMENT table. Cascade only
deletions from PROJECT to ASSIGNMENT; do not cascade either deletions or
updates from EMPLOYEE to ASSIGNMENT.
I finally managed to successfully created these tables in iSQL *Plus with this Query:
CREATE TABLE DEPARTMENT (
DepartmentName char(35) NOT NULL,
BudgetCode char(30) NOT NULL,
OfficeNumber char(15) NOT NULL,
Phone char(12) NOT NULL,
Constraint DepartmentPK PRIMARY KEY(DepartmentName)
);
INSERT INTO DEPARTMENT VALUES (
'Administration', 'BC-100-10', 'BLDG01-300', '360-285-8100');
CREATE TABLE EMPLOYEE (
EmployeeNumber int NOT NULL,
FirstName char(25) NOT NULL,
LastName char(25) NOT NULL,
Department char(35) DEFAULT 'Human Resources' NOT NULL,
Phone char(12) NULL,
Email char(30) NOT NULL,
DepartmentName_FK char(35) NOT NULL,
Constraint EmployeePK PRIMARY KEY(EmployeeNumber),
Constraint EmployeeAK1 UNIQUE(Email),
Constraint DepartmentFK FOREIGN KEY (DepartmentName_FK)
references DEPARTMENT(DepartmentName)
--ON UPDATE CASCADE
--ON DELETE no ACTION
);
CREATE TABLE PROJECT (
ProjectID int NOT NULL,
Name char(30) NOT NULL,
Department1 char(15) NOT NULL,
MaxHours int DEFAULT 100 NOT NULL,
StartDate DATE NULL,
EndDate DATE NULL,
DepartmentName_FK1 char(30) NULL,
Constraint datecheck check (StartDate < EndDate),
Constraint ProjectIDPK PRIMARY KEY(ProjectID),
Constraint DepartmentFK1 FOREIGN KEY (DepartmentName_FK1)
references DEPARTMENT(DepartmentName)
-- ON UPDATE CASCADE
-- ON DELETE no ACTION
);
CREATE TABLE Assignment(
ProjectID Number NOT NULL,
EmployeeNumber Number NOT NULL,
HoursWorked Number NULL,
Constraint ProjectIDEmpNumPK PRIMARY KEY(ProjectID, EmployeeNumber),
constraint ProjectIDFK FOREIGN KEY(ProjectID)
references Project(ProjectID),
constraint EmpNumFK FOREIGN KEY(EmployeeNumber)
references Employee(EmployeeNumber)
--CONSTRAINT UniqueEmployee UNIQUE (EmployeNumber)
--ON DELETE CASCADE
);
but how do I specify cascading delete and update and specify not to?
Did you try this?
CREATE TABLE Assignment(
ProjectID Number NOT NULL,
EmployeeNumber Number NOT NULL,
HoursWorked Number NULL,
Constraint ProjectIDEmpNumPK PRIMARY KEY(ProjectID, EmployeeNumber),
constraint ProjectIDFK FOREIGN KEY(ProjectID)
references Project(ProjectID)
ON DELETE CASCADE
ON UPDATE no ACTION ,
constraint EmpNumFK FOREIGN KEY(EmployeeNumber)
references Employee(EmployeeNumber)
ON DELETE no ACTION
ON UPDATE no ACTION
);