INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

前端 未结 14 1101
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:09

I am getting the following error. Could you please help me?

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN

14条回答
  •  盖世英雄少女心
    2020-11-22 12:01

    I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.

    Despite the checked answer being correct:

    Mike M wrote-

    "The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."

    What is missing from this answer is simply;

    You must build the table containing the Primary Key first.

    Another way to say it is;

    You must Insert Data into the parent table, containing the Primary Key, before attempting to insert data into the child table containing the Foreign Key.

    In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.

    If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.

提交回复
热议问题