CTE如何在sql内部工作?

时间:2011-10-28 08:48:04

标签: sql-server common-table-expression

我在跟踪执行以下代码的顺序时遇到问题:

守则正常运作

我只是想了解如何。

    with MyCTE(x)
    as
    (
  1)  select x = convert(varchar(8000),'hello') // line 1
    union all
  3)  select x + 'a' from MyCTE where len(x) < 100 //line 3
    )
    select x from MyCTE
    order by x

MSDN:

  

递归执行的语义如下:

     

将CTE表达式拆分为锚点和递归成员。

     

运行锚定成员创建第一个调用或基本结果   设(T0)。

     

运行递归成员,其中Ti作为输入,Ti + 1作为输出。

     

重复步骤3,直到返回空集。

     

返回结果集。这是T0到Tn的UNION ALL。

阶段:

1)执行第1行(x =你好)

2)执行第3行(helloa)

3)现在它自称:所以x再次回到你好! (第1行)

  • 根据:line 1 ,每当cte调用自身时 - x总是应该重置! (或者在递归中绕过T0?)

  • (x)部分MyCTE(x)的作用是什么?输入或输出?

引用

  

运行递归成员,其中Ti作为输入,Ti + 1作为输出。

据我所知,(x)是out值,而不是Input。

1 个答案:

答案 0 :(得分:4)

T0 / Line1作为锚执行一次。

    执行
  1. 第1行(问候)
  2. 执行第3行(helloa)因为LEN(hello)= 5然后小于100
  3. 第3行被执行(helloaa),因为LEN(helloa)= 6小于100
  4. 执行
  5. 第3行(helloaaa)因为LEN(helloaa)= 7然后小于100
  6. 执行第3行(helloaaaa)因为LEN(helloaaa)= 8然后小于100
  7. 执行第3行(helloaaaa)因为LEN(helloaaaa)= 9然后小于100
  8. 执行第3行(helloaaaaa)因为LEN(helloaaaa)= 10而不是100
  9. ...

    有一些评论

    with MyCTE(x)
    as
    (
       select x = convert(varchar(8000),'hello')     -- Anchor, executed once
       union all
       select x + 'a' from MyCTE where len(x) < 100  -- Recursion, executed n times
    )
    select x from MyCTE order by x
    

    在运行时,这是

       select x = convert(varchar(8000),'hello')     -- Anchor
       union all
       select 'hello' + 'a'         -- Recursion 1
       union all
       select 'helloa' + 'a'        -- Recursion 2
       union all
       select 'helloaa' + 'a'       -- Recursion 3
       union all
       select 'helloaaa' + 'a'      -- Recursion 4
       union all
       select 'helloaaaa' + 'a'     -- Recursion 5
       ...