這是兩張表:
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
無法創建約束或索引。請參閱以前的錯誤。
uj5u.com熱心網友回復:
非常簡單 - 外鍵約束必須始終參考表的整個主鍵 - 你不能參考“半個 PK”.....
由于該表上的主鍵定義為:
create table sales.SpecialOfferProduct
(
....
primary key (specialofferid, productid)
)
那么顯然你的外鍵還必須包括兩列:
alter table sales.SalesOrderDetail
add foreign key (SpecialOfferId, ProductId)
references sales.SpecialOfferProduct(SpecialOfferId, ProductId)
uj5u.com熱心網友回復:
您的主鍵有兩列,因此不能僅用于第二個表中的一列參考。
您可以進行雙列參考,也可以僅為以下內容添加新索引ProductId:
create index idx_SpecialOfferProduct_ProductID
on sales.SpecialOfferProduct (ProductID )
然后添加新的外鍵。
uj5u.com熱心網友回復:
外鍵必須參考主鍵/輔助鍵或唯一索引。請嘗試這樣的事情:
alter table sales.SalesOrderDetail
add foreign key (specialofferid, ProductId)
references sales.SpecialOfferProduct(specialofferid, ProductId)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/492697.html
