Creating Temporary Tables in SQL Server

Fri, Oct 2, 2009

Tech Tips

Here are three methods of creating and working with temporary tables in Microsoft SQL Server:

Method 1: Select Into
This is a quick and dirty method to create a temporary table. Compared to the other methods, you do not have to define the column names. Just add the ‘into #temptablename’ at the end of the columns you want selected.

  1. select id, code   
  2. into #mytemptable  
  3. from sourcetable  
  4.   
  5. --view the data  
  6. select * from #mytemptable  

Method 2: Create Table
Use this method if you want more control of the definition of the table and column types

  1. CREATE TABLE #mytemptable (  
  2. dataid int,  
  3. description varchar(30) )  
  4.   
  5. -- insert some data into it  
  6. insert into #mytemptable  
  7. select id, code from sourcetable  
  8.   
  9. -- view the data  
  10. select * from #mytemptable  
  11.   
  12. -- drop the table if you want to  
  13. drop table #mytemptable  

Method 3: Table Variable
This method is useful for programming stored procedures and user functions. Once you define the table, you can take advantage of passing table variables back and forth between code.

  1. DECLARE @mytemptable TABLE (  
  2. dataid int,  
  3. description varchar(30) )  
  4.   
  5. -- insert some data into it  
  6. insert into @mytemptable  
  7. select id, code from sourcetable  
  8.   
  9. -- view the data  
  10. select * from @mytemptable  

How Long are Temporary Tables Good For:
Temporary tables are good for the length of your database session. If you have a query window in management studio, once you create a temporary table, it is available until you close that query window. You can also use the ‘drop table’ statement on it.

What are Temporary Tables Good For:
– If you are analyzing data, it helps to store the results of frequently or long running sql
– If you are doing complex sql or aggregation (like or data warehouses), it might make your process simpler. I would use table variables (method 3) in that case, for performance reasons.

Bookmark and Share

Comments are closed.