一张数据表
     yh_gx(id,yh_id,p_id)
    yh_id 是用户号,p_id是用户的上级领导编号
    如
       id  yh_id p_id
       1    001   002
       2    003   001
       3    004   003       如何通过输入一个用户编号查出该用户的所有下级编号以及包括该用户的编号
  能否通过一条SQL语句查出!
如:   输入用户编号 001 ,查出他的所有下及 
                    003,004,还有他自己001
   能否用一条SQL语句查出呢!
  急等!

解决方案 »

  1.   

    declare @i int
    declare @temp table(id varchar(3),fg int)
    select @i=1
    insert into @temp values('001',@i)
    while (select id from @temp where fg=@i)<>''
    begin
    insert into @temp
    select yh_id ,fg=@i+1 from #tb where p_id in (select id from @temp where fg=@i)
    select @i=@i+1

    end
    select id from @temp
      

  2.   

    create proc return_id
    @str varchar(3)--用户号
    as
    begin
    declare @i int
    declare @temp table(id varchar(3),fg int)
    select @i=1
    insert into @temp values(@str,@i)
    while (select count(1) from @temp where fg=@i)<>''
    begin
    insert into @temp
    select yh_id ,fg=@i+1 from yh_gx where p_id in (select id from @temp where fg=@i)
    select @i=@i+1

    end
    select id from @temp
    end