SQL Server - 如何删除递归行

标签 sql sql-server-2008

enter image description here

我有一个 department表,我想选择并删除departmentid的所有引用行和 departmentidparent从部门 ID 表中,让我们假设 departmentid=13 .

这意味着

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

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

最佳答案

带 sample 表

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

关于SQL Server - 如何删除递归行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12502502/

相关文章:

php - 比较mysql中的两个逗号分隔值并获取匹配的计数

sql-server-2008 - 有很多长文本字段的SQL表的最佳数据类型

sql-server - 在多个服务器上的多个数据库上执行存储过程 SQL Server

sql-server - 调用-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server

sql - 在 oracle 中划分日期范围

sql-server-2008 - 无法在 SQL Server 2008 中注册默认实例 MSSQLSERVER

mysql - 如何检查数据库表中是否存在某个元素?

java - 从 spring 属性加载 SQL 不运行

sql - 计算 SQL 中 2 个日期之间的差异,不包括周末

sql - 如何在不丢失小时、分钟和秒的情况下向 Hive 时间戳添加天数