I actually disagree with the "Which to use" section.
The author says, if there are more than 100 rows, then you should use a temp table. I strongly disagree with this. If you have a WIDE temp table with lots of columns, this may be true, but if you have a narrow temp table, it's not. Think of it this way, SQL Server stores data in 8K pages. An int is 4 bytes. If you wanted to store a list of 1000 Integers, it would take 4,000 bytes, which easily fits in a single SQL Server data page. The best advise I can give regarding whether to use a temp table or table variable is... try it both ways and use which ever is faster.
The author also says: If you need to create indexes on it then you must use a temporary table. This is simply not true. You can create a primary key in a table variable which is implemented through an index. Sure... you can only have one primary key so you can only have one index, but you would be surprised at how often one index on a table variable is enough.
Code:
DECLARE @TibetanYaks TABLE (
YakID int [!]Primary Key[/!],
YakName char(30) )
Of course, this requires that the YakId column be unique, so you cannot always use this technique. However, even if it is not unique, you could still force the primary key to be unique by adding an identity column, like this:
Code:
DECLARE @TibetanYaks TABLE (
YakID int ,
UniqueId Int Identity(1,1),
YakName char(30)
[!]Primary Key (YakID, UniqueId)[/!]
)
If you ever find yourself in a position where you want to do this, make sure the UniqueID appears last in the list of columns for the primary key.
In my own code, I've created table variables is hundreds of thousands of rows with a primary key that outperforms temp tables.
Personally, when I need temporary storage, I almost always start with a table variable. If performance is poor and a primary key doesn't help, then I will try a temp table.
Of course, your mileage may vary because this is highly dependent on data.
To create a table variable with an index...
-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom