在工作中遇到一个问题,是需要sql递归查询的.不懂,我有一个A表结构如下:
id parentid(父节点) ClassName(分类名称)   
1     -1           根目录                                        
3     0            小说网络                                    
4     0            新闻资讯                                
5     0            报刊杂志                                       
6     5             报刊                                        
7     5            杂志                                       
另外一张B表结构如下
 id     ClassId(所属分类)    ApplyName(应用名称)                   
                  
0           杂志                爱的岁月
1           小说                狙杀
2            网络               梦三国
3
根据A表传入的ID找到其所以节点下的应用,有可能是一级也可能是无线级。

解决方案 »

  1.   

    不太明白 你那个小说网络 新闻资讯 报刊杂志 pid应该是1吧 你是sql2000还是2005还是?
      

  2.   

    http://www.yongfa365.com/Item/SQL-Di-Gui-Function-ID-ParentID.html
      

  3.   

    Declare @Id Int 
    Set @Id = 5;    ---在此修改父节点 With RootNodeCTE(Id,ParentId) 
    As 

    Select Id,ParentId From BOM Where ParentId In (@Id) 
    Union All 
    Select BOM.Id,BOM.ParentId From RootNodeCTE 
    Inner Join BOM
    On RootNodeCTE.Id = BOM.ParentId 
    ) Select * From RootNodeCTEhttp://topic.csdn.net/u/20080409/16/1fb7d941-b1a1-4326-a936-230ddf057cbe.html
      

  4.   


    create table A
    (
        id  int,
        ClassName varchar(100),
        parentid int
    )
    insert into A select 1,'根目录',-1
    union all select 3,'小说网络',1
    union all select 4,'新闻资讯',1
    union all select 5,'报刊杂志',1
    union all select 6,'报刊',5
    union all select 7,'杂志',5create table B
    (
        id  int,
        Class  varchar(100),
        ApplyName varchar(200)
    )
    insert into B select 0,'杂志','爱的岁月'
    union all select 1,'小说','狙杀'
    union all select 2,'网络','梦三国'
    union all select 4,'报刊','爱的岁月1'
    union all select 5,'杂志','狙杀1';with rs
    as 
    (
    select A.* from A  where A.id=5 
    union all 
    select A.* from A join rs on A.parentid=rs.id
    )
    select * from rs left join B on rs.ClassName=B.Class