SQLkiwi (12/20/2010)
Both have their strengths and weaknesses, and the more rounded approach is to use each where it is suited. Table variables have many advantages aside from passing TVPs around:1. Named constraints are problematic with #temp tables (another name-collision problem). You cannot name a constraint on a table variable, so again the problem is avoided in all cases.
2. Table variables can use user-defined data types and XML schemas defined in the context database. Temporary tables cannot use either, unless they happen to have identical definitions in tempdb, which is inconvenient, and tough to maintain robustly.
3. Temporary tables inherit the collation of tempdb, whereas table variables use the context database. It is not all that uncommon for user databases to differ from tempdb in collation, and I do not enjoy resolving collation conflicts.
FYI, if this is a "contained database" (in SQL 11/Denali), then the temporary table will inherit collation from the current database, and cannot use UDDTs/XML schema/UDFs at all. (BOL Reference
4. Data stored in a table variable in the context of a user transaction is not rolled back with the transaction. This can be invaluable, e.g. where we need to log information after a roll back.
5. Table variables are the only available choice in function definitions.
6. Table variables are the only available choice to pass a table to a procedure.
So, I am absolutely not saying that table variables should replace temporary tables every time. I personally prefer to start with a table variable design, and look for reasons that would justify changing to use a temporary table.
In practice, I often find that the presence of a temporary object (of sufficient size or complexity to make a table variable a poor choice) an indicator that I am doing something dumb. Specifically, manipulating large amounts of data, creating indexes, relying on statistics to produce a non-trivial plan...all this is work that is performed again and again, on every execution. Often, it indicates that the present overall database design is lacking.
Paul
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes