Конфликт инструкции insert с ограничением foreign key как исправить

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.

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.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

asked Jun 3, 2010 at 12:24

SmartestVEGA's user avatar

SmartestVEGASmartestVEGA

8,26524 gold badges83 silver badges135 bronze badges

1

Your table dbo.Sup_Item_Cat 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.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered Jun 3, 2010 at 12:29

Mike M.'s user avatar

2

The answer on this page by Mike M. is correct:

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 that answer is: You must build the table containing the primary key first.

You must insert data into the parent table, containing the primary key, before attempting to insert data into the foreign key.

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.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered Jan 17, 2014 at 20:50

plasmasnakeneo's user avatar

plasmasnakeneoplasmasnakeneo

2,2111 gold badge13 silver badges16 bronze badges

1

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

5771 gold badge9 silver badges36 bronze badges

answered Jun 3, 2010 at 12:31

Matthew Smith's user avatar

Matthew SmithMatthew Smith

1,2771 gold badge9 silver badges19 bronze badges

0

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.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered Jun 3, 2010 at 12:27

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

241k40 gold badges406 silver badges536 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

All the fields have to match EXACTLY.

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

To troubleshoot this: Script out the FK code from the table you ae inserting data into, take note of the «Foreign Key» that has the constraints and make sure those fields’ values match EXACTLY as they were in the table throwing the FK Constraint error.

Fix the fields.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered May 30, 2014 at 21:06

John Waclawski's user avatar

John WaclawskiJohn Waclawski

9161 gold badge10 silver badges20 bronze badges

0

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.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

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

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered Apr 12, 2014 at 16:20

dotnet's user avatar

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

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

The problem was fixed by reseeding identity with

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

The code that failed before started to work.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered Apr 28, 2021 at 22:12

Mike's user avatar

MikeMike

19.6k25 gold badges97 silver badges133 bronze badges

I used code-first migrations to build my database for an MVC 5 application. The seed method in my configuration.cs file was causing the issue, creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.

philipxy's user avatar

philipxy

14.7k6 gold badges37 silver badges81 bronze badges

answered May 14, 2014 at 19:12

Paulie22's user avatar

Paulie22Paulie22

1111 gold badge1 silver badge9 bronze badges

Error: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint «FK__Item__order__3AE27131». The conflict occurred in database «pmall», table «dbo.ItemSaved», column ‘id’.

Here’s my table:

ItemSavedUnits

  • id
  • ItemID (is set in this table a FK to Item.id)
  • …etc.

Here’s my insert statement:

insert into ItemSavedUnits (ItemID, name, Price)
select ItemID, name,Price
from ItemUnits where ItemID = 92439 

I don’t really understand why if I a FK constraint on ItemSavedUnits.ItemID that is related to Item.ItemID and ItemUnits has no constraints at all why I’m getting a problem inserting into ItemSavedUnits. The ItemID I’m tryign to insert does exist in the Item table.

Community's user avatar

asked Dec 1, 2009 at 19:38

PositiveGuy's user avatar

PositiveGuyPositiveGuy

46.3k109 gold badges301 silver badges468 bronze badges

1

Are you absolutely sure that ItemId 92439 exists in the Item table, and not just in ItemUnits?

or

Is your select statement returning null?

answered Dec 1, 2009 at 19:40

Jim B's user avatar

7

It looks like you need a row in ItemUnits with that ID first — what does the SELECT statement part of your insert return? No rows?

Also, is there a trigger on the ItemSavedUnits table that could be causing problems?

answered Dec 1, 2009 at 19:43

SqlRyan's user avatar

SqlRyanSqlRyan

32.9k33 gold badges114 silver badges197 bronze badges

Your foreign key constraint violation doesn’t appear to deal with the ItemSavedUnits table — the violation exception is being thrown by the constraint on the ItemSaved table, not the ItemSavedUnits table. Is there a trigger on ItemSavedUnits that’s trying to insert into ItemSaved?

answered Dec 1, 2009 at 19:45

Dathan's user avatar

DathanDathan

7,2362 gold badges26 silver badges46 bronze badges

  • Remove From My Forums
  • Вопрос

  • Здравствуйте, делаю проект с использованием EF.  И он выдает ошибку

     Конфликт инструкции INSERT с ограничением FOREIGN KEY «FK_dbo.Attachments_dbo.NotificationEFs_AttachmentId». Конфликт произошел в базе данных таблица «dbo.NotificationEFs», column ‘newId’.Выполнение данной инструкции было
    прервано.»}

    Вот сам код

    var entity = ParserNotificationTender.GetNotifycationEntity(f);
    var placingway = ParserNotificationTender.GetPlacingWayEntity(f);
                                var etp = ParserNotificationTender.GetETPEntity(f);
                                var attachments = ParserNotificationTender.GetAttachmentEntity(f);
                                printform.Notification = entity;
                                placingway.Notify = entity;
                                etp.NotifyEtp = entity;
                                foreach (var attachment in attachments)
                                {
                                    attachment.notifyId = entity;
                                    if (attachment.CryptoSignObg != null)
                                    {
                                        attachment.CryptoSignObg.AttachmentNotify = attachment;
                                        listCryptosign.Add(attachment.CryptoSignObg);
                                    }
                                }
                                if (entity != null)
                                {
                                    listIntity.Add(entity);
                                    listPrintForm.Add(printform);
                                    lispPlacingWay.Add(placingway);
                                    listETP.Add(etp);
                                    if (attachments != null)
                                    {
                                        listAttachment.Add(attachments);
                                    }
                                    
                                }
    
    
    

    Далее вызывается этот метод 

    public static void AddCryptoSign(List<CryptoSignsAttachment> cryptosignrange)
            {
                using (var context = new DBEntity())
                {
                    foreach (var obj in cryptosignrange)
                    {
                        context.CryptoSignObj.Add(obj);
                        context.SaveChanges();
                    }
                }
            }

    и в нем как раз эта ошибка происходит, причем всегда во второй итерации.

    • Перемещено

      11 января 2015 г. 12:46

Ответы

  • Ошибка связана с тем, что у вас вводится значиние которое отсуствует в свяной таблице (на которое указывает внешний ключ). Т.е. одному из полей сушности назначается неверное значение. Вам надо или задать его правильно или снять ограничение
    внешнего ключа с таблицы.


    Сделаем содержимое сообщества лучше, вместе!

Вопрос:

Я получаю следующую ошибку. Не могли бы вы мне помочь?

Сообщение 547, уровень 16, состояние 0, строка 1
Оператор INSERT конфликтует с ограничением FOREIGN KEY “FK_Sup_Item_Sup_Item_Cat”. Конфликт произошел в базе данных “dev_bo”, таблица “dbo.Sup_Item_Cat”. Заявление было прекращено.

Код:

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')

Последний столбец client_id вызывает ошибку. Я попытался поместить значение, которое уже существует в dbo.Sup_Item_Cat в столбец, соответствующий sup_item.. но без радости 🙁

Лучший ответ:

В вашей таблице dbo.Sup_Item_Cat он имеет ссылку внешнего ключа на другую таблицу. Способ работы FK заключается в том, что он не может иметь значение в этом столбце, которое также не находится в столбце первичного ключа ссылочной таблицы.

Если у вас есть SQL Server Management Studio, откройте его и sp_helpdbo.Sup_Item_Cat. Посмотрите, в каком столбце включен FK, и в каком столбце которого он ссылается. Вы вставляете некоторые плохие данные.

Сообщите мне, если вам что-то объяснено лучше!

Ответ №1

Я сам столкнулся с этой проблемой, касающейся сообщения об ошибке, полученного при заполнении поля внешнего ключа. Я попал на эту страницу в надежде найти ответ. Проверенный ответ на этой странице действительно правильный, к сожалению, я чувствую, что ответ немного неполон для людей, не знакомых с SQL. Я довольно хорошо умею писать код, но запросы SQL для меня новы, как и создание таблиц базы данных.

Несмотря на то, что проверенный ответ является правильным:

Майк М wrote-

“Способ работы FK заключается в том, что он не может иметь значение в этом столбце, которого нет также в столбце первичного ключа в указанной таблице”.

Чего не хватает в этом ответе просто;

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

Еще один способ сказать это;

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

Короче говоря, многие учебные пособия, похоже, не соответствуют этому факту, так что если вы попробуете самостоятельно и не поймете, что существует порядок операций, вы получите эту ошибку. Естественно, после добавления данных первичного ключа ваши данные внешнего ключа в дочерней таблице должны соответствовать полю первичного ключа в родительской таблице, в противном случае вы все равно получите эту ошибку.

Если кто-то прочитал это далеко. Я надеюсь, что это помогло сделать проверенный ответ более ясным. Я знаю, что некоторые из вас могут почувствовать, что подобные вещи довольно просты и что открытие книги ответило бы на этот вопрос до того, как она была опубликована, но правда в том, что не все учатся одинаково.

Ответ №2

Вы пытаетесь вставить запись со значением в столбце внешнего ключа, которого нет во внешней таблице.

Например: если у вас есть таблицы “Книги” и “Авторы”, в которых “Книги” имеют ограничение внешнего ключа для таблицы “Авторы”, и вы пытаетесь вставить запись книги, для которой нет записи об авторе.

Ответ №3

Вам нужно будет опубликовать свое выражение для получения дополнительных разъяснений. Но…

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

Ответ №4

Проблема не в client_id из того, что я вижу. Это больше похоже на проблему с 4-м столбцом, sup_item_cat_id

Я бы запустил

sp_helpconstraint sup_item

и обратите внимание на столбец constraint_keys, возвращенный для внешнего ключа FK_Sup_Item_Sup_Item_Cat, чтобы подтвердить, какой столбец является реальной проблемой, но я уверен, что это не тот, который вы пытаетесь исправить. Кроме того, “123123” также выглядит подозрительным.

Ответ №5

Я обнаружил, что все поля должны соответствовать ТОЧНО.

Например, отправка “cat dog” не совпадает с отправкой “catdog”.

То, что я сделал для устранения этого неполадки, заключалось в script из кода FK из таблицы, в которую я вставлял данные, обратите внимание на “Foreign Key” с ограничениями (в моем случае было 2) и убедитесь, что эти 2 значения полей соответствовали ТОЧНО, поскольку они были в таблице, которая бросала ошибку ограничения FK.

Как только я исправил 2 поля, дающие мои проблемы, жизнь была хорошей!

Если вам нужно лучшее объяснение, сообщите мне.

Ответ №6

Это означает именно то, что он говорит. Вы пытаетесь вставить значение в столбец с ограничениями FK на нем, который не соответствует никаким значениям в таблице поиска.

Ответ №7

Данные родительской таблицы не существуют, поэтому она вызывает проблему. Для вышеуказанной проблемы данные недоступны в таблице dbo.Sup_Item_Cat “

Ответ №8

Дважды проверьте поля в отношении, для которого задан внешний ключ. SQL Server Management Studio, возможно, не выбрали нужные вам поля при определении отношения. Это сожгло меня в прошлом.

Ответ №9

  • запустить sp_helpconstraint
  • заплатите ВНИМАНИЕ столбцу constraint_keys, возвращенному для внешнего ключа.

Ответ №10

Отсутствие данных родительской таблицы вызывает проблему.
В вашей проблеме не доступность данных в “dbo.Sup_Item_Cat” вызывает проблему

Ответ №11

У меня была такая же проблема, когда я использовал первые преобразования кода для создания моей базы данных для приложения MVC 5. В конце концов я нашел метод seed в моем файле configuration.cs, чтобы вызвать проблему. Мой метод seed создавал запись таблицы для таблицы, содержащей внешний ключ, перед созданием записи с соответствующим первичным ключом.

Ответ №12

Я столкнулся с этой проблемой, когда мои поля значений вставки содержали вкладки и пробелы, которые не были очевидны для невооруженного глаза. Я создал свой список значений в Excel, скопировал и вставил его в SQL, и запустил запросы, чтобы найти несоответствия в моих FK-полях.

В запросах совпадения не было обнаружено, что в моем поле FK есть вкладки и пробелы, но INSERT распознал их и продолжал генерировать ошибку.

Я снова тестировал, копируя содержимое поля FK в одной записи и вставляя его в запрос вставки. Когда эта запись также потерпела неудачу, я подошел ближе к данным и, наконец, обнаружил вкладки/пробелы.

Как только я очистил удаленные вкладки/пробелы, моя проблема была решена. Надеюсь, это поможет кому-то!

Ответ №13

Я также получил ту же ошибку в моем коде SQL, это решение работает для меня,


Проверьте данные в первичной таблице. Возможно, вы вводите значение столбца, которого нет в столбце первичного ключа.

Ответ №14

Иногда это происходит, когда вы пытаетесь Insert/Update объект, в то время как foreign key который вы пытаетесь Insert/Update самом деле не существует. Поэтому убедитесь, что foreign key существует, и повторите попытку.

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

Loading

Понравилась статья? Поделить с друзьями:
  • Тренажер для пресса аб рокет инструкция пользования
  • Сумамед инструкция по применению цена уколы
  • Препарат эльвита удивит инструкция по применению цена отзывы
  • Руководство по полевым инженерно геологическим изысканиям
  • Haas мануал на русском