求一树形结构的sql

表结构:
id parent_id name

数据:
0 A
1 0 a
2 0 b
3 1 aa
4 1 saqwqw
5 2 ewqe
6 2 w112

。。。。。


我想写个sql,根据已知id上溯得到这个id的第二级数据的name,而不是根A(也就是在我列出的数据中始终得到的是a或者b这两个name,而不是A.打个比方)

作者: langxingcs   发布时间: 2011-06-13

SQL code
declare @id int
set @id=2
;with f as
(
select * from tb  where id=@id
union all
select a.* from tb a join f on a.parent_id =f.id
)
select name from f

作者: fredrickhu   发布时间: 2011-06-13

楼主举个例子,传入什么值,得到什么结果?

作者: htl258   发布时间: 2011-06-13

SQL code
create table tb(id int,parent_id int,name nvarchar(10))
insert into tb select 0,null,'A'
insert into tb select 1,0,'a'
insert into tb select 2,0,'b'
insert into tb select 3,1,'aa'
insert into tb select 4,1,'saqwqw'
insert into tb select 5,2,'ewqe'
insert into tb select 6,2,'w112'
go
declare @id int
set @id=5
;with cte as(
select * from tb where id=@id
union all
select a.* from tb a inner join cte b on a.id=b.parent_id where a.id<>0
)select * from cte a where not exists(select 1 from cte where id<a.id)
go
drop table tb
/*
id          parent_id   name
----------- ----------- ----------
2           0           b

(1 行受影响)

*/

作者: qianjin036a   发布时间: 2011-06-14