【问题标题】:multiple cascade paths sql server 2017 create self referencial foreign key多个级联路径 sql server 2017 创建自引用外键
【发布时间】:2021-01-12 18:28:20
【问题描述】:

我有这个创建表脚本

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, Level 16, State 1, Line 1
Could not create constraint or index. See previous errors.

如何将删除级联添加到外键约束?

【问题讨论】:

    标签: sql sql-server foreign-keys sql-delete self-reference


    【解决方案1】:

    不幸的是,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)
    ;
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 2013-03-26
      • 1970-01-01
      • 2017-02-09
      相关资源
      最近更新 更多