簡體   English   中英

添加外鍵約束

[英]Add foreign key constraint

這是兩張表:

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)

我收到此錯誤:

消息 1776,第 16 級,狀態 0,第 180 行
引用表 'sales.SpecialOfferProduct' 中沒有與外鍵 'FK__SalesOrde__Produ__4E88ABD4' 中的引用列列表匹配的主鍵或候選鍵。

消息 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM