T-SQL Tutorial

Create Temporary Table


In SQL Server, a temporary table is a table that is created and exists only for the duration of a session or a specific scope within a session. Temporary tables are useful for storing and manipulating intermediate results within a specific query, stored procedure, or batch of statements. They are particularly handy when you need to store and process data temporarily, without the need for a permanent table in the database.

There are two types of temporary tables in SQL Server: local temporary tables and global temporary tables.


Local Temporary Tables

Local temporary tables are only accessible within the session that created them. They are automatically dropped when the session that created them ends or when the specific scope, such as a stored procedure, completes execution. To create a local temporary table, you can use the # symbol before the table name.

-- Create a local temporary table
CREATE TABLE #TempTable (
ID INT,
Name VARCHAR(50)
);

-- Insert data into the temporary table
INSERT INTO #TempTable VALUES (1, 'John'), (2, 'Jane');

-- Query data from the temporary table
SELECT * FROM #TempTable;

The temporary table will be automatically dropped when the session ends.


Global Temporary Tables

Global temporary tables are accessible to all sessions, but they are dropped when the last session using the table ends. To create a global temporary table, you can use the ## symbol before the table name.

-- Create a global temporary table
CREATE TABLE ##GlobalTempTable (
ID INT,
Name VARCHAR(50)
);

-- Insert data into the global temporary table
INSERT INTO ##GlobalTempTable VALUES (1, 'Alice'), (2, 'Bob');

-- Query data from the global temporary table
SELECT * FROM ##GlobalTempTable;

The global temporary table will be automatically dropped when the last session ends.

When working with temporary tables, it's important to note that their scope is limited, and they are not meant for long-term storage. Also, be cautious about naming conflicts, as temporary tables are created in the tempdb system database and can be accessed by multiple sessions.

Using temporary tables can enhance the performance and readability of complex queries by breaking them down into manageable steps and allowing for intermediate data storage and manipulation.