从子项删除父项/删除整个树

时间:2016-12-19 10:55:14

标签: sql sql-server triggers sql-delete cascading-deletes

在循环中删除父级和子级

表1(父表)

Id  int 

表2(关系表)

Id1 int FOREIGN KEY (Id1) REFERENCES Table1 (Id)    
Id2 int FOREIGN KEY (Id2) REFERENCES Table1 (Id)

Id - Id1 one to one or one to zero relationship 
Id - Id2 one to many

表1中的数据

Id
1
2
3
4
5
6
7
8
9
10    

表2中的数据

Id1 Id2
2   1
3   1
4   2
5   2
6   4
7   4
8   5
9   5

所以它就像一棵树,根为1

1 has two childs 2 and 3
2 has two childs 4 and 5
4 has two childs 6 and 7
5 has two childs  8 and 9
3,6,7,8,9,10 has no child

实现下述情况的最佳方式:

删除1 =>删除完整的table2和table1(表1中的10除外)

2 个答案:

答案 0 :(得分:0)

您可以使用Recursive CTE

执行此操作
;WITH cte
     AS (SELECT Id1,
                Id2,
                id2 AS parent
         FROM   Yourtable
         UNION ALL
         SELECT a.Id1,
                a.Id2,
                b.Id2
         FROM   cte a
                JOIN Yourtable b
                  ON a.parent = b.id1)
SELECT *
FROM   cte
WHERE  parent = 1
OPTION (maxrecursion 0)
--DELETE FROM Yourtable
--WHERE  id1 IN (SELECT id1
--             FROM   cte
--             WHERE  parent = 1)
--OPTION (maxrecursion 0) 

如果select返回预期结果,则对select发表评论并取消评论Delete

答案 1 :(得分:0)

尝试

update table2 set id2 = null;
delete from table1 where id <> 10;
delete from table2;
相关问题