Saturday, September 10, 2011

Table Variables


The syntax for creating table variables is quite similar to creating either regular or temporary tables.  The only differences involve a naming convention unique to variables in general, and the need to declare the table variable as you would any other local variable in Transact SQL:
As you can see the syntax bridges local variable declaration (DECLARE @variable_name variable_data_type) and table creation (column_name, data_type, nullability).  As with any other local variable in T-SQL, the table variable must be prefixed with an "@" sign.  Unlike temporary or regular table objects, table variables have certain clear limitations.
    * Table variables can not have Non-Clustered Indexes
    * Statistics can not be created against table variables
Similarities with temporary tables include:
    * Instantiated in tempdb
    * Just as with temp and regular tables, users can perform all Data Modification Language (DML) queries against a table variable:  SELECT, INSERT, UPDATE, and DELETE. 

An interesting limitation of table variables comes into play when executing code that involves a table variable.  A table variable's lifespan is only for the duration of the transaction that it runs in.  
     
An unofficial rule-of-thumb for usage is to use table variables for returning results from user-defined functions that return table values and to use temporary tables for storage and manipulation of temporary data; particularly when dealing with large amounts of data.  However, when lesser row counts are involved, and when indexing is not a factor, both table variables and temporary tables perform comparably.  It then comes down to preference of the individual responsible for the coding process.
Table variable use fewer resource than a temporary table because of there limited scope. Transactions touching table variables only last for the duration of the update on the table variable, so there is less locking and logging overhead. This is also gives better performance to the table variable as against the temporary table.
We can also declare constraint, primary key, identity columns, and default value in the table variable very easily. SQL server does not maintain any statistics on the table variable [Remember statistics are heavily used by the query optimizer to determine the best method to execute]. 
Also we cannot change the definition of the table after the table is created. This means that we cannot use the alter table statement on a table variable. If we are using a table variable in a join, you will need to alias the table in order to execute the query.

No comments:

Post a Comment