I was asked to test a change to a query, moving a Table Valued Function (TVF) into a CTE (non-recursive). My understanding was that each CTE reference is executed separately, so there was a possibility of the change leading to tempdb contention...
I was very surprised to see the query performance improve when using the CTE. IE:
;WITH cte AS (
SELECT t.col FROM dbo.getValues() t)
SELECT ...
JOIN cte c ...
UNION ALL
SELECT ...
JOIN cte c ...
Can anyone shed any light on why this is happening?
TOP ... ORDER BYand Quassnoi's blog that usesUSE PLANto achieve this. Whether that is relevant to you or not who knows without more details / an actual execution plan. – Martin Smith Jun 14 '12 at 6:53