Меню

Ошибка the insert statement conflicted with the foreign key constraint

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 KEY constraint «FK_Sup_Item_Sup_Item_Cat». The conflict occurred in database «dev_bo», table «dbo.Sup_Item_Cat». The statement has been terminated.

Code:

insert into sup_item (supplier_id, sup_item_id, name, sup_item_cat_id, 
                      status_code, last_modified_user_id, last_modified_timestamp, client_id)   
values (10162425, 10, 'jaiso', '123123',
        'a', '12', '2010-12-12', '1062425')

The last column client_id is causing the error. I tried to put the value which already exists in the dbo.Sup_Item_Cat into the column, corresponding to the sup_item.. but no joy 🙁

DineshDB's user avatar

DineshDB

5,9426 gold badges32 silver badges47 bronze badges

asked Jun 3, 2010 at 12:24

SmartestVEGA's user avatar

SmartestVEGASmartestVEGA

8,09924 gold badges83 silver badges134 bronze badges

3

In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. 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.

If you have SQL Server Management Studio, open it up and sp_helpdbo.Sup_Item_Cat‘. See which column that FK is on, and which column of which table it references. You’re inserting some bad data.

Let me know if you need anything explained better!

Danny Fardy Jhonston Bermúdez's user avatar

answered Jun 3, 2010 at 12:29

Mike M.'s user avatar

3

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.

Community's user avatar

answered Jan 17, 2014 at 20:50

plasmasnakeneo's user avatar

plasmasnakeneoplasmasnakeneo

2,1511 gold badge13 silver badges16 bronze badges

2

You are trying to insert a record with a value in the foreign key column that doesn’t exist in the foreign table.

For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.

Katianie's user avatar

Katianie

5761 gold badge9 silver badges35 bronze badges

answered Jun 3, 2010 at 12:31

Matthew Smith's user avatar

2

You’ll need to post your statement for more clarification. But…

That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.

Micky's user avatar

Micky

3351 gold badge4 silver badges13 bronze badges

answered Jun 3, 2010 at 12:27

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

240k40 gold badges405 silver badges535 bronze badges

The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id

I would run

sp_helpconstraint sup_item

and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides ‘123123’ looks suspect as well.

answered Jun 3, 2010 at 12:44

Cobusve's user avatar

CobusveCobusve

1,56210 silver badges23 bronze badges

Something I found was that all the fields have to match EXACTLY.

For example, sending ‘cat dog’ is not the same as sending ‘catdog’.

What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the «Foreign Key» that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.

Once I fixed the 2 fields giving my problems, life was good!

If you need a better explanation, let me know.

answered May 30, 2014 at 21:06

John Waclawski's user avatar

John WaclawskiJohn Waclawski

8961 gold badge10 silver badges20 bronze badges

1

I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.

The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.

I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.

Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!

answered Oct 23, 2015 at 13:40

mns's user avatar

Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.

answered Jan 6, 2014 at 19:27

user1424678's user avatar

  1. run sp_helpconstraint
  2. pay ATTENTION to the constraint_keys column returned for the foreign key

answered Apr 12, 2014 at 16:20

dotnet's user avatar

I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.

answered May 14, 2014 at 19:12

Paulie22's user avatar

Paulie22Paulie22

1111 gold badge1 silver badge8 bronze badges

Parent table data missing causes the problem.
In your problem non availability of data in «dbo.Sup_Item_Cat» causes the problem

answered Mar 5, 2015 at 12:11

sathish's user avatar

I also got the same error in my SQL Code, This solution works for me,


Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.

answered Dec 12, 2018 at 7:19

Chandan Kumar's user avatar

The problem was reproducible and intermittent for me using mybatis.
I’m sure I had correct DB configuration (PK, FK, auto increment etc)
I’m sure I had correct order of insertions (parent records first), in debug I could see parent record inserted with respective PK and just after that next statement failed with inserting child record with correct FK inside.

The problem was fixed by for reseeding identity with

DBCC CHECKIDENT ('schema.customer', RESEED, 0);
DBCC CHECKIDENT ('schema.account', RESEED, 0);

Exactly the same code that failed before started to work.
I would like somebody to explain me what was causing the issue.

answered Apr 28, 2021 at 22:12

Mike's user avatar

MikeMike

19.3k25 gold badges95 silver badges130 bronze badges

In my case, I was inserting the values into the child table in the wrong order:

For the table with 2 columns: column1 and column2, I got this error when I mistakenly entered:

INSERT INTO Table VALUES('column2_value', 'column1_value');

The error was resolved when I used the below format:-

INSERT INTO Table (column2, column1) VALUES('column2_value', 'column1_value');

Pawel Veselov's user avatar

answered Sep 12, 2020 at 6:45

Xplorer's user avatar

If your FK column table should contain that FK value as a primary key Value then data will be inserted.

answered Jan 14, 2021 at 17:53

Harry's user avatar

HarryHarry

297 bronze badges

February 5, 2019
MSSQL, TSQL

You can get this error when you want to inset data into a table that has the Foreing Key. It means that there is no relevant record in the Primary table that Foreign Key is linked to. The record must first be added to the primary table.

Let’s make an example for a better understanding.

Example:

We create two tables as follows. In the Person table we set the ID column as Primary Key.

CREATE TABLE [dbo].[Person](

[ID] [int] IDENTITY(1,1) NOT NULL,

[Name] [varchar](50) NULL,

CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED

(

[ID] ASC

)

) ON [PRIMARY]

GO

CREATE TABLE [dbo].[PersonDetails](

[ID] [int] IDENTITY(1,1) NOT NULL,

[PersonID] int NOT NULL,

[SurName] [varchar](50) NULL,

[Age] int

) ON [PRIMARY]

GO

Now let’s set the PersonID column in the PersonDetails table as the Foreign Key of the Primary Key in the Person table.

ALTER TABLE [dbo].[PersonDetails]  WITH CHECK ADD  CONSTRAINT [FK_PersonDetails_Person] FOREIGN KEY([PersonID])

REFERENCES [dbo].[Person] ([ID])

GO

ALTER TABLE [dbo].[PersonDetails] CHECK CONSTRAINT [FK_PersonDetails_Person]

GO

Then, when there is no record in the Primary table, try to add a record to the Foreign table.

USE [TestDB]

GO

INSERT INTO [dbo].[PersonDetails] ([PersonID],[SurName],[Age]) VALUES (1,‘CAKIR’,34)

GO

We’ll get the error as follows. Because the Primary table does not have the corresponding ID value.

Msg 547, Level 16, State 0, Line 3

The INSERT statement conflicted with the FOREIGN KEY constraint “FK_PersonDetails_Person”.

The conflict occurred in database “TestDB”, table “dbo.Person”, column ‘ID’.

The statement has been terminated.

If we add a record to the primary table first, the process of adding records to the foreign table will also be completed successfully.

USE [TestDB]

GO

INSERT INTO [dbo].[Person] ([ID],[Name]) VALUES (1,‘Nurullah’)

GO

INSERT INTO [dbo].[PersonDetails] ([PersonID],[SurName],[Age]) VALUES (1,‘CAKIR’,34)

GO

  • Remove From My Forums
  • Question

  • Background:

    (1) generate a trace file by SQL profiler 2005

    (2) replay a trace file by SQL profiler 2016

    (3) Found many errors about «INSERT statement conflicted with FOREIGN KEY constraint»

    [Microsoft][SQL Server Native Client 11.0][SQL Server]The INSERT statement conflicted with the FOREIGN KEY constraint «FK_TEST1». The conflict occurred in database «TESTDB», table «dbo.TEST2», column ‘TEST2_No’. (State
    23000) (Code 547)
    [Microsoft][SQL Server Native Client 11.0][SQL Server]The statement has been terminated. (State 01000) (Code 3621)

    (4) Check the database and confirm no conflict of foreign key in SQL server 2017

    Question:

    Is it a compatibility between 2005 and 2016?  Please advise.  Thanks!

    Ming

I am wanting to add insert into my uspInsertUserRoles procedure:

CREATE PROCEDURE [dbo].[uspInsertUserRoles]
    @RoleID INT,
    @UserID INT
    AS
    BEGIN
        INSERT INTO tblUserRoles(RoleID, UserID)
        VALUES (@RoleID,@ UserID)
    END
GO

Table:

CREATE TABLE [dbo].[tblUserRoles](
    [UserRoleID] [int] IDENTITY(1,1) NOT NULL,
    [UserID] [int] NOT NULL,
    [RoleID] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [UserRoleID] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblUserRoles]  WITH CHECK ADD FOREIGN KEY([RoleID])
REFERENCES [dbo].[tblRoles] ([RoleID])
GO

ALTER TABLE [dbo].[tblUserRoles]  WITH CHECK ADD FOREIGN KEY([UserID])
REFERENCES [dbo].[tblUsers] ([UserID])
GO

This is my code:

Private Sub btnInsertUserRole_Click(sender As Object, e As EventArgs) Handles btnInsertUserRole.Click
        sqlCon = New SqlConnection(strConn)

        Using (sqlCon)
            Dim sqlComm As New SqlCommand()
            Dim msg As String = "EXEC sp_addrolemember '" & storedRoleDesc & "','" & storedUserName & "'"
            MessageBox.Show(msg)
            sqlComm.Connection = sqlCon
            sqlComm.CommandText = "uspInsertUserRoles"
            sqlComm.CommandType = CommandType.StoredProcedure

            sqlComm.Parameters.AddWithValue("UserID", storedUserID)
            sqlComm.Parameters.AddWithValue("RoleID", storedRoleID)

            sqlCon.Open()
            'sqlComm.ExecuteNonQuery()

            Dim rowsAffected As Integer = sqlComm.ExecuteNonQuery()
            MessageBox.Show(rowsAffected)
            If rowsAffected > 0 Then
                MessageBox.Show("Record has been inserted successfully")
            End If

Gives me error:

System.Data.SqlClient.SqlException: ‘The INSERT statement conflicted with the FOREIGN KEY constraint «FK__tblUserRo__UserI__51300E55». The conflict occurred in database «THISONE», table «dbo.tblUsers», column ‘UserID’.
The statement has been terminated.’

My tblUsers:

CREATE TABLE tblUsers(
        UserID INT IDENTITY(1,1),
        FirstName varchar(50) NOT NULL,
        LastName varchar(50) NOT NULL,
        Age int NOT NULL,
        UserName varchar(50) NOT NULL,
        Password varchar(50) NOT NULL,
        PRIMARY KEY (UserID),
        UNIQUE(UserName)
        )

azhty

0 / 0 / 0

Регистрация: 10.03.2017

Сообщений: 4

1

22.05.2017, 21:17. Показов 34515. Ответов 28

Метки нет (Все метки)


Конфликт инструкции INSERT с ограничением FOREIGN KEY «FK_komnaty_klienty». Конфликт произошел в базе данных «Gostinitca», таблица «dbo.klienty», column ‘Kod_klienta’.
Создана БД на SQL Server,выбраны первичные ключи во всех таблицах. БД подключена к visual studio(asp.net). Добавлена таблица в GridView. Нужно добавлять новые данные в таблицу, но при нажатии на кнопку Добавить выходит данная ошибка, и ругается на db.SubmitChanges();Вот весь код кнопки Добавить.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        protected void Button1_Click(object sender, EventArgs e)
    {
        KlietydbDataContext db = new KlietydbDataContext();
        klienty tebl = new klienty();
        tebl.Familiya = TextBox1.Text;
        tebl.Imya = TextBox2.Text;
        tebl.Otchectvo = TextBox3.Text;
        tebl.Nomer_komnaty = Convert.ToInt32(TextBox4.Text);
        tebl.Vid_dokumenta = TextBox5.Text;
        tebl.Nomer_dokumenta = TextBox6.Text;
        tebl.Mesto_zitelstva = TextBox7.Text;
        tebl.Plata_za_prozivanie = Convert.ToDecimal(TextBox10.Text);
        db.klienty.InsertOnSubmit(tebl);
      db.SubmitChanges(); //здесь
        Response.Redirect("/Klienty.aspx");
 
    }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

22.05.2017, 22:09

2

Ну скорее всего добавляете запись, которой не существует в таблице, на которую ссылается внешний ключ.



0



635 / 522 / 322

Регистрация: 20.05.2015

Сообщений: 1,455

23.05.2017, 09:35

3

Судя по всему код клиента хоть и первичный ключ, но не автоинкриминтируемый(если это так его либо надо прописывать вручную, либо выставлять автоинкремент на стороне базы).



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

29.01.2018, 13:00

4

Цитата
Сообщение от hoolygan
Посмотреть сообщение

Ну скорее всего добавляете запись, которой не существует в таблице, на которую ссылается внешний ключ.

А можно ли как-нибудь разрешить ссылаться на несуществующую запись?



0



359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

29.01.2018, 14:15

5

Leslov, Вариантов у Вас несколько.
1. Удалить внешний ключ, т.е. перестать ссылаться на запись в другой таблице. Это повлечет возможные проблемы с логической целостностью данных. Не зря же ввели внешний ключ для этих целей.
2. Перед вставкой в таблицу, что требует проверки внешнего ключа — вставлять данные в «главную» таблицу, и брать с неё ключ для вставки в «slave»-табличку.



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

29.01.2018, 14:45

6

hoolygan, то есть, если и ссылаться, то только на уже существующую запись в таблице?

Допустим есть две таблицы: Documents (D) и Organizations (O). Одно из полей таблицы D ссылается на первичный ключ таблицы O. В качестве первичного ключа выступает GUID, причем не генерируемый автоматически, он всегда указывается явно при добавлении записи в таблицу.
При добавлении записи в таблицу D нам известен GUID организации, записи которого может не быть в таблице O. Идея в том, чтобы заполнять недостающие данные об организации уже после добавления документа, временно ссылаясь на отсутствующую запись.
Реализуемо ли это?



0



647 / 582 / 170

Регистрация: 17.07.2012

Сообщений: 1,648

Записей в блоге: 1

29.01.2018, 15:49

7

Leslov, так делать нельзя, ибо это приводит к неконсистентности данных в БД. Либо заливайте все данные в транзакции, либо создавайте пустые записи в связанной таблице, и потом уже заполняйте все поля при помощи UPDATE/MERGE



1



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

29.01.2018, 16:10

8

Leslov, внешний ключ имеет право ссылаться ни на что (null). Для этого его нужно создать со специальной настройкой.



0



647 / 582 / 170

Регистрация: 17.07.2012

Сообщений: 1,648

Записей в блоге: 1

29.01.2018, 16:20

9

Цитата
Сообщение от Usaga
Посмотреть сообщение

внешний ключ имеет право ссылаться ни на что (null). Для этого его нужно создать со специальной настройкой.

Ну ссылаться ни на что (NULL) и ссылаться на несуществующий PK — разные вещи.



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

29.01.2018, 16:30

10

Cupko, я это понимаю и мой совет этому не противоречит.



0



Leslov

3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

12.02.2018, 12:41

11

Нашел решение, подойдет для тех, кто использует миграции для обновления БД. Перед применением изменений нужно изменить файл миграции дописав строчку

C#
1
Sql("ALTER TABLE dbo.Users NOCHECK CONSTRAINT [FK_dbo.Users_dbo.Roles_RoleID]");

где
Users — основная таблица
Roles — таблица, на которую ссылается Users
RoleID — поле в таблице Users



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

12.02.2018, 14:04

12

Leslov, вы осознаёте эффект от работы NOCHECK CONSTRAINT?



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

12.02.2018, 14:16

13

Usaga, нет. Какие-нибудь подводные камни?



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

12.02.2018, 14:17

14

Leslov, так вы отключаете проверку ограничения при вставке и обновлении данных, что легко приведёт к повреждению данных. Не надо так делать. Это для самых запущенных случаев, когда по другому просто никак.



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

12.02.2018, 14:47

15

Цитата
Сообщение от Usaga
Посмотреть сообщение

что легко приведёт к повреждению данных.

Можно какой-нибудь простой пример? Пока планирую использовать этот вариант, т.к. более изящного решения не нашел.



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

12.02.2018, 14:54

16

Leslov, какой пример? Записи несуществующего идентификатора?)

Цитата
Сообщение от Leslov
Посмотреть сообщение

более изящного решения не нашел.

Изящное решение простое: записывать данные, когда все зависимости в базе уже существуют.



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

12.02.2018, 15:35

17

Usaga, хорошо. Приведу пример.
Дано:
Список документов с сервера (в виде xml), каждый из которых содержит в себе идентификатор организации (по этому идентификатору можно отдельно запросить данные).
Пустая база данных
Снятое ограничение для внешнего ключа.
Необходимо:
Сохранить в базу все полученные документы и данные об организации в двух таблицах
Решение:
Полученный xml парсим в соответствующую модель и сохраняем в базу данных. Ссылки на существующие организации будут проставлены автоматически, если в соответствующей таблице будет найдена запись с необходимым идентификатором. Далее, составляем список идентификаторов организаций отсутствующих в базе и запрашиваем их поочередно с сервера, после чего сохраняем в базу данных.

Что бы вы изменили в этом примере?



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

12.02.2018, 15:43

18

Цитата
Сообщение от Leslov
Посмотреть сообщение

Что бы вы изменили в этом примере?

Я бы восстанавливал весь граф зависимостей ДО сохранения в базу, раз есть такая техническая возможность. Т.е. лез бы в базу, смотрел наличие в ней необходимых зависимостей и, в случае наличия, сохранял бы или запрашивал недостающее, сохранял, а потом уже заносил остальное. Т.е. в любой момент в базе были бы корректные данные.



0



3 / 3 / 0

Регистрация: 13.10.2016

Сообщений: 48

12.02.2018, 15:48

19

А как быть в случае если будут проблемы с сервером, например отсутствие ответа на запрос? Не сохранять документ без организации и выводить пользователю частичные данные? Тем более если это будет случай, когда отсутствие данных об организации менее критично, чем отсутствие какого-либо документа в базе.



0



Эксперт .NET

11043 / 7599 / 1176

Регистрация: 21.01.2016

Сообщений: 28,580

12.02.2018, 15:50

20

Цитата
Сообщение от Leslov
Посмотреть сообщение

А как быть в случае если будут проблемы с сервером, например отсутствие ответа на запрос

Тогда данные сохранять нельзя, ибо они неполные и тупо повреждённые. За вами выбор: информировать пользователя или молча повредить данные и в базе.



0



as you say you have two tables….
so you have to fire insert query in primary key table first and get a identity value means newly added records primary key and then after completion of that process you have to fire second insert query with inserting a value in the FOREIGN key that is the out putted primary key from the first insert query…

IF YOU USE A STORE PROCEDURE THEN USE QUERY LIKE THIS….

INSERT INTO "FIRSTTABLE" (YOUR COLUMN LIST) VALUES (VALUES TO BE INSERTED)

DECLARE @IDENTITY INT 
INSERT INTO TABLE1(USERNAME,PASSWORD) VALUES ('test','test')
SELECT @IDENTITY =  @@IDENTITY FROM TABLE1
INSERT INTO TABLE2(USERID,FIRSTNAME,LASTNAME,MOBILENO) VALUES (@IDENTITY,'test','test','xxxx')
SELECT * FROM TABLE1
SELECT * FROM TABLE2

OR IF YOU NOT USE A STORE PROCEDURE AND USE ONLY TEXT QUERY THEN USE THIS…

INSERT INTO USERDETAIL(USERNAME,PASSWORD) VALUES ('test','test')


SELECT TOP 1 ID FROM USERDETAIL ORDER BY ID DESC

SELECT MAX(ID) FROM USERDETAIL



INSERT INTO USERPERSONALDETAIL(USERID,FIRSTNAME,LASTNAME,MOBILENO) VALUES ('your select query data','test','test','xxxx')

you have to tack care of relation ship while using parent child relation in database…
you got that error because of that reason….

Home > SQL Server Error Messages > Msg 547 — INSERT statement conflicted with COLUMN FOREIGN KEY constraint Constraint Name.  The conflict occurred in database Database Name, table Table Name, column Column Name.  The statement has been terminated.

SQL Server Error Messages — Msg 547 — INSERT statement conflicted with COLUMN FOREIGN KEY constraint Constraint Name.  The conflict occurred in database Database Name, table Table Name, column Column Name.  The statement has been terminated.

SQL Server Error Messages — Msg 547

Error Message

Server: Msg 547, Level 16, State 1, Line 1
INSERT statement conflicted with COLUMN FOREIGN KEY
constraint Constraint Name.  The conflict occurred in
database Database Name, table Table Name, column
Column Name.
The statement has been terminated.

Causes:

This error occurs when performing an INSERT command on a table and one of the columns of the table references a primary key on another table and the value being inserted to that particular column does not exist in the other table.

To illustrate, let’s say you have the following tables:

CREATE TABLE [dbo].[State] (
    [StateCode]    CHAR(2) NOT NULL PRIMARY KEY,
    [StateName]    VARCHAR(50)
)

CREATE TABLE [dbo].[County] (
    [CountyCode]   CHAR(5) NOT NULL PRIMARY KEY,
    [CountyName]   VARCHAR(50),
    [StateCode]    CHAR(2) REFERENCES [dbo].[State] ( [StateCode] )
)

Your [dbo].[State] table contains the different states of the United States but does not yet include Puerto Rico.  Since Puerto Rico is not yet included in your [dbo].[State] table, doing an insert into the [dbo].[County] table to add a county of Puerto Rico will generate the error:

INSERT INTO [dbo].[County] ( [CountyCode], [CountyName], [StateCode] )
VALUES ( '72011', 'Añasco Municipio', 'PR' )
Server: Msg 547, Level 16, State 1, Line 1
INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK__County__StateCod__43D61337'.
The conflict occurred in database 'SQLServerHelper', table 'State', column 'StateCode'.
The statement has been terminated.

Solution / Work Around:

To avoid this error from happening, make sure that the value you are inserting into a column that references another table exists in that table.  If the value does not exist in the primary table, insert to that table first before doing the insert on the second table.

To avoid the error in the example above, Puerto Rico needs to be inserted to the [dbo].[State] table first before the county can be inserted to the [dbo].[County] table:

INSERT INTO [dbo].[State] ( [StateCode], [StateName] )
VALUES ( 'PR', 'Puerto Rico' )

INSERT INTO [dbo].[County] ( [CountyCode], [CountyName], [StateCode] )
VALUES ( '72011', 'Añasco Municipio', 'PR' )
Related Articles :
  • Frequently Asked Questions — SQL Server Error Messages
  • Frequently Asked Questions — INSERT Statement
  • Frequently Asked Questions — SELECT Statement

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка te1 стиральной машины самсунг
  • Ошибка the global shader cache file friday the 13th