有一张表如下:
NodeId(int) ParentId(int) NodeName(varchar(50))
1 NULL 1
2 1 1.1
3 NULL 2
4 3 2.1
5 9 2.2.2.1
6 4 2.1.1
7 3 2.2
8 7 2.2.1
9 7 2.2.2
想要的结果如下:
NodeName 
1
1.1
2
2.1
2.1.1
2.2
2.2.1
2.2.2
2.2.2.1想用递归算法来实现。在oracle 中可以用
select * 
from table1
connect by nodeId=Parentid
start with parentId is null问题是在SQL中怎么实现呢。我描述不知道清楚不 ?
。。请大家帮忙。。谢谢

解决方案 »

  1.   

    刚写错了 。在oracle 中应该是:
    select * 
    from table1
    connect by prior nodeId=Parentid
    start with parentId is null
      

  2.   


    Create table tree (NodeId int ,ParentId int, NodeName nvarchar(50) )
    insert into tree 
    select 
    1, NULL, '1'
    union select 2, 1, '1.1'
    union select 3, NULL, '2'
    union select 4, 3, '2.1'
    union select 5, 9, '2.2.2.1'
    union select 6, 4, '2.1.1'
    union select 7, 3, '2.2'
    union select 8, 7 ,'2.2.1'
    union select 9, 7, '2.2.2'
    select * from tree
    order by nodename
      

  3.   

    NodeId      ParentId    NodeName                                           
    ----------- ----------- -------------------------------------------------- 
    1           NULL        1
    2           1           1.1
    3           NULL        2
    4           3           2.1
    6           4           2.1.1
    7           3           2.2
    8           7           2.2.1
    9           7           2.2.2
    5           9           2.2.2.1(9 row(s) affected)
      

  4.   

    错了啊!我只是举个例子,NodeName 才可以用order by 排序,巧合得到。
    实际上不是这样。是 有关树型或递归。