昨晚看的书,发现可以用T-SQL 实现自定义递归,其实也就是变相的 foreach 直接上代码 ,不懂得可问:

  

 1 declare @t table (id int ,pid int ,[name] nvarchar(50),col int )
 2 -- id 增量id  pid该数据的上级增量id   name 名称
 3 declare @id int ,@col int
 4 set @id = 2
 5 set @col = 0
 6 
 7 insert into @t select id,pid,[name],@col from  dbo.CTE where id=@id
 8 
 9 while @@rowcount >0 
10 begin 
11         set @col = @col+1 
12         insert into @t 
13         select CTE.id,CTE.pid,CTE.[name],@col from  dbo.CTE CTE    
14         --inner join @t tab on  tab.col + 1 =@col and  tab.pid= cte.id --从下往上找
15         inner join @t tab on  tab.col + 1 =@col and  tab.id= cte.pid --从上往下找
16 end
17 
18 select * from  @t
View Code

  

  表中数据如下:

  

    id       pid             name
    ----------- ----------- --------------------------------------------------
    1    NULL          经理
    2    1           副经理1
    3    1       副经理2
    4    1       副经理3
    5    2       副经理1下面的人1
    6    2       副经理1下面的人2
    7    2       副经理1下面的人3
    8    5       民工

  下次有时间再发一些其他研究的话题。

  

posted on 2013-06-26 13:24  小明@  阅读(380)  评论(0)    收藏  举报