In this article, I am going to give a quick overview of temporary tables in SQL Server 2012. Temporary tables are stored in tempdb. They work like a regular table in that you can perform the operations select, insert and delete as for a regular table. If created inside a stored procedure they are destroyed upon completion of the stored procedure. So let's have a look at a practical example of how to create temporary tables in SQL Server 2012. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

There are two types of temporary tables; one is local and the other is global.

Local Temporary Tables

Local temporary tables are the tables stored in tempdb.Local temporary tables are temporary tables that are available only to the session that created them. These tables are automatically destroyed at the termination of the procedure or session. They are specified with the prefix #, for example #table_name and these temp tables can be created with the same name in multiple windows.

Creating local temporary table

createtable#table_name

(

column_namevarchar(20),

column_noint

)

Global Temporary Tables

Global temporary tables are also stored in tempdb.Global temporary tables are temporary tables that are available to all sessions and all users. They are dropped automatically when the last session using the temporary table has completed. They are specified with the prefix #, for example ##table_name.

Creating Global Temporary Table

createtable##GlobalTemporaryTable

(

column_namevarchar(20),

column_noint

)

Both tables are stored in the tempdb system database.

Storage Location of Temporary Table

Temporary tables are stored inside the Temporary Folder of tempdb. Whenever we create a temporary table, it goes to the Temporary folder of the tempdb database. tempdb -> temporary tables.

Temporary Tables VS Regular Table

A Temporary table differs in the following two ways from regular tables:

Each temporary table is implicitly dropped by the system.

Each temporary table is stored in the tempdb system database. The table variable doesn't.

Dropping Temporary Tables

We can delete the temporary tables using the drop command as follows:

DROPTABLE#temporaryTable

Print'Deleted table'

Output

DROPPING Multiple Temporary Tables

You can drop a singleTemporary Tableor multiple Temporary Tables at a time.