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.