Best way to create a temp table with same columns and type as a permanent table

I need to create a temp table with same columns and type as a permanent table. What is the best way to do it? (The Permanent table has over 100 columns)

i.e.

Usually I create table like this.

DECLARE  #TT TABLE(              
  member_id INT,    
  reason varchar(1),    
  record_status varchar(1) ,    
  record_type varchar(1)    
 ) 

But is there any way to do it without mentioning the column names and type, but mention the name of another table with the required columns?


Solution 1:

select top 0 *
into #mytemptable
from myrealtable

Solution 2:

I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:

CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;

Note, the temp table will be put into a schema like pg_temp_3.

This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:

ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;

If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".