Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The DELETE statement conflict REFERENCE constraint

Tags:

sql

sql-server

I get the error

The DELETE statement conflicted with the REFERENCE constraint FK_DocYDocument1 - table DocYDocument, column SubDocID - Statement: DELETE FROM DOCUMENT WHERE (ID=?) Parameter: 'D7FAA3CF...'

Table DocYDocument has columns

PK ID, FK DocID and FK SubDocID. 
And the keys PK_DocYDocument, FK_DocYDocument and FK_DocYDocument1.

FK_DocYDocument1 foreign key column is SubDocID and FK_DocYDocument foreign key column is DocID.

Is there a problem with database design or do I've to look for the error in the program?

like image 696
user1673665 Avatar asked Nov 29 '16 12:11

user1673665


People also ask

What does the delete statement do?

The DELETE statement is used to delete existing records in a table.

What is a reference constraint?

A referential constraint is defined for a specific column (called a foreign key) when a table is defined. A table in which a referential constraint and a foreign key are defined is called a referencing table, while a table that is referenced from a referencing table with a foreign key is called a referenced table.

How do I delete a foreign key constraint in SQL Server?

In the INSERT and UPDATE specifications, select Cascade for the delete rule. Click on Close and save the table in the designer. Click Yes in the warning message window. Once you click on Yes, a foreign key with delete rule is created.


1 Answers

You have rows in DocYDocument that are referring to the DOCUMENT you are trying to delete.

You have to either delete the rows from DocYDocument with matching DocID

DELETE FROM DocYDocument WHERE DocID = ?
DELETE FROM DOCUMENT WHERE ID = ?

or change the constraint to do this automatically

ALTER TABLE DocYDocument
  DROP CONSTRAINT FK_DocYDocument;
ALTER TABLE DocYDocument
  ADD CONSTRAINT FK_DocYDocument
    FOREIGN KEY ( DocID )
    REFERENCES DOCUMENT ( ID )
    ON DELETE CASCADE;

If DocID is nullable, you could instead do ON DELETE SET NULL, if you wish.

like image 136
Markus Jarderot Avatar answered Nov 04 '22 18:11

Markus Jarderot