Why does this CTE act like a counter?

喜欢而已 提交于 2019-12-24 07:47:37

问题


The behaviour of the following query is different from my understanding of CTE, can someone elaborate why this is so?

with cte (n) as
(
    select 1
    union all
    select n + 1 from cte where n<10
)
select * from cte

I'm expecting the following output:

1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10

But I'm getting:

1,2,3,4,5,6,7,8,9,10

Why?


回答1:


A CTE is basically a re-usable sub-query that can refer to itself, so your final query is equivalent to:

SELECT 1
UNION ALL (SELECT 2 
           UNION ALL (SELECT 3 ...

Until n gets to 10.




回答2:


The anchor, select 1, probably doesn't bother you. The result is 1.

The recursive query, select n + 1 from cte where n<10, is executed repeatedly for all new rows in the CTE until no new rows are produced (or until the MaxRecursion limit is hit).

The first time through the only new row is 1 from the anchor and the result is 2 (n + 1). Now there is one new row: 2. The result: 3. Lather, rinse, repeat until n<10 causes no new rows to be generated.



来源:https://stackoverflow.com/questions/54333927/why-does-this-cte-act-like-a-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!