删除SQL表中的分层数据

编程入门 行业动态 更新时间:2024-10-28 04:22:24
本文介绍了删除SQL表中的分层数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含分层数据的表格.列ParentId",其中包含其父项的 Id(ID" - 键列).

I have a table with hierarchical data. A column "ParentId" that holds the Id ("ID" - key column) of it's parent.

删除一行时,我想删除所有子项(所有级别的嵌套).

When deleting a row, I want to delete all children (all levels of nesting).

怎么做?

谢谢

推荐答案

当行数不是太大时,erikkallen 的递归方法有效.

When the number of rows is not too large, erikkallen's recursive approach works.

这是使用临时表收集所有子项的替代方法:

Here's an alternative that uses a temporary table to collect all children:

create table #nodes (id int primary key) insert into #nodes (id) values (@delete_id) while @@rowcount > 0 insert into #nodes select distinct child.id from table child inner join #nodes parent on child.parentid = parent.id where child.id not in (select id from #nodes) delete from table where id in (select id from #nodes)

它从带有@delete_id 的行开始并从那里下降.where 语句是为了防止递归;如果您确定没有,则可以将其省略.

It starts with the row with @delete_id and descends from there. The where statement is to protect from recursion; if you are sure there is none, you can leave it out.

更多推荐

删除SQL表中的分层数据

本文发布于:2023-10-19 07:16:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506770.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!