我正在使用 SQL Server 2008。当我尝试创建表“Dossier_Financement”时出现错误:
create table Dossier_Financement
(
ID_Reunion integer foreign key references Reunion(ID_Reunion),
ID_Dossier integer foreign key references Dossier(ID_Dossier),
Decision varchar(20),
Motif text,
Montant_Retenu decimal(6,2),/* montant accorder */
Duree_Retenu smallint,/*nb jours accorder */
Nom_Giac varchar(50) foreign key references GIAC(Nom_Giac),
primary key(ID_Dossier,Nom_Giac,ID_Reunion)
)
GO
这是两个表:
create table Reunion
(
ID_Reunion integer ,
Date_Reunion datetime,
ID_Membre integer,/*jquery*/
Type_Reunion varchar(20),
Nom_Giac varchar(50),
foreign key(ID_Membre,Nom_Giac) references Membre(ID_Membre,Nom_Giac),
primary key(ID_Reunion,Nom_Giac)
)
GO
create table Dossier_Financement
(
ID_Reunion integer foreign key references Reunion(ID_Reunion),
ID_Dossier integer foreign key references Dossier(ID_Dossier),
Decision varchar(20),
Motif text,
Montant_Retenu decimal(6,2),/* montant accorder */
Duree_Retenu smallint,/*nb jours accorder */
Nom_Giac varchar(50) foreign key references GIAC(Nom_Giac),
primary key(ID_Dossier,Nom_Giac,ID_Reunion)
)
GO
'Reunion' 正常执行没有任何问题,但在尝试创建第二个表时出现此错误:
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Reunion' that match the referencing column list in the foreign key 'FK__Dossier_F__ID_Re__5629CD9C'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
最佳答案
根据实际模型需要/要求,一种解决方案是引用 Key,这需要 所有 部分(注意 Nom_Giac
已添加到 FK 定义中):
create table Dossier_Financement
(
...
foreign key(ID_Reunion,Nom_Giac) references Reunion(ID_Reunion,Nom_Giac),
)
根据 Mark M 的回答,另一种解决方案是将 ID_Reunion 列设为键(注意 Nom_Giac
已从 PK 定义中删除):
create table Reunion
(
...
primary key(ID_Reunion)
)
这将使 ID_Reunion 成为一个键(实际上是主键),然后可以使用 foreign key references Reunion(ID_Reunion)
引用它。
编码愉快!
关于SQL 错误 : "There are no primary or candidate keys in the referenced table...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10747204/