SQL Server Temporary Tables
SQL Server Temporary Tables
The syntax to create a local temporary table is similar to the syntax of a normal table. CREATE TABLE
statement is used to create a temporary table but the table name (Maximum 116 characters) is prefixed
with ‘#’ (single hash sign). Its scope is limited to session in which it is created. These are automatically
deleted once the session that created the table has been closed. We can also drop temporary table
explicitly using drop command similar to normal table.
The existence of Local temp table is only to the current session of current user (current connection) or
we can say to the current query window only. If we close the current query window where we created
the local temporary table or open a new query window then it is not accessible and will give the error
as: "Invalid object name".
One cannot create another local temporary table with the same name in the same session. It will give an
error as: "There is already an object named '#temp' in the database" but table with the same name can
be created from another session. To test, open new query window in sql server management studio and
create a local temporary table there with the same name as previously created local temporary table.
It will create a new temporary table for that session also.
These tables are automatically destroyed at the end of the procedure or the session that created them.
Global temporary tables:
Global Temporary tables are visible to or available across all sessions and all users (all connections).
The syntax to create a global temporary table is similar to the syntax of normal table. CREATE TABLE
command is used to create a global temporary table but the table name (Maximum 116 characters) is
prefixed with ‘##’ (double hash sign). Once created, it is available to all the users by any connection like
a permanent table.
A Global Temporary table is dropped automatically once all connections using it have been closed.
1. Using CREATE TABLE command and inserting data into it similar to normal table
2. Using CREATE TABLE command and inserting data into it from other existing table using INSERT
INTO- SELECT FROM command
3. Directly create and insert data into temporary table from other existing table using SELECT
INTO- FROM command
First Way: Create a temporary table and insert data into it like normal table.
Second Way: Using CREATE TABLE command and insert data into it from other existing table.
To test, let’s first create a normal table and insert data into it.
Now create a temporary table (#tbBooks) and insert data into it from the table (tbBooks) created above.
--drop existing #tbBooks temporary table(if already created)
DROP TABLE #tbBooks
Third Way: Directly create and insert data into temporary table from other existing table using
SELECT INTO- FROM command. This way we don’t need to create a temporary table explicitly. It
automatically creates the temporary table and inserts data into it.
Now let’s create a temporary table automatically and insert all data into it from tbBooks table created
above. Command will be:
--Create temporary table automatically and copy all the data from existing table
SELECT * INTO #tbBooks FROM tbBooks
Suppose we want to get all the records from tbBooks table where price is greater than 1000 and insert
them into #tbBooks temporary table then command will be:
--Create temporary table automatically and insert data into it from existing table based on condition
SELECT * INTO #tbBooks FROM tbBooks WHERE Price>1000
DECLARE
@StartDate AS DATE='2014-12-17';
DECLARE @EndDate AS DATE='2014-12-25';
WHILE (@StartDate<=@EndDate)
BEGIN
INSERT #DateList(iDate,iDayName) VALUES(@StartDate,DATENAME(DW,@StartDate))
SET @StartDate=CAST(DATEADD(DAY,1,@StartDate) AS DATE)
END
In above example we are using temporary table to store and get all the dates and their day name
between two dates.
Update in temporary table: Update operation on temporary table is similar to normal table
--Create temporary table automatically and copy all the data from existing table
SELECT * INTO #tbBooks FROM tbBooks
--Update the record
UPDATE #tbBooks SET Price=1100 WHERE BookId=4;
Note: The price of Book with Id=4 is updated to 1100 from 1000 in the temporary table
Delete from temporary table: Delete operation in temporary table is similar to normal table
--Create temporary table automatically and copy all the data from existing table
SELECT * INTO #tbBooks FROM tbBooks
Note: Record with the BookId=4 is deleted from the temporary table
Important points about Temporary Tables
1. Temporary tables are alternative of table variables to store multiple result set.
2. Temporary tables can be defined as local or global temporary tables.
3. Local temporary tables are temporary tables that are available only to the session that created them.
These tables are automatically destroyed at the end of the procedure or session that created them.
4. Global temporary tables are temporary tables that are available to all sessions and all the users.
They are dropped automatically when the last session using the temporary table has completed.
Both local temporary tables and global temporary tables are physical tables created within the tempdb
database.
5. Temporary tables can be used in Stored Procedures, Triggers and Batches but not in user defined
functions
6. Temporary tables can be access in nested stored procedures.
7. Temporary Table can be truncated like normal table.
8. Temporary Table can be altered like normal table.
9. Temporary tables used in stored procedures cause more recompilations of the stored procedures than
when table variables are used.
10. The data in the temporary table will be rolled back when a transaction is rolled back similar to normal
table.
11. A temporary table will generally use more resources than its counterpart table variable
PRIMARY KEY, UNIQUE, NULL, CHECK etc can be implemented at the time of creating temporary tables
using CREATE TABLE statement or can be added after the table has been created.
12. FOREIGN KEY is not allowed in temporary table.
13. Temporary tables can be indexed even after creation.