如就是你上表的数据就简单了
select * from table where fatherid<>0如果还有别的数据就要知道一个对应的关系才行

解决方案 »

  1.   

    select * from table where fatherid>0
      

  2.   

    --创建函数
    create function f_cid(
    @id int
    )returns @re table(id int,level int)
    as
    begin
    declare @l int
    set @l=0
    insert @re select @id,@l
    while @@rowcount>0
    begin
    set @l=@l+1
    insert @re select a.id,@l
    from tb a,@re b
    where a.fatherid=b.id and b.level=@l-1
    end
    /*--如果只显示最明细的子(下面没有子),则加上这个删除
    delete a from @re a
    where exists(
    select 1 from tb where fatherid=a.id)
    --*/
    return
    end
    go--调用(查询所有的子)
    select a.*,层次=b.level from tb a,f_cid(1)b where a.id=b.id
    go
      

  3.   

    --树形数据查询示例
    --作者: 邹建--示例数据
    create table tb(id int identity(1,1),pid int,name varchar(20))
    insert tb select 0,'中国'
    union all select 0,'美国'
    union all select 0,'加拿大'
    union all select 1,'北京'
    union all select 1,'上海'
    union all select 1,'江苏'
    union all select 6,'苏州'
    union all select 7,'常熟'
    union all select 6,'南京'
    union all select 6,'无锡'
    union all select 2,'纽约'
    union all select 2,'旧金山'
    go--查询指定id的所有子
    create function f_cid(
    @id int
    )returns @re table(id int,level int)
    as
    begin
    declare @l int
    set @l=0
    insert @re select @id,@l
    while @@rowcount>0
    begin
    set @l=@l+1
    insert @re select a.id,@l
    from tb a,@re b
    where a.pid=b.id and b.level=@l-1
    end
    return
    end
    go--调用(查询所有的子)
    select a.*,层次=b.level from tb a,f_cid(2)b where a.id=b.id
    go--删除测试
    drop table tb
    drop function f_cid/*--测试结果id          pid         name                 层次          
    ----------- ----------- -------------------- ----------- 
    2           0           美国                   0
    11          2           纽约                   1
    12          2           旧金山                  1(所影响的行数为 3 行)
    --*/
      

  4.   

    取下级(只含到下下级)
    select id,fatherId
     from 表 a
    where  a.Fatherid = 给定值 
      or   a.Fatherid in ( select Id 
                            from 表 c 
                           where c.Fatherid = 给定值 )