表 A
id    fid    tid
1     12     5   
2     22     12
3     24     22
4     26     null
如果输入tid=5则输出:
id    fid    tid
1     12     5   
2     22     12
3     24     22    就是根据fid和tid之间的关联选择结果,12继承自5,22又继承自12,24又继承自22 所有上面结果
请教sql的写法.
分不够会追加

解决方案 »

  1.   


    --写个函数
    create function fn_Records(
    @Tid int
    )
    returns @R table (Id int,fid int,tid int)
    as
    begin
      insert @r select Id,fid,tid from a where tid=@Tid
      while exists (select 1 from a where tid in (select fid from @r) and id not in (select id from @R))
         insert @r select Id,fid,tid from a where tid in (select fid from @r) and id not in (select id from @R)
      return
    end
    go--调用
    select * from dbo.fn_Records(5)
      

  2.   

    create table A (id  int, fid  int,tid int)
    insert A
    select 1        ,   12        ,   5       
    union select 2     ,      22   ,        12 
    union select 3      ,     24   ,        22 
    union select 4      ,     26    ,null
    declare @str varchar(1000),@fid varchar(100)
    select @str=isnull(@str,'')+','+rtrim(id),@fid=isnull(@fid,'')+rtrim(fid) from A t where tid=5
    while @@rowcount>0
    begin
     select @str=@str+','+rtrim(id),@fid=rtrim(fid) from A t where tid=@fid
    end
    select * from A where charindex(','+rtrim(id)+',',@str+',')>0drop table A
      

  3.   

    create table A (id  int, fid  int,tid int)
    insert A
    select 1        ,   12        ,   5       
    union select 2     ,      22   ,        12 
    union select 3      ,     24   ,        22 
    union select 4      ,     26    ,null
    go
    create function f(@val int)
    returns varchar(8000)
    as
    begin
    declare @str varchar(1000),@fid varchar(100) select @str=isnull(@str,'')+','+rtrim(id),@fid=isnull(@fid,'')+rtrim(fid) from A t where tid=@val
    while @@rowcount>0
    begin
     select @str=@str+','+rtrim(id),@fid=rtrim(fid) from A t where tid=@fid
    end
    set @str=@str+','
    return @str
    end
    go
    select * from A where charindex(','+rtrim(id)+',',dbo.f(5))>0drop function f
    drop table A
    /*  结果
    id          fid         tid         
    ----------- ----------- ----------- 
    1           12          5
    2           22          12
    3           24          22(所影响的行数为 3 行)
    */