Конфликт инструкции 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,8665 gold badges32 silver badges45 bronze badges

asked May 25, 2014 at 14:39

chosenOne Thabs's user avatar

chosenOne ThabschosenOne Thabs

1,4443 gold badges21 silver badges38 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 badge25 silver badges33 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

59.5k36 gold badges322 silver badges405 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,64313 silver badges27 bronze badges

3

  • 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

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);
    }

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

: 8111
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

Scenario:

You are working as SQL Server developer, You wrote an update statement for one of the table and getting below error.



Msg 547, Level 16, State 0, Line 32
The UPDATE statement conflicted with the REFERENCE constraint «FK_». 
The conflict occurred in database «YourDatabaseName», table «SchemaName.YourTableName», column ‘ColumnName’.
The statement has been terminated.

How to resolve this issue?

Solution:

Let’s create this error first by using below script. We are going to create two tables dbo.Customer and dbo.Orders. The tables has Primary-Foreign Key Relationship.

USE YourDatabaseName
GO

CREATE TABLE dbo.Customer (
    Customerid INT PRIMARY KEY
    ,FName VARCHAR(100)
    ,LName VARCHAR(100)
    ,SSN VARCHAR(10)
    )


    CREATE TABLE dbo.Orders (
    OrderId INT Identity(1, 1)
    ,OrderitemName VARCHAR(50)
    ,OrderItemAmt INT
    ,Customer_id INT FOREIGN KEY REFERENCES Customer(CustomerId)
    )


    --insert sample data
     insert into dbo.Customer 
    (CustomerId,FName, LName,SSN)
     values
    (1,'Aamir','Shahzad','000-000-00')

    insert into dbo.Orders
    (OrderItemName,OrderItemAmt,Customer_Id)
    values ('TV',1,1)


How to update record when Column is referenced by Foreign Key Constraint in SQL Server

Now let’s say if you feel that CustomerId value is incorrect in dbo.Customer and need to be updated. You wrote below update statement to update CustomerId to 100.

    update dbo.Customer
    set Customerid=100

You will get below error.

Msg 547, Level 16, State 0, Line 33

The UPDATE statement conflicted with the REFERENCE constraint «FK__Orders__Customer__1ED998B2». 

The conflict occurred in database «YourDatabaseName», table «dbo.Orders», column ‘Customer_id’.

The statement has been terminated.

As there is no Customer_id value=100 in dbo.Orders table, You can’t update the record in reference table. Now you thought that let’s fix the Parent table first ( dbo.Orders) and then I can update the dbo.Customer table.

    update dbo.Orders
    set Customer_Id=100



Again you got the error as shown below, because we don’t have CustomerId=100 available in dbo.Customer table.

Msg 547, Level 16, State 0, Line 36

The UPDATE statement conflicted with the FOREIGN KEY constraint «FK__Orders__Customer__1ED998B2».

 The conflict occurred in database «YourDatabaseName», table «dbo.Customer», column ‘Customerid’.

The statement has been terminated.

From here we can come with with multiple solutions

1) Instead of updating the record, Insert the record in Reference Table ( Dbo.Customer), Then update the record in Parent table (Dbo.Orders) and finally delete the existing records from Reference Table.

    --Insert Record in Reference Table First
     insert into dbo.Customer 
    (CustomerId,FName, LName,SSN)
     values
    (100,'Aamir','Shahzad','000-000-00')

    --Update the Records in Parent Table 
        update dbo.Orders
    set Customer_Id=100

    --Delete the old record from Reference Table
    Delete from dbo.Customer
    where CustomerId=1



Check the records in table now.

How to update Column Value when referenced by Foreign Key Constraint in SQL Server 

2) Disable the Foreign Key Constraint and Update the Values Manually

Another solution can be, disable the Foreign Key constraint, update the records and finally enable the Foreign key again.

--Find the Foreign Key Constraint with Table Name
    USE YourDatabaseName
    GO
    Select 
    Schema_name(Schema_id) as SchemaName,
    object_name(Parent_object_id) as TableName,
    name as ForeignKeyConstraintName
    from sys.foreign_keys


Disable the Foreign Key Constraint by using below statement

Syntax

ALTER TABLE SchemaName.ParentTableName

NOCHECK CONSTRAINT Constraint_Name

I used below statement to disable Foreign Key constraint on dbo.Orders table.

--Disable Foregin Key by using NOCHECK
ALTER TABLE dbo.Orders
NOCHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E

--Run Update Statements
    update dbo.Customer
    set Customerid=100

    update dbo.Orders
    set Customer_Id=100

Enable Foreign Key Constraint Syntax

ALTER TABLE SchemaName.ParentTableName

CHECK CONSTRAINT Constraint_Name

I execute below script to Enable Foreign Key Constraint on dbo.Orders table.

--Enable Foreign Key Constraint by using CHECK
ALTER TABLE dbo.Orders
CHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E

Video Demo : The UPDATE statement conflicted with the REFERENCE Constraint

Понравилась статья? Поделить с друзьями:
  • Коринфар инструкция по применению при каком заболевании
  • Все руководства будут готов
  • Лактулоза сироп инструкция по применению цена для детей
  • Измеритель неоднородностей линий р5 12 инструкция
  • Эспумизан при коликах инструкция по применению