I need to create a relationship between ReportID which is part of a composite primary key.
This is my code written for Microsoft SQL Server:
CREATE TABLE Tableone
(
ReportID varchar UNIQUE,
Date date,
Line ommited
PRIMARY KEY (ReportNumber, Date)
)
CREATE TABLE Tabletwo
(
Line omitted
Line ommited
ReportID varchar UNIQUE FOREIGN KEY REFERENCES Tableone(ReportID),
Line ommited
PRIMARY KEY (XX, XXX, ReportID)
)
UPDATE: We have specifically been asked to set both ReportID and Date as the primary key in Tableone but to just reference ReportID in Tabletwo.
Thanks for your time.
If you have a composite primary key, then all foreign key constraints that reference it must use all columns of the composite primary key.
So in your case –
TableTwomust referenceTableOne(ReportID, Date)The only way around this would be to create a
UNIQUE INDEXonTableOne (ReportID)– then you can create a foreign key reference to that unique constraint alone.But that then begs the question: why isn’t
ReportIDalone the primary key, if it’s already unique (since you can put aUNIQUE INDEXon it) and NOT NULL (since it’s part of the compound PK) ?Step 1: create the
UNIQUE INDEX:Step 2: create the foreign key from
TableTwo: