Create a temporary table like a current table in SQL Server 2005/2008

10,219

Solution 1

select * into #temp_table from current_table_in_stored_procedure

#temp_table - locally temp
##temp_table - globally temp

select top 0 * into #temp_table from current_table_in_stored_procedure to have empty table

Solution 2

SELECT * INTO #t FROM table

if you want it to be empty:

SELECT * INTO #t FROM table WHERE 1 = 2

Solution 3

Alternatively you can script the existing table and change the name to the temp table name and add the create table script to the top of the rest of the script you want to run. I generally do this if it really important the temp table exactly match the structure of the real table (for instance when I am creating a fake table called #inserted to use when testing the code I intend to put into a trigger.)

Most of the time though the select into will get you what you need.

Share:
10,219
craigmoliver
Author by

craigmoliver

I am a veteran fullstack developer with extensive experience building custom web applications and systems for government and private sector. I currently work for Ernst & Young (EY) as a .NET Tech Lead. I am a full stack developer with fluent Microsoft .NET skills and secondary experience with Linux and Java. LinkedIn Twitter CV/Resume

Updated on June 08, 2022

Comments

  • craigmoliver
    craigmoliver almost 2 years

    How do you create a temporary table exactly like a current table in a stored procedure?

  • 3Dave
    3Dave over 14 years
    This will copy the data from current_table into a #temp_table, but #temp_table will not have the same keys, identity settings, etc. Still, this is the accepted way to perform this task.
  • Peter Radocchia
    Peter Radocchia over 14 years
    @David: the temp table will inherit identity settings, but no, none of the keys or indexing. I wish I could turn it off!