Skip to content
Advertisement

The INSERT statement conflicted with the FOREIGN KEY constraint “FK__…”

I’m a very new beginner with SQL and I’m battling a problem I can’t seem to find the answer to. I’ve found similar questions here on Stack Overflow but I still can’t see what I’m supposed to change in my code to make it work.

I’ve got 4 tables in a relation as follows:

Then, I’ve got three procedures that are returning the identity value primary key for DeviceLocation, TempHumidSensor, LightSensor before inserting in to DeviceMessage, as follows:

GetDeviceLocation

GetLightSensor

GetTempHumidSensor

Finally, there’s the SaveSqlData procedure that is called upon by .NET code in the end.

I usually test this procedure with this snippet:

The error that shows both when this method is invoked from C# and by the test call above says:

I’ve read that it has to do with the order of inserts, but I’m not sure how to fix it or where the problem lies exactly.

I can see that there are inserts to all tables except for DeviceMessage, when this error occures. Any help is vastly appreciated.

Advertisement

Answer

You can see the problem by putting a diagnostic SELECT @DeviceLocationId etc in SaveSqlData – you will get zeroes.

The way you’re getting the Ids back from your Get sprocs doesn’t work. Each sproc SELECTs the id, but the caller (the EXEC in SaveSqlData) expects a return value.

Change your Get sprocs to RETURN the id, eg:

Note you also have a typo in SaveSqlData, the column in DeviceMessage is named TempSensorId not TempHumidSensorId.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement