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
SQL Server provides two types of temporary tables according to their scope: Local Temporary Table. Global Temporary Table.
If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables. I've seen this from my own experience. CTE's perform significantly slower. CTE's also perform slower because the results are not cached.
The answer lies in performance. It takes processing time to create a view table. If you are going to use the data only once during a database session, then a view will actually perform better than a temporary table because you don't need to create a structure for it.
Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With