Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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?

like image 531
Ananth Avatar asked Feb 09 '12 06:02

Ananth


People also ask

How do I create a temp table from an existing table?

In SQL Server you can create a temporary table based on another table by using the SELECT... INTO syntax. You can create the table with or without data. In other words, you can copy data from the original table if you wish, or you can create the table without any data.

Are CTES more efficient than temp tables?

Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.


1 Answers

select top 0 * into #mytemptable from myrealtable 
like image 94
nathan gonzalez Avatar answered Sep 17 '22 17:09

nathan gonzalez