20 April 2012

Temporary Tables

Prefixed the table with a pound sign (#).
This tells SQL Server that this table is a local temporary table.
This table is only visible to this session of SQL Server.
When I close this session, the table will be automatically dropped.

You can treat this table just like any other table with a few exceptions.
The only real major one is that you can't have foreign key constraints on a temporary table.

Temporary tables are created in tempdb.
If you run this query:

-----start-----
CREATE TABLE #Test_Temporary_Table
(
    Temp_Table_ID int,
    Temp_Table_Name char(30)
)

select name
from tempdb..sysobjects
where name like '#Test_Temporary_Table%'

drop table #Test_Temporary_Table
-----end-----


You'll get something like this:
name
------------------------------------------------------------------------------------
#Test_Temporary_Table_________________________ . . .

___________________________________00000000001D


If you close this session,
-----start-----
select * from #Test_Temporary_Table
-----end-----

The results will:
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name '#Test_Temporary_Table'.