![](/img/trans.png)
[英]Error: The INSERT statement conflicted with the FOREIGN KEY constraint
[英]How to write a check to avoid the message “INSERT statement conflicted with the FOREIGN KEY constraint”?
我閱讀並理解以下問題中的條目: INSERT語句與FOREIGN KEY約束沖突 。 我確實明白了,但是,在這種情況下,我需要將大約1 Gb的記錄插入到表中,其中一些記錄具有沖突的外鍵。 查詢如下所示:
IF NOT EXISTS (SELECT * FROM [dbo].[tbl_R_TaskHistory] WHERE [TaskID] =
10000529)
BEGIN insert into [dbo].[tbl_History]
([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16
04:53:37.210' AS DateTime)) END
在RequestID上發生沖突,所以我認為必須有一種方法來檢查以避免錯誤消息。 我的觀點是,我希望我的查詢檢查RequestID是否沒有FOREIGN KEY約束,它不會插入此記錄並移動到下一個記錄。
如果您的查詢只包含一行,您可以像這樣展開檢查:
IF NOT EXISTS (SELECT * FROM [dbo].[tbl_R_TaskHistory] WHERE [TaskID] = 10000529) AND EXISTS(SELECT 1 FROM [dbo].[...referencing table...] WHERE [RequestD] = 5738366)
BEGIN
insert into [dbo].[tbl_History] ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16 04:53:37.210' AS DateTime));
END
無論如何,如果要同時插入多行並出於性能考慮,最好將值存儲在緩沖區表中。 像這樣的東西:
insert into #tbl_History ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
values (10000529,'A0000187',NULL,5738366,0,NULL,CAST(N'2011-03-16 04:53:37.210' AS DateTime))
,(...)
,(...)
,(...)
然后,只需對引用表執行內連接:
insert into [dbo].[tbl_History] ([TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed])
SELECT [TaskID],[UserID],[ActD],[RequestD],[No],[SignID],[Completed]
FROM #tbl_History A
INNER JOIN [dbo].[...referencing table...] B
ON A.[RequestD] = B.[RequestD];
這種語法也有效
declare @a int = 5;
declare @b int = 18;
insert into sample (a, b)
select @a, @b
where not exists (select 1 from sample where b = @b)
and exists (select 1 from student where iden = @a)
這避免了創建#temp
insert into sample (a, b)
select a, b
from ( values (5,19)
, (5,30)
, (5,31)
, (5,32)
, (7,41)
, (7,42)
) v(a,b)
where not exists (select 1 from sample where b = v.b)
and exists (select 1 from student where iden = v.a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.