列级FOREIGN KEY约束

时间:2018-02-08 10:19:12

标签: sql sql-server

我正在为我的学校做一个数据库项目,我偶然发现了一个我似乎无法解决的奇怪问题。这是我在尝试创建表时的代码:

Create table Offering(
StartDate       DATE            NOT NULL    ,       
PRIMARY KEY(StartDate) 
);

Create table OfferPerWeek(
StartDate       DATE            NOT NULL    ,
StartTime       TIME(0)         NOT NULL    ,
[Day]           VARCHAR(10)     NOT NULL
PRIMARY KEY (StartDate,[Day],StartTime)
FOREIGN KEY (StartDate) 
REFERENCES Offering(StartDate)
);

--The table that have the issues 
Create table OfferPerWeek_Venue(  
[Day]           VARCHAR(10)     NOT NULL    ,
StartDate       DATE            NOT NULL    , 
StartTime       TIME(0)         NOT NULL    
PRIMARY KEY (StartDate, [Day], StartTime)
FOREIGN KEY (StartDate, [Day], StartTime) 
REFERENCES OfferPerWeek (StartDate, [Day] , StartTime)
);

错误消息说:

  

在列级FOREIGN KEY约束

中指定了多个键

我对这个问题感到很困惑,我试图创建多个外键,引用父表的那么多主键。

真的希望这可以修复,谢谢

2 个答案:

答案 0 :(得分:3)

您缺少逗号。尝试:

Create table OfferPerWeek_Venue(  
[Day]           VARCHAR(10)     NOT NULL    ,
StartDate       DATE            NOT NULL    , 
StartTime       TIME(0)         NOT NULL , <-- comma there  
PRIMARY KEY (StartDate, [Day], StartTime), <-- comma there
FOREIGN KEY (StartDate, [Day], StartTime) 
REFERENCES OfferPerWeek (StartDate, [Day] , StartTime)
);

您可以尝试以下命名,命名外键:

Create table OfferPerWeek_Venue(  
[Day]           VARCHAR(10)     NOT NULL    ,
StartDate       DATE            NOT NULL    , 
StartTime       TIME(0)         NOT NULL ,  
CONSTRAINT [PK_GoodName] PRIMARY KEY (StartDate, [Day], StartTime), 
CONSTRAINT [FK_GoodName] FOREIGN KEY (StartDate, [Day], StartTime) 
REFERENCES OfferPerWeek (StartDate, [Day] , StartTime)
);

答案 1 :(得分:1)

CREATE TABLE语句在每个CONSTRAINT

之前缺少逗号