Search code examples
sql-serverweak-entity

There are no primary or candidate keys in the referenced table 'Card' that match the referencing column list in the foreign key


Create table scripts:

Create Table [Card]
(
    GiveDate Date not null, 
    PN nvarchar(50) not null, 
    FOREIGN KEY (PN) REFERENCES Patient (PN),
    PRIMARY KEY (GiveDate,PN)
)

Create table [Registration]
(
    EntryDate Date not null,
    ExitDate Date, 
    RoomId int not null,
    CardGiveDate date not null, 
    PN nvarchar(50) not null,
    PRIMARY KEY (PN, EntryDate, CardGiveDate),
    FOREIGN KEY (PN, CardGiveDate) REFERENCES [Card](PN, GiveDate)
)

I looked at this but it doesn't help me.

Card table has primary key


Solution

  • The PK in Card is (GiveDate, PN) , but your FK references a key (PN, GiveDate) - the order of the columns must match! So try this in your Registration table:

    Create table [Registration]
    (
        EntryDate Date not null,
        ExitDate Date, 
        RoomId int not null,
        CardGiveDate date not null, 
        PN nvarchar(50) not null,
        PRIMARY KEY (PN, EntryDate, CardGiveDate),
        -- make sure to specify the columns in the same order as they are defined in the referenced table!
        FOREIGN KEY (PN, CardGiveDate) REFERENCES [Card](GiveDate, PN)
    )