引入FOREIGN KEY约束可能会导致循环或多个级联路径

时间:2016-07-12 07:20:31

标签: sql sql-server foreign-key-relationship

我有这个sql脚本在mssql中创建数据库:

CREATE TABLE ENTITY (
  ID             bigint IDENTITY(1,1)             NOT NULL,
  NAME           nvarchar(255)                    NOT NULL,
  PARENT_ID      bigint                           NULL
)
go

ALTER TABLE ENTITY
ADD CONSTRAINT PK_ENTITY PRIMARY KEY CLUSTERED (ID)
WITH FILLFACTOR = 80
go

ALTER TABLE ENTITY
ADD CONSTRAINT FK_ENTITY FOREIGN KEY (PARENT_ID)
REFERENCES ENTITY (ID) ON DELETE CASCADE ON UPDATE CASCADE
go

根据设计,我想在单个表中创建父 - >子关系 所以,只是一些伪代码示例:

id |  name |  parent_id
1    Mother     null
2    Steve      1
3    Jack       1

如果需要,我想删除所有DELETE Cascade孩子的母亲 但在我安装此脚本后,我收到:

Introducing FOREIGN KEY constraint 'FK_ENTITY' on table 'ENTITY' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

我是否可以正确实现这样的单表层次结构?

1 个答案:

答案 0 :(得分:0)

似乎sql server不允许使用Recursive Foreign Keys级联DELETE,因此您可以为删除操作编写程序,如下所示:

ActiveWorkbook.SaveAs FileName:= ThisWorkbook.Path & "\Accenture.xlsx" ...