SQL Server foreign key conflict in a multi values statement?

十年热恋 提交于 2019-12-13 06:39:57

问题


I have a SQL Server INSERT sentence like below:

insert into foo( num, a, b ) values 
(1, a, b), 
(2, a, b), 
...
(9999, a, b);

But there is a "INSERT statement conflicted with the FOREIGN KEY constraint" error. The problem is that SQL Server does not tell me which exactly is the value or line with the problem. How can I quickly find what the value with the error?


回答1:


You can turn this into a SELECT statement to find the rows that do not match.

Assuming that the column a references the table other the following will show the values that are not present in the other table:

select *
from (
  values 
   (1, a, b), 
   (2, a, b), 
    ...
   (9999, a, b)
) t(num,a,b)
where not exists (select 1 
                  from other o 
                  where o.id = t.a);

The select .. from ( values ) requires SQL Server 2012 or newer - but as you have used that tag, you should be able to use that.



来源:https://stackoverflow.com/questions/39274955/sql-server-foreign-key-conflict-in-a-multi-values-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!