SqlServer里,如何一条sql进行递归删除?

游北亮
博客专家认证
2010-09-09 07:38:01
我知道可以递归检索,如:
CREATE TABLE [aaa](
[id] [int] NULL,
[pid] [int] NULL,
[name] [nchar](10)
)
GO
INSERT INTO aaa VALUES(1,0,a)
INSERT INTO aaa VALUES(2,0,b)
INSERT INTO aaa VALUES(3,1,c)
INSERT INTO aaa VALUES(4,1,d)
INSERT INTO aaa VALUES(5,2,e)
INSERT INTO aaa VALUES(6,3,f)
INSERT INTO aaa VALUES(7,3,g)
INSERT INTO aaa VALUES(8,4,h)
GO

下面的Sql是查询出1结点的所有子结点
with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
select * from my1



我现在想删除1结点和所有子结点,不想用存储过程
但是发现一条sql实现不了:
with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from my1
错误:派生表 'my1' 不可更新,因为其定义中包含 UNION 运算符。


delete from aaa where id in(
with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
select * from my1
)
这个错误更多:
消息 156,级别 15,状态 1,第 2 行
关键字 'with' 附近有语法错误。
消息 319,级别 15,状态 1,第 2 行
关键字 'with' 附近有语法错误。如果此语句是公用表表达式或 xmlnamespaces 子句,那么前一个语句必须以分号结尾。
消息 102,级别 15,状态 1,第 6 行
')' 附近有语法错误。
...全文
489 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
youyou2404 2010-09-09
  • 打赏
  • 举报
回复
游北亮 2010-09-09
  • 打赏
  • 举报
回复
散分散分,就当学习帖了
黄_瓜 2010-09-09
  • 打赏
  • 举报
回复


[Quote=引用 2 楼 youbl 的回复:]
刚说完就试验出来了

with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)
[/Quote]恭喜,蹭分
ws_hgo 2010-09-09
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 youbl 的回复:]
刚说完就试验出来了

with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)
[/Quote]
恭喜
nalnait 2010-09-09
  • 打赏
  • 举报
回复
study...
hao1hao2hao3 2010-09-09
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 youbl 的回复:]
刚说完就试验出来了

with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)
[/Quote]

这么快!那就接分了。
游北亮 2010-09-09
  • 打赏
  • 举报
回复
刚说完就试验出来了

with my1 as(select * from aaa where id = 1
union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)
游北亮 2010-09-09
  • 打赏
  • 举报
回复
请教,有没有办法一条sql进行递归删除呢?

不要存储过程,谢谢。

22,298

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧