T-SQL使用CTE递归

DECLARE @DiGui TABLE ( Id INT, ParentId INT )
INSERT  INTO @DiGui
        ( Id ,
          ParentId 
        )
        SELECT  1 ,
                2
        UNION
        SELECT  2 ,
                3
        UNION
        SELECT  3 ,
                4
        UNION
        SELECT  5 ,
                10
        UNION
        SELECT  1 ,
                10
SELECT  *
FROM    @DiGui ;
WITH    temp ( [Id], [parentid] )
          AS ( SELECT   Id ,
                        parentid
               FROM     @DiGui
               WHERE    [Id] = 1
               UNION ALL
               SELECT   a.Id ,
                        a.parentid
               FROM     @DiGui a
                        INNER JOIN temp ON a.[Id] = temp.[parentid]
             )
    SELECT  *
    FROM    temp

  结果:

 

posted @ 2017-04-08 20:31  小银光  阅读(228)  评论(0编辑  收藏  举报