Reputation: 10134
whats the difference between the two types of temp tables @tmp vs #tmp in SQL 2005? and are their other types i am unaware of?
thanks
Upvotes: 5
Views: 9142
Reputation: 432311
#tmp
is a temp table and acts like a real table mostly. It can have indexes, can have statistics, participates in transactions, optimiser will work out correct row estimates
@tmp
is a table variable. No indexes, no statistics, not transaction aware, optimiser always assumes exactly 1 row
Otherwise, they are both scoped (slightly different), in memory/cache but context is tempdb though, will spill to disk if too big etc
Edit:
About keys on table variables. They make no difference. There are no stats and one row is assumed. It will change a table scan to a clustered index scan which is the same. Check any query plan and estimated rows.
Also, just read this Read What a difference a temp table makes over a table variable
The first thing that I did was put a primary key on the @ComputersToProcess table variable. That turned the table scan into a Clustered Index Scan, but didn’t do anything for performance.
Upvotes: 11
Reputation: 39946
See http://support.microsoft.com/kb/305977:
Table variables have the following advantages over temporary tables:
These are some of the drawbacks as compared to temporary tables:
Are table variables memory-only structures that are assured better performance as compared to temporary or permanent tables, because they are maintained in a database that resides on the physical disk?
For practical performance comparisons, see also:
Upvotes: 5
Reputation: 9983
Just adding onto existing answers. There's actually 3 types of temp tables. In addition to the other answers, you can create global temp tables like so ##globalTempTable
These are visible to all sql server connections, and are rarely used, however useful in noting that they do indeed exist.
Here's a good read on the difference between standard and global temp tables http://www.codeproject.com/KB/database/TempTable.aspx
Upvotes: 2
Reputation: 70523
There is one other type of "temp table" I you use a CTE it is like creating a temp table.
Upvotes: 0
Reputation: 74909
@tmp
refers to a variable of type table stored in memory whereas #tmp
refers to a table in the TEMP
database.
Upvotes: 1