Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT * INTO [tmp table] without declare table?

i want use select statement on the a table and inserting result into a temp table variable, but i don't declare temp table with columns and i want use like this:

Declare #tmp table;  SELECT * INTO #tmp FROM myTable 

this want declare columns and data types for #tmp

please help me

like image 790
hamed aj Avatar asked Jul 10 '11 18:07

hamed aj


People also ask

How do you SELECT data into a temp table?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.

What is #table and ## table in SQL?

#table refers to a local temporary table - visible to only the user who created it. ##table refers to a global temporary table - visible to all users.


2 Answers

You can do this simply without the DECLARE command - which is not valid for #temp tables anyway, only @table variables. Did you try just the following without trying to define #tmp first:

SELECT * INTO #tmp FROM myTable; 
like image 74
Aaron Bertrand Avatar answered Oct 06 '22 06:10

Aaron Bertrand


With data:

select * into #tmp from myTable 

No data:

select * into #tmp from myTable where 0=1 

BTW, you can not do this with table variables.

select * into @tmp from myTable 

Table variables need to be declared with the columns.

like image 21
Mikael Eriksson Avatar answered Oct 06 '22 06:10

Mikael Eriksson