sql cte 递归用法

今天看别人用sql语句写出了一个日历,感觉挺不错的。语句里面用了sql的CTE这个是在sql2005才出现的,主要方便在sql里面实现递归。于是自己就写了一个递归的小例子。

create table Test
(
id varchar(30),
name varchar(30),
par_id varchar(30),
)
insert Test select '001','湖北','000'
union all select '002','武汉','001'
union all select '003','襄樊','002'
union all select '004','保康','003'
union all select '005','马良','004'
union all select '006','歇马','004'
union all select '007','两峪','005'

展示的树结构如下

湖北
|__武汉
    |_襄樊
       |_保康
     歇马_|_马良  
                  |_两峪

用sql语句实现如下

;with pro
as
(
select * from test where name='保康'
union all
select t.* from test t,pro p where t.par_id=p.id
)
select * from pro

这是由父节点找子节点

;with pro
as
(
select * from test where name='保康'
union all
select t.* from test t,pro p where t.id=p.par_id
)
select * from pro

这是由子节点找父节点

;with pro
as
(
select * from test where name='保康'
union all
select t.* from test t,pro p where t.par_id=p.id
)
select * from pro

 

来自: http://hi.baidu.com/cyj380236628/blog/item/c2464ec2e510c7160ef4778a.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值