简体   繁体   English

如何将外键添加到SQL Server 2012中的现有列

[英]How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query 我正在尝试使用以下查询将外键添加到现有列中

ALTER TABLE Sub_Category_Master 
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)

but I'm getting an error 但我遇到一个错误

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". ALTER TABLE语句与FOREIGN KEY约束“ FK__Sub_Categ__Categ__5812160E”发生冲突。 The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'. 在数据库“ shaadikarbefikar_new”的表“ shaadikarbefikar.Category_Master”的列“ Category_ID”中发生了冲突。

Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID ). 很好,该错误清楚地告诉您Sub_Category_Master表中的Category_ID包含一些在Category_Master不存在的值(列Category_ID )。 But that's exactly the point of having a foreign key constraint - making sure your child table ( Sub_Category_Master ) only uses defined values from its parent table. 但这正是具有外键约束的关键-确保子表( Sub_Category_Master )仅使用其父表中的已定义值。

Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. 因此,在能够建立此外键关系之前,必须首先修复那些“伏都教”值。 I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E : 我也强烈建议您自己明确命名该约束,以避免那些系统生成的但不是非常有用的约束名称,例如FK__Sub_Categ__Categ__5812160E

ALTER TABLE Sub_Category_Master 
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
    FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
    REFERENCES  Category_Master(Category_ID);
CREATE TABLE Orders 
(
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),

    CONSTRAINT FK_PersonOrder 
        FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM