问题描述
我有这个创建表脚本
CREATE TABLE Categories (
Id int IDENTITY(1,1) not null,ParentId int null,[Order] int default 0,Published bit not null default 0,Deleted bit not null default 0,CONSTRAINT PK_Categories_Id PRIMARY KEY CLUSTERED (Id),CONSTRAINT FK_Categories_ParentId FOREIGN KEY (ParentId) REFERENCES Categories(Id) on delete cascade,Title nvarchar(255) NOT NULL,CreatedAt DateTime not null default GETDATE(),UpdatedAt DateTime not null default GETDATE()
);
我得到一个错误
Msg 1785,Level 16,State 0,Line 1
Introducing FOREIGN KEY constraint 'FK_Categories_ParentId' on table 'Categories' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION,or modify other FOREIGN KEY constraints.
Msg 1750,State 1,Line 1
Could not create constraint or index. See previous errors.
如何在外键约束上添加删除级联?
解决方法
不幸的是,与某些其他数据库相反,SQL Server只是不允许对自引用外键执行引用操作。
一种可能的解决方法是使用一个instead of delete
触发器,该触发器遵循关系并删除所有子行:
create trigger trg_categories
on categories
instead of delete
as
with cte as (
select id from deleted
union all
select cte.id
from cte
inner join categories cat on cat.parentid = cte.id
)
delete cat
from categories cat
where exists (select 1 from cte where cte.id = cat.id)
;