Sqlexception конфликт инструкции 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.8k6 gold badges39 silver badges85 bronze badges

asked Jun 3, 2010 at 12:24

SmartestVEGA's user avatar

SmartestVEGASmartestVEGA

8,56526 gold badges87 silver badges143 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 bronze badges

answered Jan 17, 2014 at 20:50

plasmasnakeneo's user avatar

plasmasnakeneoplasmasnakeneo

2,2211 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

5891 gold badge9 silver badges38 bronze badges

answered Jun 3, 2010 at 12:31

Matthew Smith's user avatar

Matthew SmithMatthew Smith

1,2871 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.8k6 gold badges39 silver badges85 bronze badges

answered Jun 3, 2010 at 12:27

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

243k40 gold badges408 silver badges537 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,57210 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.8k6 gold badges39 silver badges85 bronze badges

answered May 30, 2014 at 21:06

John Waclawski's user avatar

John WaclawskiJohn Waclawski

9461 gold badge11 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 bronze badges

answered Apr 28, 2021 at 22:12

Mike's user avatar

MikeMike

20.2k25 gold badges99 silver badges143 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.8k6 gold badges39 silver badges85 bronze badges

answered May 14, 2014 at 19:12

Paulie22's user avatar

Paulie22Paulie22

1111 gold badge1 silver badge9 bronze badges

I experienced same issue while running the query:

INSERT INTO [dbo].[work_flow_actions] ([work_flow_id] ,[actions_id]) VALUES (70004, 150044)

Meanwhile, I confirmed that the values 70004 and 150044 exist in the corresponding tables.

I fixed this by including the database name as follows:

INSERT INTO [TIS].[dbo].[work_flow_actions] ([work_flow_id] ,[actions_id]) VALUES (70004, 150044)

Greg d'Eon's user avatar

answered Jun 28 at 1:11

Philip Afemikhe's user avatar

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.8k6 gold badges39 silver badges85 bronze badges

asked Jun 3, 2010 at 12:24

SmartestVEGA's user avatar

SmartestVEGASmartestVEGA

8,56526 gold badges87 silver badges143 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 bronze badges

answered Jan 17, 2014 at 20:50

plasmasnakeneo's user avatar

plasmasnakeneoplasmasnakeneo

2,2211 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

5891 gold badge9 silver badges38 bronze badges

answered Jun 3, 2010 at 12:31

Matthew Smith's user avatar

Matthew SmithMatthew Smith

1,2871 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.8k6 gold badges39 silver badges85 bronze badges

answered Jun 3, 2010 at 12:27

Justin Niessner's user avatar

Justin NiessnerJustin Niessner

243k40 gold badges408 silver badges537 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,57210 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.8k6 gold badges39 silver badges85 bronze badges

answered May 30, 2014 at 21:06

John Waclawski's user avatar

John WaclawskiJohn Waclawski

9461 gold badge11 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 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.8k6 gold badges39 silver badges85 bronze badges

answered Apr 28, 2021 at 22:12

Mike's user avatar

MikeMike

20.2k25 gold badges99 silver badges143 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.8k6 gold badges39 silver badges85 bronze badges

answered May 14, 2014 at 19:12

Paulie22's user avatar

Paulie22Paulie22

1111 gold badge1 silver badge9 bronze badges

I experienced same issue while running the query:

INSERT INTO [dbo].[work_flow_actions] ([work_flow_id] ,[actions_id]) VALUES (70004, 150044)

Meanwhile, I confirmed that the values 70004 and 150044 exist in the corresponding tables.

I fixed this by including the database name as follows:

INSERT INTO [TIS].[dbo].[work_flow_actions] ([work_flow_id] ,[actions_id]) VALUES (70004, 150044)

Greg d'Eon's user avatar

answered Jun 28 at 1:11

Philip Afemikhe's user avatar

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.8k111 gold badges306 silver badges472 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

33.2k33 gold badges115 silver badges201 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,3063 gold badges27 silver badges46 bronze badges

  • Remove From My Forums
  • Question

  • User1005758432 posted

    Here’s my code behind:

    protected void cuwRegister_CreatedUser(object sender, EventArgs e)
        {
            //create new create user wizard to grab the user name and password
            CreateUserWizard cuwNewUser = sender as CreateUserWizard;
            // Insert a new record into UserProfiles
            foundBoardDataContext addBrdMemberDC = new foundBoardDataContext();
            foundBoard newMember = new foundBoard();
    
            TextBox txtFirstName = (TextBox)cuwNewUser.CreateUserStep.ContentTemplateContainer.FindControl("txtFstName");
            TextBox txtLastName = (TextBox)cuwNewUser.CreateUserStep.ContentTemplateContainer.FindControl("txtLstName");
    
            newMember.brdFstName = txtFirstName.Text;
            newMember.brdLstName = txtLastName.Text;
            newMember.userName = cuwNewUser.UserName;
            newMember.password = cuwNewUser.Password;
            newMember.emailAddr = cuwNewUser.Email;
    
            addBrdMemberDC.foundBoards.InsertOnSubmit(newMember);
            addBrdMemberDC.SubmitChanges();
    
        }

    And here’s the relationship between the two tables:

    I kept getting this error when registering new user.

    The INSERT statement conflicted with the FOREIGN KEY constraint «FK_foundBoard_aspnet_Users». The conflict occurred in database «Advancement», table «dbo.aspnet_Users», column ‘UserId’.
    The statement has been terminated.

    Description:
    An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint «FK_foundBoard_aspnet_Users». The conflict occurred in database «Advancement», table «dbo.aspnet_Users», column ‘UserId’.
    The statement has been terminated.

    Source Error:

    Line 46: 
    Line 47:         addBrdMemberDC.foundBoards.InsertOnSubmit(newMember);
    Line 48:         addBrdMemberDC.SubmitChanges();
    Line 49: 
    Line 50:     }

Answers

  • User-29804325 posted

    Hi,

    As it mentioned, since you assign the foreign key between this two table. You should make sure the value of brdID in custom table matched the UserID in aspnet_User table. According to your code, when you prepared to insert data into your custom
    table. You also need to set the brdID(I’m not sure if you has done this step in Linq to sql in InsertOnSubmit method, but you should confirm it).

    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        CreateUserWizard cuwNewUser = sender as CreateUserWizard;
        string userName = CreateUserWizard.UserName;
        MembershipUser User = Membership.GetUser(userName);
        object UserGUID = User.ProviderUserKey;
    
        //your code...
        
        //insert the UserGUID to your custom table
        newMember.brdID = UserGUID;
        //your code...
    }

    UserID is guid type. Also make sure the brdID is the same datatype of UserID in aspnet_User tables.

    Hope this can help you.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

azhty

0 / 0 / 0

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

Сообщений: 4

1

22.05.2017, 21:17. Показов 38919. Ответов 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



360 / 287 / 76

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

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

22.05.2017, 22:09

2

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



0



644 / 528 / 324

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

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

23.05.2017, 09:35

3

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



0



3 / 3 / 0

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

Сообщений: 48

29.01.2018, 13:00

4

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

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

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



0



360 / 287 / 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



652 / 587 / 171

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

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

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

29.01.2018, 15:49

7

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



1



Эксперт .NET

11867 / 8189 / 1250

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

Сообщений: 30,802

29.01.2018, 16:10

8

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



0



652 / 587 / 171

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

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

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

29.01.2018, 16:20

9

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

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

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



0



Эксперт .NET

11867 / 8189 / 1250

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

Сообщений: 30,802

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

11867 / 8189 / 1250

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

Сообщений: 30,802

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

11867 / 8189 / 1250

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

Сообщений: 30,802

12.02.2018, 14:17

14

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



0



3 / 3 / 0

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

Сообщений: 48

12.02.2018, 14:47

15

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

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

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



0



Эксперт .NET

11867 / 8189 / 1250

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

Сообщений: 30,802

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

11867 / 8189 / 1250

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

Сообщений: 30,802

12.02.2018, 15:43

18

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

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

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



0



3 / 3 / 0

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

Сообщений: 48

12.02.2018, 15:48

19

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



0



Эксперт .NET

11867 / 8189 / 1250

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

Сообщений: 30,802

12.02.2018, 15:50

20

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

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

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



0



I’m working on a data migration from one database to a another.

So far everything is working but with one table I always get the same error. There is a problem with the foreign key that I also want to migrate in this table. I think I have to declare something special for a foreign key?

This is my query:

INSERT INTO [asd].HolidayTracker.dbo.AnnualVacation(UserId,WorkingTime,VacationDays,FromDate,ToDate)
SELECT u1.user_htUserId,
       u1.vacationDays,
       u1.workingTime,
       CAST('2013-01-01' AS DATETIME),
       CAST('2013-12-31' AS DATETIME)

FROM    HolidayTracker.dbo.AnnualVacation u1 
            LEFT JOIN  [asd].HolidayTracker.dbo.AnnualVacation u2
                ON u1.user_htUserId = u2.UserId AND 
                   u1.vacationDays = u2.VacationDays AND
                   u1.workingTime = u2.WorkingTime

This is the error message I get:

error message The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AnnualVacation_HtUser1". The conflict occurred in database "HolidayTracker", table "dbo.HtUser", column 'UserId'.

This is the table structure: Source table

enter image description here

Destination Table 

enter image description here

My User table where all users are saved 



Thanks for help and fast answer 

  • Изменено

    3 апреля 2013 г. 7:53

Понравилась статья? Поделить с друзьями:

Это тоже интересно:

  • Smart window cleaner robot инструкция на русском
  • Smart window clean robot инструкция на русском
  • Sprint layout инструкция на русском
  • Sprint 10d зарядное устройство инструкция
  • Spring clear для цветов инструкция

  • Подписаться
    Уведомить о
    guest

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