SQL Server - 如何删除递归行

时间:2012-09-19 20:35:59

标签: sql sql-server-2008

enter image description here

我有一个department表,我想从表中选择并删除departmentiddepartmentidparent的所有参考行以获取部门ID,我们假设departmentid=13

这意味着

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

在此,应从表中删除所有行。我很困惑,也没有任何想法如何解决它。

1 个答案:

答案 0 :(得分: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