写个函数
create function fn_Materiel(
@Materiel varchar(30)
)
returns @r table (
Layer     int,
Materiel varchar(30)
)
as
begin
    declare @Layer int
    set @Layer=1
    insert @r values (@Layer,@Materiel)
    while exists (select 1 from tableA a,@r t
        where a.Parent=t.Materiel and t.Layer=@Layer
        )
    begin
        insert @r select @Layer+1,Child from tableA a,@r t
        where a.Parent=t.Materiel and t.Layer=@Layer
        set @Layer=@Layer+1
    end
    return
endgo--调用
select * from dbo.fn_Materiel('A')

解决方案 »

  1.   

    它说这行有点错误:
    while exists (select 1 from tableA a,@r t
    无法解决 equal to 操作的排序规则冲突。
      

  2.   

    如果你用的SQLSERVER2005就好办了,如下create table tableA
    (parent varchar(10),
    child varchar(10)
    )
    go
    insert into tableA
    select  'A','B'
    union all
    select 'A','C'
    union all 
    select 'B','D'
    union all
    select 'B','E'
    union all
    select 'e','f'
    union all
    select 'e','g'
    go
    select * from tablea
    gowith tablecte(child,lvl) as
    (
    select child,2 from tablea where parent='a'
    union all
    select b.child,lvl+1
    from tablecte a join tablea b
    on a.child=b.parent
    where b.parent in (select  parent from tablea)
    )
    select 'a' as materiel , 1 as layer
    union all 
    select * from tablecte
      

  3.   

    结果为:materiel layer
    a 1
    B 2
    C 2
    D 3
    E 3
    f 4
    g 4
      

  4.   

    查询出来的数据排序上,能不能不按照层排,比如:
    A是第一层,A下面有B和C,但B下面有D和E,我想它们显示出来的顺序是:
       Layer  Materiel
       1      A
       2      B
       3      D
       3      E
       2      C
      

  5.   

    将2楼的改一改可以用了:
    if object_id('fn_Materiel') is not null
    drop function fn_Materiel
    go
    create function fn_Materiel(
    @Materiel varchar(30)
    )
    returns @r table (
    Layer     int,
    Materiel varchar(30),
    FarterM varchar(300)
    )
    as
    begin
        declare @Layer int
        set @Layer=1
        declare @FarterM varchar(300)
        set @FarterM=@Materiel+'|'
        insert @r values (@Layer,@Materiel,@FarterM)
        while exists (select 1 from tableA a,@r t
            where  a.Parent=t.Materiel and t.Layer=@Layer
            )
        begin
            insert @r select @Layer+1,Child,t.FarterM+Child+'|' from tableA a,@r t
            where a.Parent=t.Materiel and t.Layer=@Layer
            set @Layer=@Layer+1    end
        return
    endgo--调用
    select * from dbo.fn_Materiel('A') order by FarterM,Layer谢谢2楼和5楼朋友的帮忙.
      

  6.   

    不过好像在繁体的数据库运行就不行,在简体的数据库就没问题.
    有没有办法解决这问题呢?
    因为这是要做在一个繁体(Chinese_Taiwan-Stroke-CI_AS)数据库上的.