create table tb1
(ChildId int,Fatherid int)insert into tb1
select 1,0 union all
select 2,0 union all
select 3,1 union all
select 4,1 union all
select 5,2 union all
select 6,2 union all
select 7,2 union all
select 8,3 union all
select 9,4 union all
select 10,5 union all
select 11,6gocreate function tmpfun(@p int,@q int)
returns varchar(30)
as
begindeclare @str varchar(30)set @str=cast(@q as varchar(10))while exists(select 1 from tb1 where ChildId=@p and Fatherid =@q)
 
select @str=@str+' '+cast (@p as varchar(10)),
@p=(select top 1 ChildId from tb1 where Fatherid =@p),
@q =ChildId
from tb1 a 
where  ChildId=@p 
and Fatherid =@q
return @strendgoselect dbo.tmpfun(ChildId,Fatherid) from tb1 a /*
0 1 3 8
0 2 5 10
1 3 8
1 4 9
2 5 10
2 6 11
2 7
3 8
4 9
5 10
6 11*/goselect dbo.tmpfun(ChildId,Fatherid) from tb1 a 
where exists(select 1 from tb1 where Fatherid=a.ChildId )/*
0 1 3 8
0 2 5 10
1 3 8
1 4 9
2 5 10
2 6 11*/
godrop function tmpfun
drop table tb1

解决方案 »

  1.   

    create table tb1
    (ChildId int,Fatherid int)insert into tb1
    select 1,0 union all
    select 2,0 union all
    select 3,1 union all
    select 4,1 union all
    select 5,2 union all
    select 6,2 union all
    select 7,2 union all
    select 8,3 union all
    select 9,4 union all
    select 10,5 union all
    select 11,6gocreate function fn_FirstChild(@f int)
    returns varchar(300)
    as
    begindeclare @str varchar(300)set @str=cast(@f as varchar(10))if exists(select 1 from tb1 where Fatherid =@f)
    select top 1 @str=@str+' '+ dbo.fn_FirstChild(ChildId) from tb1 where Fatherid =@f
    return @strendgo--实现功能
    select '0 '+ dbo.fn_FirstChild(ChildId) as result from tb1 where Fatherid =0
      

  2.   

    create table tb1
    (ChildId int,Fatherid int)insert into tb1
    select 1,0 union all
    select 2,0 union all
    select 3,1 union all
    select 4,1 union all
    select 5,2 union all
    select 6,2 union all
    select 7,2 union all
    select 8,3 union all
    select 9,4 union all
    select 10,5 union all
    select 11,6gocreate function fn_FirstChild(@f int)
    returns varchar(300)
    as
    begindeclare @str varchar(300)set @str=cast(@f as varchar(10))if exists(select 1 from tb1 where Fatherid =@f)
    select top 1 @str=@str+' '+ dbo.fn_FirstChild(ChildId) from tb1 where Fatherid =@f
    return @strendgo--实现功能
    select '0 '+ dbo.fn_FirstChild(ChildId) as result from tb1 where Fatherid =0-------------------------------------------
    不好
    -------------------------------------------
    关系被损坏了
    因该要显示所有的父子关系如求1的家族
    应该是:
    1   3    8

    1    3   9
    这样才对
    不然品什么把1   3   9  给丢掉了
    相信楼主也是这意思