--查询的函数
create function f_qry(
@id int, --要查询的id
@level int --要查询的级数
)returns @re table(id int primary key,level int)
as
begin
declare @l int
set @l=1 --方法1,不包含本级
insert @re select id,@l
from 表
where RefID=@id
while @@rowcount>0 and @l<@level /*--方法2,包含本级
insert @re select @id,@l
while @@rowcount>0 and @l<=@level
--*/
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a 
join @re b on a.RefID=b.id and b.level=@l-1
end
return
end
go--调用
select * from f_qry(1,3)--如果还要显示它的详细信息
select a.*,b.level
from 表 a join f_qry(1,3) b on a.id=b.id

解决方案 »

  1.   

    --测试--测试数据
    create table 表(ID int,Name varchar(10),RefID int)
    insert 表 select 1,'aa',0
    union all select 2,'bb',1    -- 是1的下线
    union all select 3,'cc',1    -- 也是1的下线
    union all select 4,'dd',2    -- 是2的1级下线, 是1的2级下线
    union all select 5,'ee',3    -- 是3的1级下线, 是1的3级下线
    union all select 6,'er',4    -- 是4的1级下线, 是1的4级下线
    go--查询的函数
    create function f_qry(
    @id int, --要查询的id
    @level int --要查询的级数
    )returns @re table(id int primary key,level int)
    as
    begin
    declare @l int
    set @l=1 --方法1,不包含本级
    insert @re select id,@l
    from 表
    where RefID=@id
    while @@rowcount>0 and @l<@level /*--方法2,包含本级
    insert @re select @id,@l
    while @@rowcount>0 and @l<=@level
    --*/
    begin
    set @l=@l+1
    insert @re select a.id,@l
    from 表 a 
    join @re b on a.RefID=b.id and b.level=@l-1
    end
    return
    end
    go--调用
    select * from f_qry(1,3)--如果还要显示它的详细信息
    select a.*,b.level
    from 表 a join f_qry(1,3) b on a.id=b.id
    go--删除测试
    drop table 表
    drop function f_qry/*--测试结果id          level       
    ----------- ----------- 
    2           1
    3           1
    4           2
    5           2
    6           3(所影响的行数为 5 行)ID          Name       RefID       level       
    ----------- ---------- ----------- ----------- 
    2           bb         1           1
    3           cc         1           1
    4           dd         2           2
    5           ee         3           2
    6           er         4           3(所影响的行数为 5 行)
    --*/