![](/img/trans.png)
[英]SQL Server table creation error : There are no primary or candidate keys in the referenced
[英]SQL ERROR : “There are no primary or candidate keys in the referenced table…”
我正在使用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.
您只能使用要引用的表的完整主鍵創建外鍵。 您的第二個表嘗試僅使用Reunion表的主鍵的一半來創建外鍵。
根據實際的模型需求/要求,一個解決方案是引用Key,它需要所有部分(注意Nom_Giac
被添加到FK定義中):
create table Dossier_Financement
(
...
foreign key(ID_Reunion,Nom_Giac) references Reunion(ID_Reunion,Nom_Giac),
)
根據Mark M的回答,另一個解決方案是將ID_Reunion列設為Key(請注意Nom_Giac
已從PK定義中刪除):
create table Reunion
(
...
primary key(ID_Reunion)
)
這將使ID_Reunion成為Key(實際上是主鍵),然后可以使用foreign key references Reunion(ID_Reunion)
。
快樂的編碼!
在要創建索引的列上創建唯一索引:
CREATE UNIQUE NONCLUSTERED INDEX [UX_Index] ON dbo.[Table]([Column1],[Column2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.