问题
Do CTEs use any space in tempdb or does it use memory exclusively?
I've tagged the question with both mssql 2005 and 2008 as I use both.
回答1:
I'll try not to copy/paste MSDN
It doesn't matter.
A CTE is independent of query execution: it is only a language construct. Think of it as neat derived table or subquery.
This means that except for recursive CTEs (see later), all CTEs can be coded inline. If you use the CTE code once, it is for readability. If you use the CTE twice or more, then it is defensive: you don't want to make a mistake and have the derived table different each use.
Where a CTE is used twice or more, then that code will be executed twice or more. It won't be executed once and cached in tempdb.
Summary: it may or may not, just like if the code was inline.
Note: a recursve CTE is simply a derived table inside a derived table inside a derived table inside a a derived table inside a der... so same applies.
You can see this in Tony Rogerson's article. The use of tempdb would happen anyway if coded inline. He also notes that using a temp table can be better because of the "macro" expansion I explained above
FYI: the same applies to views. Just macros.
回答2:
A common table expression can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. When the query plan for a common table expression query uses a spool operator to save intermediate query results, the Database Engine creates a work table in tempdb to support this operation.
source
回答3:
From MSDN: http://msdn.microsoft.com/en-us/library/ms345368.aspx
A common table expression can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.
When the query plan for a common table expression query uses a spool operator to save intermediate query results, the Database Engine creates a work table in tempdb to support this operation.
来源:https://stackoverflow.com/questions/7801924/do-ctes-use-any-space-in-tempdb