How CTE really works?

前端 未结 2 1427
渐次进展
渐次进展 2021-02-20 11:03

I came across this CTE solution for concatenating row elements and I thought it\'s brilliant and I realized how powerful CTEs can be.

However, in order to use such a tool

2条回答
  •  死守一世寂寞
    2021-02-20 11:34

    The page Recursive Queries Using Common Table Expressions describes the logic of CTEs:

    The semantics of the recursive execution is as follows:

    1. Split the CTE expression into anchor and recursive members.

    2. Run the anchor member(s) creating the first invocation or base result set (T0).

    3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.

    4. Repeat step 3 until an empty set is returned.

    5. Return the result set. This is a UNION ALL of T0 to Tn.

    However, that's only the logical flow. As always, with SQL, the server is free to reorder operations as it sees fit, if the result will be "the same", and the reordering is perceived to provide the results more efficiently.

    The presence of your function with side effects (causing a delay, then returning GETDATE()) isn't something that would normally be considered when deciding whether to reorder operations.

    One obvious way in which the query may be reordered is that it may decide to start working on result set Ti+1 before it has fully created result set Ti - it may be more efficient to do this than to fully construct Ti first, since the new rows are definitely already in memory and have been accessed recently.

提交回复
热议问题