sql-servertemp-tablestable-variable

What's the difference between a temp table and table variable in SQL Server?


In SQL Server 2005, we can create similar tables in two different ways.

We can use a table variable:

declare @tmp table (Col1 int, Col2 int);

Or we can use a temporary table:

create table #tmp (Col1 int, Col2 int);

What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory.

In which scenarios does one outperform the other?


Solution

  • There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.

    As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)

    Some points to consider when choosing between them:

    Some further reading: