简体   繁体   English

将外键约束添加到具有现有数据的表的主键列中

[英]adding a foreign key constraint to a primary key column of a table with existing data

I'm trying to add in a foreign key constraint on a newly created column of an existing table(table A) and the primary key column of a newly created table (table B). 我正在尝试在现有表(表A)的新创建列和新表(表B)的主键列上添加外键约束。 This is on sql server 2008. When I add in the relationship the Alter table script fails. 这是在sql server 2008上。当我添加关系时,Alter table脚本失败。 I have also made the new column created on table A to allow nulls. 我还创建了在表A上创建的新列以允许为空。 However when I try to save with NO on Check Existing data - I'm able to save the relationship. 但是,当我尝试对“检查现有数据”使用“否”进行保存时-我能够保存该关系。 Is this a good way of creating foreign key constraint on existing data, or should I create a new table (table c) mimicking a many to many relationship instead of adding the new column to table A,which will enable me to create my foreign key constraints without having to specify "No Check" on existing data, although the actual relationship is one to many. 这是在现有数据上创建外键约束的好方法,还是应该创建一个模拟多对多关系的新表(表c),而不是将新列添加到表A中,这将使我能够创建外键约束,而不必在现有数据上指定“不检查”,尽管实际关系是一对多的。

Yes, you can do that by making Checking Existing Data On Creation Or Re-Enabling = No 是的,您可以通过Checking Existing Data On Creation Or Re-Enabling = No来做到这一点

If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK 如果您不想针对现有数据验证新的CHECK或FOREIGN KEY约束,请使用WITH NOCHECK

创建时检查现有数据

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

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