SQL Server: adding foreign key on multiple columns

不想你离开。 提交于 2020-01-14 22:39:37

问题


I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error.

I'm using SQL Server with Microsoft SQL Server Management Studio.

Here's what I do:

CREATE TABLE House 
(
    hid         INTEGER         PRIMARY KEY,
    hname       VARCHAR(32)     NOT NULL,
    address     VARCHAR(128)    NOT NULL,
);

CREATE TABLE Room 
(
    sid         INTEGER,
    hid         INTEGER         FOREIGN KEY REFERENCES House(hid),
    rname       VARCHAR(32)     NOT NULL,

    CONSTRAINT sid_pk PRIMARY KEY(sid, hid)
);

CREATE TABLE Seat 
(
    hid         INTEGER,
    sid         INTEGER,
    plid        INTEGER,
    row         INTEGER         NOT NULL,
    seat        INTEGER         NOT NULL,

    CONSTRAINT sid_fk 
        FOREIGN KEY (hid, sid) REFERENCES Room(hid, sid), <-- Here's the error
    CONSTRAINT plid_pk 
        PRIMARY KEY (hid, sid, plid),

    UNIQUE(hid, sid, row, seat)
);

And I keep getting "Error 1776" saying that there is no primary key in the room-table...


回答1:


as per comments from @hogan..posting as community wiki,so that this is not lost

In the Room table ,primary key is (sid, hid)..But in seat table,you are referencing a new primary key Room(hid, sid)

so change your room table constraint definition like below

CONSTRAINT sid_fk FOREIGN KEY (hid, sid) REFERENCES Room(sid,hid)



来源:https://stackoverflow.com/questions/41305693/sql-server-adding-foreign-key-on-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!