34,576
社区成员
发帖
与我相关
我的任务
分享
create table tb(id int,name varchar(50),fatherid int)
insert into tb select 1,'a',0
insert into tb select 2,'b',1
insert into tb select 3,'c',2
insert into tb select 4,'d',3
insert into tb select 5,'e',4
insert into tb select 6,'f',5
insert into tb select 7,'g',6
go
declare @id int
set @id=3;
with dom as
(
select id,name,fatherid from tb where id=@id
union all
select a.id,a.name,a.fatherid from tb a join dom b on a.fatherid=b.id
)
select * from dom
--> By dobear_0922(小熊) 2008-11-06 17:25:10
--> 测试数据:@t
declare @t table([id] int,[name] varchar(1),[fatherID] int)
insert @t
select 1,'a',0 union all
select 2,'b',1 union all
select 3,'c',2 union all
select 4,'d',3 union all
select 5,'e',4 union all
select 6,'f',5 union all
select 7,'g',6
--select * from @t
declare @id int
set @id=3
;with nt as
(
select * from @t where id=@id
union all
select t.* from @t t join nt on t.[fatherID]=nt.[id]
)
select * from nt
/*
id name fatherID
----------- ---- -----------
3 c 2
4 d 3
5 e 4
6 f 5
7 g 6
(5 行受影响)
*/