我有以下SQL代码,通过比较两个表中的数据将数据从一个表插入另一个表。目标表中的PK为[bomItem], [bomRev], [bomEntry]
。
如果ItemID in source table = bomItem field in Dest. table
AND [rev](field in Source tbl)NOT=[bomRev](in destination tbl)
,我想插入。
当我尝试运行脚本时,我收到以下错误
Msg 547,Level 16,State 0,Line 46 INSERT语句与FOREIGN KEY约束“FK_MIBOMD_MIBOMH”冲突。冲突发生在数据库“MITESTCO”,表“dbo.MIBOMH”中。 声明已经终止。
USE [MITESTCO];
GO
INSERT INTO [MIBOMD]
([bomItem], [bomRev], [bomEntry], [partId], [qty],[lead])
SELECT [ItemID], [rev], [bomEntry], [partid], [qty],[lead]
FROM [assy]
WHERE [rev] IN (SELECT [bomRev] FROM [MIBOMH])
AND [ItemID] IN (SELECT [bomItem] FROM [MIBOMH])
AND [ItemID] IN (SELECT [ItemID] FROM [MIITEM])
AND [partid] IN (SELECT [ItemID] FROM [MIITEM]);
答案 0 :(得分:0)
禁用数据库中的所有约束 -
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
-- Insert data
重新开启 -
exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"