Is a SQL Server recursive CTE considered a loop?

风格不统一 提交于 2020-01-02 04:40:46

问题


I was under the impression that recursive CTEs were set based, but in a recent SO post someone mentioned that they are loops.

Are recursive CTEs set based? Am I wrong to assume that a set based operation cannot be a loop?


回答1:


If it is recursive it is still considered a loop. Although one statement is set based, calling it over and over can be considered a loop. This is an argument about the definition or wording based on the context being used. They are set based statements but the processing is considered in simple terms a looping process.

For those interested here is a nice little write up about performance with CTE's:

http://explainextended.com/2009/11/18/sql-server-are-the-recursive-ctes-really-set-based/




回答2:


They are set based. Recursive sets are still sets.

But all set operations are, if you look with a powerful enough magnifier glass, loops. Ultimately the code runs on CPUs and CPUs execute a stream of serial instructions that operate on discrete regions of memory. In other words, there is no set oriented hardware. Being 'set oriented' is a logical concept. The fact that all SQL operations are ultimately implemented using some form of a loop is an implementation detail.




回答3:


I think the distinction that needs to be done is "tail recursion" versus "general recursion".

All tail recursions can be implemented as loops - without the need for a Stack.

General recursion support can also be implemented as a Loop - but with a stack.

Recursive CTEs are Tail recursions and hence essentially a Loop. The only difference is the terminating condition is handled by SQL semantics/execution engine. The output from each Loop iteration is UNIONed or whatever set op you specify.



来源:https://stackoverflow.com/questions/7825820/is-a-sql-server-recursive-cte-considered-a-loop

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