Конфликт инструкции update с ограничением foreign key

I have a table called patient_address, which reference a PK key in patient table. But if I try to run one of the following statements :

update patient set id_no='7008255601088' where id_no='8008255601089'
update patient_address set id_no='7008255601088' where id_no='8008255601089'

I get this error message:

«The UPDATE statement conflicted with the REFERENCE constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient_address», column ‘id_no’.» or «The
UPDATE statement conflicted with the FOREIGN KEY constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient», column ‘id_no’.» .

Does any body know the possible cause ? Thanks.

MackM's user avatar

MackM

2,9065 gold badges31 silver badges45 bronze badges

asked May 25, 2014 at 14:39

chosenOne Thabs's user avatar

chosenOne ThabschosenOne Thabs

1,4803 gold badges21 silver badges39 bronze badges

5

This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.

If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.

Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:

enter image description here

You can also set the rule using T-SQL:

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

Hope this helps

answered May 25, 2014 at 15:14

Milica Medic Kiralj's user avatar

5

If you don’t want to change your table structure, you can run the following query:

ALTER TABLE [UserStore] 
NOCHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT  FK_UserIdentity_User_UserId

BEGIN TRAN

UPDATE  [user] 
SET Id = 10
WHERE Id = 9

UPDATE  [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9

UPDATE  [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9

COMMIT TRAN

ALTER TABLE [UserStore] 
CHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE UserIdentity 
CHECK CONSTRAINT FK_UserIdentity_User_UserId

answered Jul 11, 2019 at 21:12

Bartho Bernsmann's user avatar

Bartho BernsmannBartho Bernsmann

2,4031 gold badge26 silver badges34 bronze badges

It sometimes happens when you try to Insert/Update an entity while the foreign key that you are trying to Insert/Update actually does not exist. So, be sure that the foreign key exists and try again.

answered Feb 6, 2019 at 10:06

Masoud Darvishian's user avatar

In MySQL

set foreign_key_checks=0;

UPDATE patient INNER JOIN patient_address 
ON patient.id_no=patient_address.id_no 
SET patient.id_no='8008255601088', 
patient_address.id_no=patient.id_no 
WHERE patient.id_no='7008255601088';

Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check.
Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.

answered Aug 6, 2016 at 3:41

YATIN GUPTA's user avatar

This was the solution for me:

-- Check how it is now
select * from patient
select * from patient_address

-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient 
set id_no='7008255601088'
where id_no='8008255601088'

alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address 
set id_no='7008255601088'
where id_no='8008255601088'

-- Check how it is now
select * from patient
select * from patient_address

answered Nov 8, 2018 at 23:28

Francesco Mantovani's user avatar

Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.

exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'

exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Source:

https://stackoverflow.com/a/161410/3850405

answered Apr 3, 2019 at 10:37

Ogglas's user avatar

OgglasOgglas

62.5k37 gold badges334 silver badges420 bronze badges

I would not change the constraints,
instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.

Then you can remove the initial primary key row with id_no =7008255601088.

Three steps include:

  1. Insert duplicate row for new id_no
  2. Update Patient_address to point to new duplicate row
  3. Remove the row with old id_no

answered Jan 15, 2016 at 18:14

Charan Raj's user avatar

Charan RajCharan Raj

4715 silver badges8 bronze badges

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation.
You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

jezzah's user avatar

jezzah

911 silver badge9 bronze badges

answered May 25, 2014 at 14:45

wastl's user avatar

wastlwastl

2,64314 silver badges27 bronze badges

3

Recently I tried to add a one-to-many relationship in my MVC application via Entity Framework Code First. I added the relationship to bind an Administrator name from a dropdown list to the current application that is being filled out. So I have one table for the administrator names and one for the actual application information. The application and dropdown list of admin names seem to work fine and all information is going into my database on submit, but when I try to Edit the application, I get the following error:

The UPDATE statement conflicted with the FOREIGN KEY constraint The conflict occurred in database table «dbo.Administrator», column ‘AdministratorId’

I’ve tried setting my Id columns to «Not Null», but this did not solve the issue.

Model:

public class Administrator
{

    public int AdministratorId{ get; set; }
    public string AdministratorName{ get; set; }

}

public class Application
{
    public Application()
    {
        GetDate = DateTime.Now;
    }

    public int ApplicationId { get; set; }

    [DisplayName("Marital Status")]
    public bool? MaritalStatus { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [DisplayName("Middle Initial")]
    public string MiddleInitial { get; set; }
     [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [DisplayName("Date Submitted")]
    public DateTime GetDate { get; set; }

    public int AdministratorId{ get; set; }

    public virtual Administrator Administrator{ get; set; }
}

Controller (Index):

 public ActionResult Index()
    {
        ViewBag.LoanOfficerId = new SelectList(db.Administrators, "AdministratorId", "AdministratorName");
        return View();
    }

    // POST: Applications/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index([Bind(Include = "AdministratorId,FirstName,MiddleInitial,LastName,")] Application application)
    {



        if (ModelState.IsValid)
        {
ViewBag.AdministratorId= new SelectList(db.Administrators, "AdministratorId",     "AdministratorName", application.Administrator);
            db.Applications.Add(application);
            db.SaveChanges();

            return RedirectToAction("Thanks");
        }


        return View(application);
    }

  • Remove From My Forums
  • Question

  • Hello team,

    I have two tables one is Temp, the structure of both is shape of  EmployeeID and ManagerID with a FK relation on the same table, the temp table does not have this FK at all.

    I have two problems:

    1) I’m almost sure that every EmployeeID has a ManagerID except for the most parent has a Null parent, so the relation is fine; I need to make sure that this is the case with a sql statement ( I have created some, but need a verification from experts like you)

    2) When I update the orginal table with the temp table I get the error «The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint«

    I’m using ADO to execute this update in a transaction using a stored procedure (SQL server 2005) …I need to put my hand on the problem.

    Is there something like NOCHECK can handle this situatin?

    Your quick response is very much appreciated.


    TheScorpion

The «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server is a common issue faced by many database developers. This error occurs when an update operation is attempted on a table with a foreign key constraint, and the updated data violates the constraint. The foreign key constraint enforces referential integrity in the database by ensuring that the values in the referenced columns are valid and exist in the parent table.

Method 1: Check the Constraint

To fix the SQL error on update when encountering a FOREIGN KEY constraint, you can use the «Check the Constraint» method. This method involves checking the constraint that is causing the error and modifying it accordingly. Here are the steps to do this:

  1. Identify the constraint that is causing the error. This can be done by looking at the error message or by checking the table’s constraints.

  2. Check the constraint to see if it is set to «CASCADE». If it is, then the error is likely caused by a circular reference. In this case, you will need to modify the constraint to remove the circular reference.

  3. If the constraint is not set to «CASCADE», then you can modify the constraint to allow updates to the foreign key. This can be done using the «WITH CHECK CHECK» option.

Here is an example of how to modify a constraint to allow updates to the foreign key:

ALTER TABLE [dbo].[Orders] WITH CHECK CHECK CONSTRAINT [FK_Orders_Customers]

In this example, the «Orders» table has a foreign key constraint named «FK_Orders_Customers». The «WITH CHECK CHECK» option is used to modify the constraint to allow updates to the foreign key.

Here is another example of how to modify a constraint to remove a circular reference:

ALTER TABLE [dbo].[Orders] NOCHECK CONSTRAINT [FK_Orders_Customers]
ALTER TABLE [dbo].[Customers] NOCHECK CONSTRAINT [FK_Customers_Orders]
ALTER TABLE [dbo].[Orders] WITH CHECK CHECK CONSTRAINT [FK_Orders_Customers]
ALTER TABLE [dbo].[Customers] WITH CHECK CHECK CONSTRAINT [FK_Customers_Orders]

In this example, the «Orders» and «Customers» tables have foreign key constraints that reference each other. The «NOCHECK» option is used to temporarily disable the constraints, and then the constraints are modified to remove the circular reference using the «WITH CHECK CHECK» option.

By following these steps and modifying the constraint accordingly, you can fix the SQL error on update when encountering a FOREIGN KEY constraint.

Method 2: Use SET NULL or SET DEFAULT

To fix the SQL error on update when the UPDATE statement conflicts with the FOREIGN KEY constraint, you can use either SET NULL or SET DEFAULT. Here are the steps to do it:

  1. Identify the foreign key constraint that is causing the error. You can do this by looking at the error message or by querying the system tables.

  2. Determine whether you want to set the referencing column to NULL or to a default value. If you choose to set it to a default value, you need to define the default value first.

  3. Use the ALTER TABLE statement to modify the foreign key constraint and specify the ON UPDATE clause with either SET NULL or SET DEFAULT.

Here’s an example code for setting the referencing column to NULL:

ALTER TABLE [dbo].[ReferencingTable] 
  DROP CONSTRAINT [FK_ReferencingTable_ReferencedTable]

ALTER TABLE [dbo].[ReferencingTable] 
  WITH CHECK ADD CONSTRAINT [FK_ReferencingTable_ReferencedTable] 
  FOREIGN KEY([ReferencedColumn])
  REFERENCES [dbo].[ReferencedTable] ([ReferencedColumn])
  ON UPDATE SET NULL
  ON DELETE CASCADE

And here’s an example code for setting the referencing column to a default value:

ALTER TABLE [dbo].[ReferencingTable] 
  ADD CONSTRAINT [DF_ReferencingTable_ReferencedColumn] 
  DEFAULT ('DefaultValue') FOR [ReferencedColumn]

ALTER TABLE [dbo].[ReferencingTable] 
  DROP CONSTRAINT [FK_ReferencingTable_ReferencedTable]

ALTER TABLE [dbo].[ReferencingTable] 
  WITH CHECK ADD CONSTRAINT [FK_ReferencingTable_ReferencedTable] 
  FOREIGN KEY([ReferencedColumn])
  REFERENCES [dbo].[ReferencedTable] ([ReferencedColumn])
  ON UPDATE SET DEFAULT ('DefaultValue')
  ON DELETE CASCADE

Note that the ON DELETE clause is added for completeness. It specifies what action to take when the referenced row is deleted. In this example, it is set to CASCADE, which means that the referencing rows will also be deleted.

Method 3: Disable the Constraint and Re-enable it

To fix the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server, you can disable the constraint and re-enable it after the update is done. Here are the steps to do it:

-- Step 1: Disable the foreign key constraint
ALTER TABLE [child_table] NOCHECK CONSTRAINT [FK_child_table_parent_table]

-- Step 2: Update the child table
UPDATE [child_table] SET [column_name] = [new_value] WHERE [condition]

-- Step 3: Re-enable the foreign key constraint
ALTER TABLE [child_table] CHECK CONSTRAINT [FK_child_table_parent_table]

In the above code, replace [child_table], [FK_child_table_parent_table], [column_name], [new_value], and [condition] with the actual names and values for your database.

The NOCHECK CONSTRAINT statement disables the foreign key constraint, allowing you to update the child table without triggering the error. The CHECK CONSTRAINT statement re-enables the foreign key constraint after the update is done.

Note that disabling the constraint can lead to data integrity issues if you don’t handle it carefully. Make sure to test your code thoroughly and re-enable the constraint as soon as possible to avoid any potential problems.

That’s it! With these simple steps, you can fix the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server.

Method 4: Modify the Referenced Data

To fix the SQL error on update related to the FOREIGN KEY constraint, we can modify the referenced data. Here are the steps to do this:

  1. Identify the FOREIGN KEY constraint that is causing the error. This can be done by looking at the error message or by checking the table schema.

  2. Find the table that is referenced by the FOREIGN KEY constraint. This is the table that needs to be modified.

  3. Update the referenced data in the table to match the new values in the referencing table. This can be done using an UPDATE statement.

  4. Once the referenced data has been updated, retry the UPDATE statement that was causing the error.

Here is an example of how to modify the referenced data to fix the SQL error on update:

-- Identify the FOREIGN KEY constraint causing the error
ALTER TABLE dbo.Orders
ADD CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID) REFERENCES dbo.Customers(CustomerID);

-- Find the referenced table
SELECT *
FROM dbo.Customers;

-- Update the referenced data
UPDATE dbo.Customers
SET CustomerID = 'C002'
WHERE CustomerID = 'C001';

-- Retry the UPDATE statement
UPDATE dbo.Orders
SET CustomerID = 'C002'
WHERE OrderID = 1;

In this example, we first identify the FOREIGN KEY constraint FK_Orders_Customers that is causing the error. We then find the referenced table dbo.Customers and update the CustomerID value from C001 to C002. Finally, we retry the UPDATE statement on the dbo.Orders table and it should now execute successfully.

Note that modifying the referenced data can have implications for other parts of the database, so it is important to fully understand the impact of any changes before making them.

Method 5: Use a Transaction

If you’re encountering the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server, you can use a transaction to fix it. Here are the steps:

  1. Begin a transaction using the BEGIN TRANSACTION statement.
  2. Update the parent table first before updating the child table to avoid the foreign key constraint error.
  3. Use the TRY...CATCH block to handle any errors that may occur during the transaction.
  4. If an error occurs, use the ROLLBACK TRANSACTION statement to undo the changes made in the transaction.
  5. If no error occurs, use the COMMIT TRANSACTION statement to commit the changes made in the transaction.

Here’s an example code:

BEGIN TRANSACTION;

BEGIN TRY
    UPDATE ParentTable
    SET Column1 = 'NewValue'
    WHERE ParentID = 1;

    UPDATE ChildTable
    SET Column2 = 'NewValue'
    WHERE ChildID = 1;
END TRY
BEGIN CATCH
    PRINT 'Error occurred: ' + ERROR_MESSAGE();
    ROLLBACK TRANSACTION;
END CATCH;

COMMIT TRANSACTION;

In this example, we first update the ParentTable before updating the ChildTable to avoid the foreign key constraint error. We also use a TRY...CATCH block to handle any errors that may occur during the transaction. If an error occurs, we print the error message and rollback the transaction. If no error occurs, we commit the changes made in the transaction.

Note that using a transaction can help you avoid the foreign key constraint error, but it may not always be the best solution. You should also consider other options such as disabling the constraint temporarily or updating the child table first if it makes sense in your specific scenario.

When I am trying to save Updated data in table using Entity Framework in ASP.NET MVC, I am getting the below error

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_CustomerProfileV2_IndustryList". 
The conflict occurred in database "CRM", table "dbo.IndustryList", column 'IndustryName'.
The statement has been terminated.

How can i Resolve the above issue?

Here is my Current sample code

 [HttpPost]
        public ActionResult EditCustomer(long customerProfileID, CustomerProfile model)
        {
            try
            {
                //code removed 

                crmdb.Entry(model).State = System.Data.Entity.EntityState.Modified;
                crmdb.SaveChanges(); //error here

               //some code removed
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString().Replace("\n", "<br>"));
                return PartialView();
            }
        }

Any help is appreciated, thanks

Asked by:- jon

0

: 8834
At:- 4/2/2018 9:33:50 AM


2 Answers

As per your error details «The UPDATE
statement conflicted with the FOREIGN KEY constraint «FK_CustomerProfileV2_IndustryList». The conflict occurred
in database
«CRM», table
«dbo.IndustryList», column ‘IndustryName’. The statement has been terminated.
«

When you are submitting forms or updating the data, You have a field related to Table dbo.IndustryList with Columns name IndustryName, which cannot be empty due to Foreign key constraint.

So to simply resolve this error provide some value for IndustryName in your form

2

At:- 4/2/2018 11:29:46 AM

Above answer works in some cases but, this error can also occur when you try to update «Primary Key» of a table row but it is referenced by a foreign key from another table and the UPDATE SPECIFIC of table Reference is set to «No action».

So to remove this error, in your SSMS database table, you can simply right-click your foreign key and select Modify.

In the Foreign key relationships dialog under the «INSERT and UPDATE Specific» set the UPDATE rule =  Cascade (Instead of «No Action»)

You can also perform above operation using SQL Query

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

0

At:- 8/3/2021 3:29:06 PM
Updated at:- 8/3/2021 3:30:38 PM

Понравилась статья? Поделить с друзьями:
  • Руководство по эксплуатации телевизора haier 50 smart tv dx
  • Коринфар инструкция по применению при каком заболевании
  • Лактулоза сироп инструкция по применению цена для детей
  • Эспумизан при коликах инструкция по применению
  • Как приготовить запеченные роллы дома фото пошаговая инструкция