CTEs…
- Are unindexable (but can use existing indexes on referenced objects)
- Cannot have constraints
- Are essentially disposable
VIEW
s - Persist only until the next query is run
- Can be recursive
- Do not have dedicated stats (rely on stats on the underlying objects)
Temp Tables…
- Are real materialized tables that exist in tempdb
- Can be indexed
- Can have constraints
- Persist for the life of the current CONNECTION
- Can be referenced by other queries or subprocedures
- Have dedicated stats generated by the engine
As far as when to use each, they have very different use cases. If you will have a very large result set, or need to refer to it more than once, put it in a #temp
table. If it needs to be recursive, is disposable, or is just to simplify something logically, a CTE
is preferred.
CTE
WITH cte (Column1, Column2, Column3)
AS
(
SELECT Column1, Column2, Column3
FROM SomeTable
)
SELECT * FROM cte
Temp Table
SELECT Column1, Column2, Column3
INTO #tmpTable
FROM SomeTable
SELECT * FROM #tmpTable
Example
CTE
temp table
Refer to or reading
- What’s the difference between a CTE and a Temp Table?
- which-are-more-performant-cte-or-temporary-tables
文档信息
- 本文作者:Xuxiaotuan
- 本文链接:https://xuyinyin.cn/2023/08/23/Which-are-more-performant,-CTE-or-temporary-tables/
- 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)