Wednesday, May 6, 2009

table variables in sql server 2005

Table variable is almost similar to the temporary table in sql server 2005. Table variables are replacement to temporary tables. The following syntax shows how to define a table variable.

declare @Customer table
(
CustomerID int identity(1,1),
CustomerName varchar(100),
CompanyName varchar(100),
Address varchar(250)
)

You can notice the syntax to define a table variable is similar to the syntax to normal table definition. declare keyword is used in place of create keyword. And table name is prefixed with '@' as all tsql variables do.
  1. Table variables are stored in memory rather than in database.
  2. Querying table variables is very fast as there are no disk reads needed.
  3. The scope the table variables is same as other tsql variables. i.e, within statements batch or sproc
  4. Table variables cannot be dropped as they are automatically disappeared when they reach out scope
  5. As explained above all the data in table variables is stored in server's memory. So if there is huge data then it is not recommended to use table variables to avoid memory overhead.
  6. If the number of records is more than 100 then it is recommended to use temporary tables. To learn more about temporary tables please readi this blog post http://cherupally.blogspot.com/2009/05/how-to-create-temporary-table-in-sql.html

Shout it

3 comments:

Kiran said...

Table variables are not stored exclusively in memory.

http://technet.microsoft.com/en-us/library/cc966545.aspx

Kiran said...

updated with this comment

Kiran said...

Thanks...