递归查询AAA表字段
ID(自动编号) strNum1(主编号)strNum2(次编号)    intTaxis(顺序)
1              01              001               1                
2              001             011               2
3              001             010               1
6              01              002               2
4              002             021               1
5              002             022               2
......
搜索出来的结果如下:当查询 01 时结果如下01(主层)(包含001、002)
001(次层)(包含011、010)
010(次次层)(按顺序排列 1)
011(次次层)(按顺序排列 2)
002(次层)(包含021、022)
021(次次层)(按顺序排列 1)
022(次次层)(按顺序排列 2)
......当查询 001 时结果如下 
001(主层)(包含011、010)
010(次层)(按顺序排列 1)
011(次层)(按顺序排列 2)请教大家有什么简洁的好方法查询出来呢?

解决方案 »

  1.   

    SQL Server 2000环境下参考:--生成测试数据
    create table BOM(ID INT,PID INT,MSG VARCHAR(1000))
    insert into BOM select 1,0,NULL
    insert into BOM select 2,1,NULL
    insert into BOM select 3,1,NULL
    insert into BOM select 4,2,NULL
    insert into BOM select 5,3,NULL
    insert into BOM select 6,5,NULL
    insert into BOM select 7,6,NULL
    go--创建用户定义函数
    create function f_getChild(@ID VARCHAR(10))
    returns @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
    as
    begin
        declare @i int,@ret varchar(8000)
        set @i = 1
        insert into @t select ID,PID,@i from BOM where PID = @ID
        
        while @@rowcount<>0
        begin
            set @i = @i + 1
            
            insert into @t 
            select 
                a.ID,a.PID,@i 
            from 
                BOM a,@t b 
            where 
                a.PID=b.ID and b.Level = @i-1
        end
        return
    end
    go--执行查询
    select ID from dbo.f_getChild(3)
    go--输出结果
    /*
    5
    6
    7
    */--删除测试数据
    drop function f_getChild
    drop table BOM
      

  2.   

    在SQL Server2005中其实提供了CTE[公共表表达式]来实现递归:  关于CTE的使用请查MSDN  
    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 RootNodeCTE
      

  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 RootNodeCTE正解
      

  4.   

    本帖最后由 libin_ftsafe 于 2008-04-09 16:54:20 编辑
      

  5.   

    钻石的高度,难以企及啊!
    向 libin_ftsafe  学习!