简体   繁体   English

在SQL Server中添加外键约束的问题?

[英]Issues with adding foreign key constraint in SQL Server?

I am using SQL Server, and I need to add a foreign key to an already existing table. 我正在使用SQL Server,我需要将一个外键添加到现有的表中。

The issue is the column which will act as the foreign key already has a few inconsistent values (which do not occur as a primary key) in another table. 问题是作为外键的列已经在另一个表中具有一些不一致的值(不作为主键出现)。

I was wondering, when I alter the table and add the foreign key constraint, what will happen to the rows in the table with foreign key constraint , which has inconsistent values?? 我想知道,当我改变表并添加外键约束时,表中的行会发生什么外键约束,它具有不一致的值?

--Neeraj --Neeraj

In this case it is your decision. 在这种情况下,这是你的决定。 You can leave this values in table using WITH NOCHECK clause. 您可以使用WITH NOCHECK子句将此值保留在表中。 But all new inserted values will be checked. 但是将检查所有新插入的值。

You'll get an error and nothing will be inserted. 您将收到错误,不会插入任何内容。

To find all inconsistent rows (supposing that A and B are the target tables, A.id is a parent key and B.fk_id is a child, foreign key, id): 要查找所有不一致的行(假设AB是目标表,则A.id是父键, B.fk_id是子,外键,id)​​:

   SELECT B.fk_id
     FROM B
LEFT JOIN A ON A.id = B.fk_id
    WHERE A.id IS NULL

After executing it you'll have all child rows that refers to "nowhere". 执行它之后,您将拥有所有引用“无处”的子行。 So you either need to remove them, modify to point to the existing rows or set B.fk_id to NULL (if there is no NOT NULL constraint). 因此,您需要删除它们,修改为指向现有行或将B.fk_id设置为NULL (如果没有NOT NULL约束)。

And after that query returns 0 rows - you can safely create foreign key constraint without any magic options. 在该查询返回0行之后 - 您可以安全地创建外键约束而无需任何魔术选项。

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

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