添加外键约束



这是两个表:

create table sales.SpecialOfferProduct 
(
SpecialOfferID int not null,
ProductID int not null,
rowguid uniqueidentifier not null,
ModifiedDate datetime not null,
primary key (specialofferid, productid)
)
create table sales.SalesOrderDetail 
(
SalesOrderID int not null,
SalesOrderDetailId int not null,
CarrierTrackingNumber nvarchar(25),
OrderQty smallint not null,
ProductId int not null,
SpecialOfferId int not null,
UnitPrice money not null,
UnitPriceDiscount money not null,
LineTotal as (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty], (0.0))),
rowguid uniqueidentifier not null,
ModifiedDate datetime not null,
primary key (SalesOrderID, SalesOrderDetailId)
)

我正在尝试添加一个外键:

alter table sales.SalesOrderDetail
add foreign key (ProductId) 
references sales.SpecialOfferProduct(ProductId)

我得到这个错误:

Msg 1776, Level 16, State 0, Line 180
在引用表sales中没有主键或候选键。SpecialOfferProduct'匹配外键' fk__salesorder__produc_4e88abd4 '中的引用列列表。

Msg 1750, 16层,状态1,180行
无法创建约束或索引。见前面的错误。

非常简单-外键约束必须始终引用整个表的主键-您不能引用"半"PK".....

因为表上的主键定义为:

create table sales.SpecialOfferProduct 
(
....
primary key (specialofferid, productid)
)

那么显然外键也必须包括列:

alter table sales.SalesOrderDetail
add foreign key (SpecialOfferId, ProductId) 
references sales.SpecialOfferProduct(SpecialOfferId, ProductId)

你的主键有两列,所以它不能用来引用第二个表中的一列。

您可以创建双列引用,也可以仅为ProductId添加新索引:

create index idx_SpecialOfferProduct_ProductID 
on sales.SpecialOfferProduct (ProductID )

然后添加新的外键。

外键必须引用主/从键或唯一索引。请尝试这样做:

alter table sales.SalesOrderDetail
add foreign key (specialofferid, ProductId) 
references sales.SpecialOfferProduct(specialofferid, ProductId)

最新更新