我有一个department
表,我想从表中选择并删除departmentid
和departmentidparent
的所有参考行以获取部门ID,我们假设departmentid=13
这意味着
Departmentid departmentidparent
13 13
14 13
15 13
16 14
17 14
在此,应从表中删除所有行。我很困惑,也没有任何想法如何解决它。
答案 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