SQL 递归查询

CREATE TABLE [ptable](
 [id] [int] NULL,
 [pid] [int] NULL,
 [name] [nchar](10)
)
GO
INSERT INTO ptable VALUES(1,0,'a')
INSERT INTO ptable VALUES(2,0,'b')
INSERT INTO ptable VALUES(3,1,'c')
INSERT INTO ptable VALUES(4,1,'d')
INSERT INTO ptable VALUES(5,2,'e')
INSERT INTO ptable VALUES(6,3,'f')
INSERT INTO ptable VALUES(7,3,'g')
INSERT INTO ptable VALUES(8,4,'h')
GO

--查询出1结点的所有子结点
with tmp as(select * from ptable where id = 1
 union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
)
select * from tmp 

--查询出8结点的所有父结点
with tmp as(select * from ptable where id = 8
 union all select ptable.* from tmp, ptable where tmp.pid = ptable.id
)
select * from tmp;

--递归删除1结点和所有子结点的语句:
with tmp as(select * from ptable where id = 1
   union all select ptable.* from tmp, ptable where tmp.id = ptable.pid
)
delete from ptable where exists (select id from tmp where tmp.id = ptable.id) 

转载于:https://www.cnblogs.com/pato/archive/2012/03/31/2427210.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值