递归返回结果显示,求sql或者思路,谢谢!
表:tb
p_id id name
null 1 aa
1 2 bb
2 3 cc
3 4 dd
3 5 ee
希望出现的查询结果
列1 列2 列3 列4 列5 列6 列7 列8 列9
null 1 aa 2 bb 3 cc 4 dd
null 1 aa 2 bb 3 cc 5 ee
就是只按照level最大的行显示,但是如何能将上层节点作为列显示呢?
做多个表然后关联查询速度太慢,希望能直接用语句实现,谢谢!
问题点数:30、回复次数:2Top
1 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-02-24 11:17:09 得分 30
--生成测试数据
create table tb(
p_id int,
id int,
name varchar(10))
insert into tb select null,1,'aa'
insert into tb select 1 ,2,'bb'
insert into tb select 2 ,3,'cc'
insert into tb select 3 ,4,'dd'
insert into tb select 3 ,5,'ee'
--执行查询过程
declare @s varchar(8000)
declare @i int
declare @n int
set @i = 1
select p_id,id,name,@i as level into temp from tb where p_id is null
while exists(select 1 from tb a,temp b where a.p_id = b.id and b.level = @i)
begin
insert into temp
select a.*,(@i+1) from tb a,temp b where a.p_id = b.id and b.level = @i
set @i = @i + 1
end
print @i
set @n = @i
set @s = ''
while @n > 0
begin
set @s = ',p_id'+rtrim(@n)+' int,id'+rtrim(@n)+' int,name'+rtrim(@n)+' varchar(10)' + @s
set @n = @n - 1
end
set @s = 'create table temp1('+stuff(@s,1,1,'')+')'
exec(@s)
set @n = @i
while @n>0
begin
set @s = 'insert into temp1(p_id'+rtrim(@n)+',id'+rtrim(@n)+',name'+rtrim(@n)+')
select a.p_id,a.id,a.name from temp a where a.level ='+rtrim(@n)+'
and not exists(select 1 from temp where p_id = a.id)'
exec(@s)
if(@n!=@i)
begin
set @s = 'update temp1
set
p_id'+rtrim(@n)+' = b.p_id,
id' +rtrim(@n)+' = b.id ,
name'+rtrim(@n)+' = b.name
from
temp1 a,temp b
where
a.p_id'+rtrim(@n+1)+'=b.id'
exec(@s)
end
set @n = @n - 1
end
select * from temp1
--删除临时表
drop table temp
drop table temp1Top
2 楼eTopFancy(你的美丽我的回忆)回复于 2005-03-01 10:18:30 得分 0
study!!Top




