How does a Recursive CTE run, line by line?

后端 未结 5 1973
情书的邮戳
情书的邮戳 2020-11-27 12:33

I think I\'ve got the format of Recursive CTEs down well enough to write one, but still find myself frustrated to no end that I cannot manually process one (pretend to be th

5条回答
  •  一生所求
    2020-11-27 13:11

    The algorithm that CTE use is:

    1. Execute the anchor part, get result r0
    2. Execute the recursive part, using r0 as input, and get result r1 (not null)
    3. Execute the recursive part, using r1 as input, and get result r2 (not null)
    4. Execute the recursive part, using r3 as input, and get result r3 (not null) ...
    5. Execute the recursive part, using r(n-1) as input, and output rn (null). This time rn is null, so we use UNION ALL to combine r0, r1, r2 ... r(n-1) and that's the final result

    Lets take an example:

    WITH    cte ( value )
              AS (
                   SELECT   1
                   UNION ALL
                   SELECT   value + 1
                   FROM     cte
                   WHERE    value < 4
                 )
        SELECT  *
        FROM    cte
    

    The result of this query is:

    value
    -----------
    1
    2
    3
    4
    
    (4 row(s) affected)
    

    Let's examine it step by step:

    Execute anchor query (SELECT 1), we got:
      r0 = 1
      cte = r0 = 1
    
        |
        |
        V
    
    Now we execute
    SELECT value + 1 FROM cte WHERE value < 4
    Since cte is r0 (only has 1), we got:
      r1 = 2
      cte = r1 = 2
    
        |
        |
        V
    
    Now we execute
    SELECT value + 1 FROM cte WHERE value < 4
    Since cte is r1 (only has 2), we got:
      r2 = 3
      cte = r2 = 3
    
        |
        |
        V
    
    Now we execute
    SELECT value + 1 FROM cte WHERE value < 4
    Since cte is r2 (only has 3), we got:
      r3 = 4
      cte = r3 = 4
    
        |
        |
        V
    
    Now we execute
    SELECT value + 1 FROM cte WHERE value < 4
    Since cte is r3 (only has 4), we got:
      r4 = NULL (because r3 (4) is equal to 4, not less than 4)
    Now we stop the recursion!
    
        |
        |
        V
    
    Let's calculate the final result:
    R = r0 union all
        r1 union all
        r2 union all
        r3 union all
      = 1 union all
        2 union all
        3 union all
        4 union all
      = 1
        2
        3
        4
    

提交回复
热议问题