简体   繁体   English

添加外键约束

[英]Add foreign key constraint

Those are the two tables:这是两张表:

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

I'm trying to add a foreign key :我正在尝试添加外键:

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

I get this error :我收到此错误:

Msg 1776, Level 16, State 0, Line 180消息 1776,第 16 级,状态 0,第 180 行
There are no primary or candidate keys in the referenced table 'sales.SpecialOfferProduct' that match the referencing column list in the foreign key 'FK__SalesOrde__Produ__4E88ABD4'.引用表 'sales.SpecialOfferProduct' 中没有与外键 'FK__SalesOrde__Produ__4E88ABD4' 中的引用列列表匹配的主键或候选键。

Msg 1750, Level 16, State 1, Line 180消息 1750,第 16 层,状态 1,第 180 行
Could not create constraint or index.无法创建约束或索引。 See previous errors.请参阅以前的错误。

Very simple - a foreign key constraint must always reference the whole primary key of the table - you cannot reference "half a PK".....非常简单 - 外键约束必须始终引用表的整个主键 - 你不能引用“半个 PK”.....

Since your primary key on that table is defined as:由于该表上的主键定义为:

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

then obviously your foreign key must also include BOTH columns:那么显然你的外键还必须包括列:

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

Your primary key has two columns so it can't be used to reference by just one column from the second table.您的主键有两列,因此不能仅用于第二个表中的一列引用。

You can either make a dual column reference, or you add a new index for only ProductId :您可以进行双列引用,也可以仅为ProductId添加新索引:

create index idx_SpecialOfferProduct_ProductID 
on sales.SpecialOfferProduct (ProductID )

And then add the new foreign key as you have it.然后添加新的外键。

Foreign key must reference on primary/secondary keys or unique index.外键必须引用主键/辅助键或唯一索引。 Please, try something like this:请尝试这样的事情:

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