SQL Server - 如何删除递归行

4

enter image description here

我有一个department表,我想选择并删除该表中与部门ID和父级部门ID相关的所有引用行,假设departmentid=13

这意味着:

Departmentid         departmentidparent
13                     13
14                     13
15                     13
16                     14
17                     14

在这个表格中,所有行都应该被删除。我非常困惑,并不知道该如何解决。

所以,您想删除任何祖先中部门ID = 13的部门? - Mark Sherretta
1个回答

7

使用样本表

create table tbl (departmentid int, departmentidparent int)
insert tbl select 13,13
insert tbl select 14,13
insert tbl select 15,13
insert tbl select 16,14
insert tbl select 17,11
insert tbl select 115,17

这是能够满足你需求的查询语句。
;with cte as
(
select *
 from tbl
 where departmentid=13
 union all
 select tbl.*
 from tbl
 join cte on tbl.departmentidparent=cte.departmentid
 -- the next line is only required because the sample data has parent=self!
 where tbl.departmentid!=cte.departmentid
)
delete tbl
from cte
where tbl.departmentid = cte.departmentid

不,我没有,真的。你应该试一试。 :) - RichardTheKiwi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接