CTE如何在sql内部工作



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

代码运行正常

我只是想弄明白。

    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

阶段:

(x=hello)

2)第3行执行(hello)

3)现在它调用自己so:这里x再次回到hello !!(第一行)

  • 根据:line 1,无论何时cte调用自己- x总是应该重置!(或者在递归中忽略了T0 ?)

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

:

运行以Ti为输入、Ti+1为输出的递归成员

据我所知,(x)是输出值,而不是输入。

T0/Line1作为锚执行一次。

  1. 第一行被执行(hello)
  2. 第3行执行(hello),因为LEN(hello) = 5小于100
  3. 第3行执行(helloaa),因为LEN(helloa) = 6小于100
  4. 第3行执行(helloaaa),因为LEN(helloaa) = 7小于100
  5. 第3行执行(helloaaa),因为LEN(helloaaa) = 8小于100
  6. 第3行被执行(helloaaaaa),因为LEN(helloaaaaa) = 9小于100
  7. 第3行被执行(helloaaaaaa),因为LEN(helloaaaa) = 10小于100

有一些注释

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
   ...

最新更新