Sql. How To Reference A Composite Primary Key Oracle?
Solution 1:
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
in your case
createtable Visit_Treat (
TreatCode CHAR(6) constraint cTreatCodeFK references Treatment(TreatCode),
SlotNum NUMBER(2),
DateVisit DATE,
constraint cVisitTreatPK primary key (SlotNum, TreatCode, DateVisit),
constraint fk_slotnumDatevisit FOREIGN KEY(SlotNum,DateVisit)
references Visit(SlotNum,DateVisit)
);
Solution 2:
A foreign key must reference the primary key of the parent table - the entire primary key. In your case, the Visit table's primary key is SlotNum, DateVisit but the foreign key from Visit_Treat only references SlotNum.
You have two good options:
Add a
DateVisitcolumn toVisit_Treatand have the foreign key beSlotNum, DateVisit, referencingSlotNum, DateVisitinVisit.Create a non-business primary key on
Visit(for example a column namedVisitIDof typeNUMBER, fed by a sequence), add aVisitIDcolumn toVisit_Treat, and make that the foreign key.
And two bad options:
Change the
Visitprimary key to be onlySlotNumso yourVisit_Treatforeign key will work. This probably isn't what you want.Don't use a foreign key. I don't recommend this option. If you're having trouble setting up a foreign key that you know should exist, it generally means a design problem.
Post a Comment for "Sql. How To Reference A Composite Primary Key Oracle?"