Problem


I am trying to use the ON DELETE CASCADE option when creating a foreign key on my database, but I get the following error:

Msg 1785, Level 16, State 0, Line 3
Introducing FOREIGN KEY constraint 'FK_Table' on table 'Table' 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 0, Line 3
Could not create constraint. See previous errors.

This tip will look at how you can use triggers to replace the functionality you get from the ON DELETE CASCADE option of a foreign key constraint.

Solution


Let's setup a simple scenario to illustrate the issue. The following database diagram illustrates our table and foreign key layout. You can see from the diagram where we are going to have the issue of multiple cascade paths as there are two paths from the Parent table down to the GrandChild table.

And here is the DDL code we can use to setup this scenario in our database.

-- Table creation logic
--parent table
CREATE TABLE [dbo].[Parent](
[ParentID] [bigint] NOT NULL,
[Data] [varchar](10) NOT NULL,
CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED
([ParentID] ASC)
)
GO
-- child table 1
CREATE TABLE [dbo].[Child1](
[Child1ID] [bigint] NOT NULL,
[ParentID] [bigint] NULL,
[Data] [varchar](10) NULL,
CONSTRAINT [PK_Child1] PRIMARY KEY CLUSTERED
([Child1ID] ASC)
)
GO
-- child table 2
CREATE TABLE [dbo].[Child2](
[Child2ID] [bigint] NOT NULL,
[ParentID] [bigint] NULL,
[Data] [varchar](10) NULL,
CONSTRAINT [PK_Child2] PRIMARY KEY CLUSTERED
([Child2ID] ASC)
)
GO
-- grandchild table
CREATE TABLE [dbo].[GrandChild](
[GrandChildID] [bigint] NOT NULL,
[Child1ID] [bigint] NULL,
[Child2ID] [bigint] NULL,
[Data] [varchar](10) NULL,
CONSTRAINT [PK_GrandChild] PRIMARY KEY CLUSTERED
([GrandChildID] ASC)
)
GO
-- foreign key constraint
ALTER TABLE [dbo].[Child1] WITH CHECK
ADD CONSTRAINT [FK_Child1_Parent] FOREIGN KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
ON DELETE CASCADE
GO
-- foreign key constraint
ALTER TABLE [dbo].[Child2] WITH CHECK
ADD CONSTRAINT [FK_Child2_Parent] FOREIGN KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
ON DELETE CASCADE
GO
-- foreign key constraint
ALTER TABLE [dbo].[GrandChild] WITH CHECK
ADD CONSTRAINT [FK_GrandChild_Child1] FOREIGN KEY([Child1ID])
REFERENCES [dbo].[Child1] ([Child1ID])
ON DELETE CASCADE
GO
-- foreign key constraint
ALTER TABLE [dbo].[GrandChild] WITH CHECK
ADD CONSTRAINT [FK_GrandChild_Child2] FOREIGN KEY([Child2ID])
REFERENCES [dbo].[Child2] ([Child2ID])
ON DELETE CASCADE
GO

After executing the code above we get the following error and confirm the initial assumption we made after looking at the database diagram, that we have multiple paths down to the GrandChild table.

Msg 1785, Level 16, State 0, Line 3
Introducing FOREIGN KEY constraint 'FK_GrandChild_Child2' on table 'GrandChild' 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 0, Line 3
Could not create constraint. See previous errors.

To get around this error by creating the foreign key with DELETE NO ACTION, we would end up with orphan records in the GrandChild table every time a DELETE statement is issued against the Parent or Child2 tables. Instead of doing this we are going to create an INSTEAD OF trigger in place of the DELETE CASCADE option. One caveat when using an INSTEAD OF trigger is that you can't have a table with both a DELETE CASCADE foreign key constraint and an INSTEAD OF trigger. If we try to create a trigger on the Child2 table as things are setup now we'll get the following error.

Msg 2113, Level 16, State 1, Procedure DELETE_Child2, Line 8
Cannot create INSTEAD OF DELETE or INSTEAD OF UPDATE TRIGGER 'DELETE_Child2' on table 'dbo.Child2'. This
is because the table has a FOREIGN KEY with cascading DELETE or UPDATE.

To get around this restriction we have to remove the DELETE CASCADE option from the foreign key on the Child2 table before we can add the DELETE CASCADE option to the GrandChild tables foreign key and then add an INSTEAD OF trigger to the Parent table. I like to keep things consistent so having DELETE CASCADE on some of the tables foreign keys and using INSTEAD OF triggers on other tables becomes quite confusing and difficult to manage. Although this approach would work, I think a better solution is to remove the DELETE CASCADE option from all the foreign keys and simply use INSTEAD OF triggers on all of the tables to handle removing the child records. We can use the following code to remove the DELETE CASCADE option from all of the foreign key constraints.

-- drop constraints with DELETE CASCADE option
ALTER TABLE [dbo].[Child1] DROP CONSTRAINT [FK_Child1_Parent]
ALTER TABLE [dbo].[Child2] DROP CONSTRAINT [FK_Child2_Parent]
ALTER TABLE [dbo].[GrandChild] DROP CONSTRAINT [FK_GrandChild_Child1]
GO
-- recreate all foreign keys without DELETE CASCADE option
ALTER TABLE [dbo].[Child1] WITH CHECK
ADD CONSTRAINT [FK_Child1_Parent] FOREIGN KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
GO
ALTER TABLE [dbo].[Child2] WITH CHECK
ADD CONSTRAINT [FK_Child2_Parent] FOREIGN KEY([ParentID])
REFERENCES [dbo].[Parent] ([ParentID])
GO
ALTER TABLE [dbo].[GrandChild] WITH CHECK
ADD CONSTRAINT [FK_GrandChild_Child1] FOREIGN KEY([Child1ID])
REFERENCES [dbo].[Child1] ([Child1ID])
GO
ALTER TABLE [dbo].[GrandChild] WITH CHECK
ADD CONSTRAINT [FK_GrandChild_Child2] FOREIGN KEY([Child2ID])
REFERENCES [dbo].[Child2] ([Child2ID])
GO

Now that we no longer have any foreign keys with the DELETE CASCADE option set we can add INSTEAD OF triggers to each table to handle the deletion of the child records. Please take note of the fact that because we are using an INSTEAD OF trigger we also have to remove the records from the parent table itself after the records have been removed from the child tables. Here is the trigger code.

CREATE TRIGGER [DELETE_Parent]
ON dbo.[Parent]
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM [Child1] WHERE ParentID IN (SELECT ParentID FROM DELETED)
DELETE FROM [Child2] WHERE ParentID IN (SELECT ParentID FROM DELETED)
DELETE FROM [Parent] WHERE ParentID IN (SELECT ParentID FROM DELETED)
END
GO
CREATE TRIGGER [DELETE_Child1]
ON dbo.[Child1]
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM [GrandChild] WHERE Child1ID IN (SELECT Child1ID FROM DELETED)
DELETE FROM [Child1] WHERE Child1ID IN (SELECT Child1ID FROM DELETED)
END
GO
CREATE TRIGGER [DELETE_Child2]
ON dbo.[Child2]
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM [GrandChild] WHERE Child2ID IN (SELECT Child2ID FROM DELETED)
DELETE FROM [Child2] WHERE Child2ID IN (SELECT Child2ID FROM DELETED)
END
GO

To test that everything is working correctly we can run the following script and verify that all the child records are being removed as expected.

INSERT INTO Parent VALUES (1,'test')
INSERT INTO Parent VALUES (2,'test')
INSERT INTO Parent VALUES (3,'test')
INSERT INTO Parent VALUES (4,'test')
INSERT INTO Child1 VALUES (1,1,'test')
INSERT INTO Child2 VALUES (10,2,'test')
INSERT INTO Child1 VALUES (2,3,'test')
INSERT INTO Child2 VALUES (11,4,'test')
INSERT INTO GrandChild VALUES (1,1,null,'test')
INSERT INTO GrandChild VALUES (2,null,10,'test')
INSERT INTO GrandChild VALUES (3,2,null,'test')
INSERT INTO GrandChild VALUES (4,null,11,'test')
DELETE FROM Parent WHERE ParentID=1
DELETE FROM Parent WHERE ParentID=2

原文链接

Solving the SQL Server Multiple Cascade Path Issue with a Trigger (转载)的更多相关文章

  1. 灵活运用 SQL SERVER FOR XML PATH 转

    灵活运用 SQL SERVER FOR XML PATH   FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些 ...

  2. SQL Server FOR XML PATH 语句的应用---列转行

    经常在论坛看到高手使用了 for xml path,由于是搜索一下,记录了详细的使用方法.在SQL Server中利用 FOR XML PATH 语句能够把查询的数据生成XML数据,下面是它的一些应用 ...

  3. 使用SQL SERVER FOR XML PATH将多个结果集转换成一行并进行去重处理

    在一个医药行业的系统中需要根据患者的接触记录ID获取不同接触类型的集合,效果像这样     --患者接触记录信息,一个患者可以有N个不同的接触记录,每个接触记录又有N个接触类型记录 IF OBJECT ...

  4. 问题:sqlserver有没有类似Oracle的LISTAGG;结果: 灵活运用 SQL SERVER FOR XML PATH

    灵活运用 SQL SERVER FOR XML PATH FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前 ...

  5. 如何对SQL Server 2005进行设置以允许远程连接(转载)

    如何对SQL Server 2005进行设置以允许远程连接(转载) 在尝试从远程计算机连接到 Microsoft SQL Server 2005 实例时,可能会接收到错误消息.在使用任何程序连接到 S ...

  6. SQL SERVER将多行数据合并成一行(转载)

    昨天遇到一个SQL Server的问题:需要写一个储存过程来处理几个表中的数据,最后问题出在我想将一个表的一个列的多行内容拼接成一行 比如表中有两列数据 : ep_classes  ep_name A ...

  7. SQL Server 磁盘空间告急(磁盘扩容)转载

    一.背景 在线上系统中,如果我们发现存放数据库文件的磁盘空间不够,我们应该怎么办呢?新买一个硬盘挂载上去可以嘛?(linux下可以直接挂载硬盘进行扩容),但是我们的SQL Server是运行在Wind ...

  8. SQL Server 2012 OFFSET/FETCH NEXT分页示例(转载)

    原文:http://beyondrelational.com/modules/29/presentations/483/scripts/12983/sql-server-2012-server-sid ...

  9. SQL Server中使用convert进行日期转换(转载)

    一般存入数据库中的时间格式为yyyy-mm-dd hh:mm:ss 如果要转换为yyyy-mm-dd  短日期格式.可以使用convert函数.下面是sqlserver帮助中关于convert函数的声 ...

随机推荐

  1. JavaScript -- Select

    -----053-Select.html----- <!DOCTYPE html> <html> <head> <meta http-equiv=" ...

  2. mpvue使用scroll-view实现图片横向滑动

    html代码 <div class="swiper-home"> <scroll-view scroll-x="true" style=&qu ...

  3. postgresql 清空数据表数据

    在 mysql中,只需要执行: TRUNCATE table_name; 即可,数据会情况,而且自增id也会变回0: 但在 postgresql 则稍有不同,因为 postgresql 的自增id是通 ...

  4. Bootstrap in ASP.NET MVC 5

    一,新建ASP.NET MVC 5 项目 Bootstrap 文件分布 引入到页面 1.定义.注意:不要包含有.min.的文件名称,会被忽略,因为在发布的时候编译器会加载min版的文件 2.在母版页中 ...

  5. 玩转mongodb(八):分布式计算--MapReduce

    MongoDB提供了MapReduce的聚合工具来实现任意复杂的逻辑,它非常强大,非常灵活.MapReduce使用JavaScript作为“查询语言”,能够在多台服务器之间并行执行.它会将一个大问题拆 ...

  6. [error] 1507#0: *22 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 10.0.0.1, server: www.wordpress.com, request: "GET /info.p

    字体比较小,如果你遇到这个问题请仔细的把下面的总结看完. 环境:CentOS6.7.2.6.32-573.el6.x86_64.nginx1.12.2 .php5.5.38 问题:nginx能解析静态 ...

  7. es6学习笔记9--函数的扩展

    函数参数的默认值 基本用法 在ES6之前,不能直接为函数的参数指定默认值,为了避免这个问题,通常需要先判断一下参数y是否被赋值,如果没有,再等于默认值. ES6允许为函数的参数设置默认值,即直接写在参 ...

  8. PBN飞越转弯Flyover衔接TF、CF航段保护区组图

    PBN飞越转弯Flyover衔接TF.CF航段虽不常用,但也很重要,与旁切转弯有一定的相似性. 飞越转弯 flyover-TF/CF 叠加图: 飞越转弯 flyover-TF/CF 分解图:

  9. Linux中locate命令的实践总结

    locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案.其方法是先建立一个包括系统内所有档案名称及路径的数据库,之后当寻找时就只需查询这个数据库,而不必实际深入档案系统之中了.在一般的 di ...

  10. 本地SQL数据库执行作业定时修改其他数据库内容

    --exec sp_addlinkedserver 'xkp', ' ', 'SQLOLEDB', '192.168.66.66'  定义链接--exec sp_addlinkedsrvlogin ' ...