DELETE语句冲突REFERENCE约束

时间:2016-11-29 12:51:41

标签: sql sql-server

我收到错误

  

DELETE语句与REFERENCE约束冲突   FK_DocYDocument1 - 表DocYDocument,列SubDocID - 语句:   DELETE FROM DOCUMENT WHERE(ID =?)参数:'D7FAA3CF ...'

表DocYDocument有列

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

FK_DocYDocument1外键列是SubDocID,FK_DocYDocument外键列是DocID。

数据库设计是否存在问题,或者我是否要在程序中查找错误?

1 个答案:

答案 0 :(得分:8)

DocYDocument中有一些行指的是您要删除的DOCUMENT

您必须删除DocYDocument中匹配DocID

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

或更改约束以自动执行此操作

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

如果DocID可以为空,如果您愿意,可以改为ON DELETE SET NULL