批量插入中忽略外键约束

ker*_*ger 6 sql sql-server foreign-keys

我想批量插入大量生成的数据,这些数据具有循环依赖关系(每个表中的列是外键约束到另一个表).为了解决这个问题,我想关闭外键约束,插入数据,然后重新打开约束.

谷歌搜索,我找到了一堆解决方案,但没有一个工作.现在我有:

ALTER TABLE TableName NOCHECK CONSTRAINT ALL
Run Code Online (Sandbox Code Playgroud)

该命令运行并且不会产生任何错误,但是当我尝试清除表以准备插入数据时,我收到以下错误:

System.Data:0:in `OnError': The DELETE statement conflicted with the REFERENCE constraint "FK_1_2_ConstraintName". The conflict occurred in database "DatabaseName", table "dbo.SomeOtherTable", column 'PrimaryKey'.\r\nThe statement has been terminated.\r\nChecking identity information: current identity value '0', current column value '0'.\r\nDBCC execution completed. If DBCC printed error messages, contact your system administrator. (System::Data::SqlClient::SqlException)
Run Code Online (Sandbox Code Playgroud)

我目前的理论是,这是由另一个表上的外键约束引起的,这取决于要更改的表.

我可以针对这个问题提出两种解决方案:

  1. 浏览所有依赖于我正在插入的表的表并禁用它们的外键约束.这似乎不必要地复杂化.

  2. 禁用数据库中所有表的外键约束.

两种解决方案都可行,但我不确定从哪个解决方案开始.有任何想法吗?

Eri*_*icZ 11

这就是我用于这种工作的东西.

--Disable all Constraints 
exec sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 

-- INSERT DATA HERE

--Enable all Constraints 
exec sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 
Run Code Online (Sandbox Code Playgroud)