今天看别人用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