This is a mirror of official site: http://jasper-net.blogspot.com/

Temporary and Global Temporary Table in SQL Server 2008

| Monday, June 13, 2011
TemporaryTable:

Temporary tables are tables that are available only to the session that created them. 

These tables are automatically destroyed at the termination of the procedure or session that created them.

Use of temporary tables in MS SQL Server is more developer friendly and they are widely used in development. Local temporary tables are visible only in the current session.

Temporary tables are created using the same syntax as a CREATE TABLE except the table name starts with a '#' sign. When the table consists of a single '#' sign, it is defined as a local temporary table and it's scope is limited to the session it is created in.

Global TemporaryTable:

Global Temporary tables are visible to or available across all sessions. And all users.
Global Temporary tables are created using the same syntax as a CREATE TABLE except the table name starts with "##" (two '#' signs). When the table is only "##", it is defined as a local global temporary table and it's scope is not limited to the session it is created in.

A Global Temporary table is dropped automatically when the last session using the temporary table has completed. 

Both the local temporary tables and global temporary tables are physical.

Uses of Temporary Tables:

A Temporary Table variable can be very useful when used with stored procedures to pass input/output parameters or to store the result of a table valued function.

Now to create the Temporary table the query will be:

CREATE TABLE #TEMPTABLE
(
Id INT,
Name VARCHAR(30),
Date DATETIME DEFAULT GETDATE()
)

Run the query. After that the "TEMPTABLE" will be created.

Now we are going to insert some values into the TempTable.

INSERT INTO #TEMPTABLE(Id, Name) VALUES(1,'shirsendu');
INSERT INTO #TEMPTABLE(Id, Name) VALUES(2,'Sarnali');
INSERT INTO #TEMPTABLE(Id, Name) VALUES(3,'Mrinal');

Execute the Query

Now to see the values inserted into the temp table execute the following query:

select * from  #TEMPTABLE

The result will look like

Read more: C# Corner

Posted via email from Jasper-net

0 comments: