Diego Quirós Diego Quirós - 5 months ago 24
SQL Question

SQL Server foreign key conflict in a multi values statement?

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?


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 (
   (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.