4

在此处输入图像描述

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

这意味着

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

在此应从表中删除所有行。我很困惑,不知道如何解决它。

4

1 回答 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
于 2012-09-19T20:46:06.337 回答