Wednesday, May 6, 2009

How to create temporary table in sql server 2005?

The syntax to create a temporary table is exactly same as the syntax to create a normal table. But the difference is the table name is prefixed with '#' (pound). By looking at the prefix '#' the sql server understands that it is a temporary table. The following code demonstrates how to create a temporary variable.

CREATE TABLE #Customer
(
CustomerID int identity(1,1),
CustomerName varchar(100),
CompanyName varchar(100),
Address varchar(250)
)

Important points about temporary tables:
  1. It is almost similar to normal table with very few exceptions.
  2. The scope of the temp table is the current connection session. It can be accessed from any where in same connection session.
  3. This table is automatically dropped when the connection session is closed.
  4. Different connection sessions creating temporary table with same name will create different copies of the temporary table with the same name. Actually internally the table name is appended with a unique number to support many connection sessions creating tables with same name. You can notice how the table name is uniquely maintained by sql server by running this query. select * from information_schema.tables where table_name like '%customer%'
  5. foreign key relations cannot be applied to temp tables.
  6. Optionally you may drop the table at the end of it's use. It is a good practice to drop any temporary table after use. drop table #Customer

When you create a temporary table it will be created in tempdb. At the time of table creation the tempdb is locked and hence there is some overhead involved using this. If there are less than 100 records then using temporary tables is not recommended. In such cases you can use table variables which are stored in memory rather than in database(on disk). To learn more about table variables please read this
http://cherupally.blogspot.com/2009/05/table-variables-in-sql-server-2005.html
Shout it

10 comments:

Kiran said...

Table variables are not stored exclusively in memory.

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

Kiran said...

I need to create a table from a temporary table. How can I do this?

jaleann_mcclurg@yahoo.com

Kiran said...

Thanks for the information...
Good Work.

Kiran said...

Useful information very crisply written. Good job.

Kiran said...

u cannot create a table from temporary table, it is not stored directly(only reference will store)

Kiran said...

wats the use of temp.table

Kiran said...

dasdasdasdasdasd

Kiran said...

What is the main difference between temp table and table variable

Kiran said...

Very simple and good article

Kiran said...

Very good

Umisha
http://dailytipsforhealth.blogspot.com/ we can talk there