Temporary Table in SQL Server
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.
The 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 its scope is limited to the session it is created in.
Global Temporary Table in SQL Server
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 its 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 been 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()
- )
Now we are going to insert some values into the TempTable.
- INSERT INTO #TEMPTABLE(Id, Name) VALUES(1,'sameer');
- INSERT INTO #TEMPTABLE(Id, Name) VALUES(2,'satish');
- INSERT INTO #TEMPTABLE(Id, Name) VALUES(3,'ashish');
Now to see the values inserted into the temp table execute the following query:
- select * from #TEMPTABLE
Now to create the Global Temporary Table.
For creating the table we already know to use "##" before the table name.
- CREATE TABLE ##GLOBALTEMPTABLE
- (
- Id INT,
- Address VARCHAR(30),
- Date DATETIME DEFAULT GETDATE()
- )
Now we are going to insert some values into the GLOBALTEMPTABLE.
- INSERT INTO ##GLOBALTEMPTABLE(Id, Address) VALUES(1,'Bangalore');
- INSERT INTO ##GLOBALTEMPTABLE(Id, Address) VALUES(2,'Bangkok');
- INSERT INTO ##GLOBALTEMPTABLE(Id, Address) VALUES(3,'CAlcutta');
- select * from ##GLOBALTEMPTABLE
Now you can cross join between the Temporary table and the GlobalTemporaryTable as in:
- select * from ##GLOBALTEMPTABLE,#TEMPTABLE
The result will look like this:
Conclusion
So in this article, we have seen how to create a temporary table and a global temporary table and how the data can be fetched.
0 Comments