There are some major differences between temp tables, table variables and common table expressions (CTEs). Some of the big differences are:
Temp Tables vs. Table Variables
- SQL Server does not place locks on table variables when the table variables are used.
- Temp tables allow for multiple indexes to be created
- Table variables allow a single index the Primary Key to be created when the table variable is declared only. There is an exception to this, that if you can create the index inline, for example by creating a unique constraint inline as shown in the comments. However these indexes (and the table variable in general) will always be assumed to have 1 row in them, no matter how much data is within the table variable.
- Temp tables can be created locally (#TableName) or globally (##TableName)
- Table variables are destroyed as the batch is completed.
- Temp tables can be used throughout multiple batches.
- Temp tables can be used to hold the output of a stored procedure (temp tables will get this functionality in SQL Server 2008).
Table variables and Temp Tables vs. CTEs
- CTEs are used after the command which creates them.
- CTEs can be recursive within a single command (be careful because they can cause an infinite loop).
- Table variables and Temp Tables can be used throughout the batch.
- The command before the CTE must end with a semi-colon (;).
- As Temp tables and table variables are tables you can insert, update and delete the data within the table.
- CTEs can not have any indexes created on them, source tables much have indexes created on them.
If you can think of anything that I’ve missed, feel free to post them in the comments.