Do CTEs use any space in tempdb?

╄→尐↘猪︶ㄣ 提交于 2019-12-05 02:15:23

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.

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

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.

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