我在跟踪执行以下代码的顺序时遇到问题:
守则正常运作
我只是想了解如何。
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。
答案 0 :(得分:4)
T0 / Line1作为锚执行一次。
...
有一些评论
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
...