--创建处理的自定义函数
create function f_id()
returns @re table(id int,sid varchar(8000),level int)
as
begin
--为了数字排序正常,需要统一编码宽度
declare @idlen int,@idheader varchar(20)
select @idlen=max(len(id))
,@idheader=space(@idlen)
from 表

declare @l int
set @l=0
insert into @re select id,right(@idheader+cast(id as varchar),@idlen),@l
from 表 
where parentid=0
while @@rowcount>0
begin
set @l=@l+1
insert into @re select a.id,b.sid+','+right(@idheader+cast(a.id as varchar),@idlen) ,@l
from 表 a inner join @re b on a.parentid=b.id and b.level=@l-1
end
return
end
go--查询
select name=space(b.level*4)+a.name
from 表 a join f_id() b on a.id=b.id
order by b.sid
go

解决方案 »

  1.   

    --测试--测试数据
    create table 表(id int,name varchar(10),parentid int)
    insert 表 select 1,'a',0
    union all select 2,'b',1
    union all select 3,'c',1
    union all select 4,'d',0
    union all select 5,'e',3
    union all select 6,'f',2
    union all select 7,'g',4
    go--创建处理的自定义函数
    create function f_id()
    returns @re table(id int,sid varchar(8000),level int)
    as
    begin
    --为了数字排序正常,需要统一编码宽度
    declare @idlen int,@idheader varchar(20)
    select @idlen=max(len(id))
    ,@idheader=space(@idlen)
    from 表

    declare @l int
    set @l=0
    insert into @re select id,right(@idheader+cast(id as varchar),@idlen),@l
    from 表 
    where parentid=0
    while @@rowcount>0
    begin
    set @l=@l+1
    insert into @re select a.id,b.sid+','+right(@idheader+cast(a.id as varchar),@idlen) ,@l
    from 表 a inner join @re b on a.parentid=b.id and b.level=@l-1
    end
    return
    end
    go--查询
    select name=space(b.level*4)+a.name
    from 表 a join f_id() b on a.id=b.id
    order by b.sid
    godrop table 表
    drop function f_id/*--测试结果name                 
    ---------------------
    a
        b
            f
        c
            e
    d
        g(所影响的行数为 7 行)
    --*/