首页 > 代码库 > T-SQL使用CTE递归

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 ,                10SELECT  *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

  结果:

技术分享

 

T-SQL使用CTE递归