1 out of 3 rated this helpful - Rate this topic

table (Transact-SQL)

Is a special data type that can be used to store a result set for processing at a later time. table is primarily used for temporary storage of a set of rows returned as the result set of a table-valued function.

NoteNote

To declare variables of type table, use DECLARE @local_variable.

Topic link iconTransact-SQL Syntax Conventions

table_type_definition ::= 
    TABLE ( { column_definition | table_constraint } [ ,...n ] )column_definition ::= 
    column_name scalar_data_type 
    [ COLLATE collation_definition ] 
    [ [ DEFAULT constant_expression ] | IDENTITY [ (seed ,increment ) ] ] 
    [ ROWGUIDCOL ] 
    [ column_constraint ] [ ...n ] 

column_constraint ::= 
    { [ NULL | NOT NULL ] 
    | [ PRIMARY KEY | UNIQUE ] 
    | CHECK (logical_expression ) 
    } 

table_constraint ::= 
     { { PRIMARY KEY | UNIQUE } ( column_name [ ,...n ] )
     | CHECK (logical_expression ) 
     } 
table_type_definition

Is the same subset of information that is used to define a table in CREATE TABLE. The table declaration includes column definitions, names, data types, and constraints. The only constraint types allowed are PRIMARY KEY, UNIQUE KEY, and NULL.

For more information about the syntax, see CREATE TABLE (Transact-SQL), CREATE FUNCTION (Transact-SQL), and DECLARE @local_variable (Transact-SQL).

collation_definition

Is the collation of the column that is made up of a Microsoft Windows locale and a comparison style, a Windows locale and the binary notation, or a Microsoft SQL Server collation. If collation_definition is not specified, the column inherits the collation of the current database. Or if the column is defined as a common language runtime (CLR) user-defined type, the column inherits the collation of the user-defined type.

Functions and variables can be declared to be of type table. table variables can be used in functions, stored procedures, and batches.

Important note Important

Queries that modify table variables do not generate parallel query execution plans. Performance can be affected when very large table variables, or table variables in complex queries, are modified. In these situations, consider using temporary tables instead. For more information, see CREATE TABLE (Transact-SQL). Queries that read table variables without modifying them can still be parallelized.

table variables provide the following benefits:

  • A table variable behaves like a local variable. It has a well-defined scope. This is the function, stored procedure, or batch that it is declared in.

    Within its scope, a table variable can be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table cannot be used in the following statement:

    SELECT select_list INTO table_variable   
    

    table variables are automatically cleaned up at the end of the function, stored procedure, or batch in which they are defined.

  • CHECK constraints, DEFAULT values and computed columns in the table type declaration cannot call user-defined functions.

  • table variables used in stored procedures cause fewer recompilations of the stored procedures than when temporary tables are used.

  • Transactions involving table variables last only for the duration of an update on the table variable. Therefore, table variables require less locking and logging resources.

Indexes cannot be created explicitly on table variables, and no statistics are kept on table variables. In some cases, performance may improve by using temporary tables instead, which support indexes and statistics. For more information about temporary tables, see CREATE TABLE (Transact-SQL).

table variables can be referenced by name in the FROM clause of a batch, as shown the following example:

SELECT Employee_ID, Department_ID FROM @MyTableVar

Outside a FROM clause, table variables must be referenced by using an alias, as shown in the following example:

SELECT EmployeeID, DepartmentID 
FROM @MyTableVar m
JOIN Employee on (m.EmployeeID =Employee.EmployeeID AND
   m.DepartmentID = Employee.DepartmentID)

Assignment operation between table variables is not supported. Also, because table variables have limited scope and are not part of the persistent database, they are not affected by transaction rollbacks.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Can anybody add more here?

This discussion entry is lacking enough information to provide a decision as to use this or temporary tables.

i.e. Where is the data actually stored, memory or in tempdb?

What limits how much data can be placed into the variable? Memory?

Does sql server treat this table as a temporary table using tempdb to manage it or is it all done in memory?

If there's a paper or this data type, perhaps a link to the paper will help.


[GAILE-MSFT]: Both temp tables and table variables are stored in tempdb. There are conditions (described here: http://msdn.microsoft.com/en-us/library/ms345368(SQL.100).aspx) when the temp data is cached in memory.

Best Practices
Do not use table variables to store large amounts of data (more than 100 rows). Plan choices may not be optimal or stable when a table variable contains a large amount of data. Consider rewriting such queries to use temporary tables or use the USE PLAN query hint to ensure the optimizer uses an existing query plan that works well for your scenario.

table variables are not supported in the SQL Server optimizer's cost-based reasoning model. Therefore, they should not be used when cost-based choices are required to achieve an efficient query plan. Temporary tables are preferred when cost-based choices are required. This typically includes queries with joins, parallelism decisions, and index selection choices.

Gail Erickson [MSFT]
SQL Server Documentation Team
table variable vs. temp table
Which is better to use - temporary table or table-valued variable - is really driven by situation. Things to know:
1. Variables exist only in the scope of a statement batch. Hence, between statement batches (either across time or between 'go'), variables are destroyed.
2. Table-valued variables are instantiated in memory
3. Temporary tables are created and stored in the system's tempdb.

#3 suggests that disk IO is involved to create, populate and retrieve from your constructed table -- this means a hit to performance as you are throttled by disk io. If you do not need to persist your dataset across batches, you may be able to achieve higher performance by storing your datasets in variables (hence, create, populate and retrieve in memory). Having said that, if you are working with a large set of data, this can consume a lot of memory and you should balance this against what else may be similarly consuming memory on the server to avoid introducing memory bottlenecks.


Table Variable and Transactions
It appears that table variables do not participate in transctions. For example, this code returns 3 rows:

DECLARE @MyTable TABLE (MyIdentityColumn INT IDENTITY(1,1),
 MyCity NVARCHAR(50))
INSERT INTO @MyTable (MyCity) VALUES (N'Boston');
BEGIN TRANSACTION IdentityTest
INSERT INTO @MyTable (MyCity) VALUES (N'London')
ROLLBACK TRANSACTION IdentityTest
INSERT INTO @MyTable (MyCity) VALUES (N'New Delhi');
SELECT * FROM @MyTable mt

And this code shows the update after the rollback
DECLARE @MyTable TABLE (MyIdentityColumn INT IDENTITY(1,1),
 MyCity NVARCHAR(50))
INSERT INTO @MyTable (MyCity) VALUES (N'Boston');
BEGIN TRANSACTION IdentityTest
UPDATE @MyTable SET MyCity = 'Denver'
ROLLBACK TRANSACTION IdentityTest
INSERT INTO @MyTable (MyCity) VALUES (N'New Delhi');
SELECT * FROM @MyTable mt

It would be nice if somewhere in BOL there was an explicit entry that discussed this and notes added to content like this to clarify this. Numerous entries on social.msdn.microsoft.com answer these questions
Alter table on table variable
It is not explicit on this article if it is possible to do an alter table or other DDL operations over a table variable.

I was trying to do it for having the result of 'RESTORE FILELISTONLY' independent of version SQL server adding the column TDEthumprint only if version>=10, but it was not successful