Home  »  Articles  »  SQL Server  »

Temporary Tables in SQL Server

 Posted By : Manoranjan SahooPosted Date : 20/07/2011 11:14:07 AM Category : SQL Server Points : 8 (Rs 1.00)

Introduction

Temporary table is very useful tool in SQL Server for developer. It provided short term use of data. These tables can be created at runtime and can do the all kinds of operations that one normal table can do. But, based on the table types, the scope is limited. These tables are created inside tempdb database. There are two types of temporary table in SQL Server:

  •  Local
  •  Global


Local : Local temporary tables are only available to the current connection to the database for the current user. These are dropped automatically when the connection is closed.

Global : Global temporary tables are available to all connections that created and exist to that database. These are dropped when the last connection using it is closed.

Both types of temporary tables are created in the system database tempdb.

How to create Temporary Tables?

Temporary tables can be created like any table in SQL Server with a CREATE TABLE or SELECT..INTO statement.
To make the table as local temporary table, attach (#) as prefix with the name of the table.
To make the table as global temporary table, attach (##) as prefix with the name of the table.

Create Local Temporary Table using Create Table statement.
Code :


CREATE TABLE #TempTable1
(
  tempfield1 INT,
  tempfield2 VARCHAR(50)
)

Create Local Temporary Table using SELECT ... INTO statement.
Code :

SELECT
    tempfield1 as id,
    tempfield2 as Name
INTO #TempTable1 FROM ActualTable1


Above sample codes will create a local temporary table named #TempTable1 with two fields with name tempfield1 and tempfield2.

Create Global Temporary Table using Create Table statement.
Code :

--replace # to ##
CREATE TABLE ##TempTable1
(
  tempfield1 INT,
  tempfield2 VARCHAR(50)
)

Create Global Temporary Table using SELECT ... INTO statement.
Code :

SELECT
    tempfield1 as id,
    tempfield2 as Name
INTO ##TempTable1 FROM ActualTable1


How to check if Temporary table exist?

use below stored procedure for checking local #TempTable1 table:


IF OBJECT_ID('tempdb..#TempTable1') IS NOT NULL
BEGIN
    PRINT '#TempTable1 exists'
END
ELSE
BEGIN
    PRINT '#TempTable1 does not exist'
END

use below code for checking global ##TempTable1 table :

IF OBJECT_ID('tempdb..##TempTable1') IS NOT NULL
BEGIN
    PRINT '##TempTable1 exists'
END
ELSE
BEGIN
    PRINT '##TempTable1 does not exist'
END

 

Responses
 Author : Manoj Sahoo Member Level : BronzeDate : 21/07/2011 01:12:44 PM Points : 2

very useful content..

thank you for providing such a nice article..



Post Reply
Login to post Response.