微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多个级联路径sql server 2017创建自引用外键

如何解决多个级联路径sql server 2017创建自引用外键

我有这个创建表脚本

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。