【问题标题】:How CTE works internal in sql?CTE如何在sql内部工作?
【发布时间】:2011-10-28 16:58:41
【问题描述】:

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

代码运行良好

我只是想了解如何。

    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=hello)

2) 执行第 3 行 (helloa)

3) 现在它这样称呼自己:这里 x 又回到了你好! (第 1 行)

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

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

引用:

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

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

【问题讨论】:

  • 这是一个理论问题,还是你运行过这个?
  • @gbn - 嗨! ,我已经运行它并且它的工作,但我不知道如何。 - whenever the cte calls itself - the x is always should be reset,但它没有(这很好)但我不知道为什么:它每次都说:select x = convert(varchar(8000),'hello')

标签: sql-server common-table-expression


【解决方案1】:

T0/Line1 作为锚点执行一次。

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

...

一些cmets

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

【讨论】:

  • 一如既往 - 你很棒。谢谢。问题是我认为1 行总是被执行....
猜你喜欢
  • 2018-12-13
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2019-01-13
  • 2010-10-14
  • 2013-09-28
相关资源
最近更新 更多