What is Temporary Table in SQL?
Temporary Tables are most likely as Permanent Tables. Temporary Tables are Created in TempDB and are automatically deleted as soon as the last connection is terminated. Temporary Tables helps us to store and process intermediate results. Temporary tables are very useful when we need to store temporary data. The Syntax to create a Temporary Table is given below:
To Create Temporary Table:
CREATE TABLE #EmpDetails (id INT, name VARCHAR(25))
To Insert Values Into Temporary Table:
INSERT INTO #EmpDetails VALUES (01, 'Lalit'), (02, 'Atharva')
To Select Values from Temporary Table:
SELECT * FROM #EmpDetails
There are 2 types of Temporary Tables: Local Temporary Table, and Global Temporary Table. These are explained as following below.
- Local Temporary Table:
A Local Temp Table is available only for the session that has created it. It is automatically dropped (deleted) when the connection that has created it, is closed. To create Local Temporary Table Single “#” is used as the prefix of a table name.
Also, the user can drop this temporary table by using the “DROP TABLE #EmpDetails” query. There will be Random Numbers are appended to the Name of Table Name. If the Temporary Table is created inside the stored procedure, it get dropped automatically upon the completion of stored procedure execution.
CREATE PROCEDURE ProcTemp AS BEGIN CREATE TABLE #EmpDetails INSERT INTO #EmpDetails VALUES ( 01, 'Lalit'), ( 02, 'Atharva') SELECT * FROM #EmpDetails END EXECUTE ProcTemp
- Global Temporary Table:
To create a Global Temporary Table, add the “##” symbol before the table name.
CREATE TABLE ##EmpDetails (id INT, name VARCHAR(25))
Global Temporary Tables are visible to all connections and Dropped when the last connection referencing the table is closed. Global Table Name must have an Unique Table Name. There will be no random Numbers suffixed at the end of the Table Name.
Please Login to comment...