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
The page Recursive Queries Using Common Table Expressions describes the logic of CTEs:
The semantics of the recursive execution is as follows:
Split the CTE expression into anchor and recursive members.
Run the anchor member(s) creating the first invocation or base result set (T0).
Run the recursive member(s) with Ti as an input and Ti+1 as an output.
Repeat step 3 until an empty set is returned.
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.