Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How SQL query result insert in temp table? [duplicate]

Tags:

sql

sql-server

I have a SQL query (SQL Server) and it generate reports, I want to store that exact report in temp table so I can play with it later. Now question is do I need to create temp table first and then store SQL query result into it, or is there any way to dynamically create table and store query result?

like image 964
Satish Avatar asked Sep 07 '12 18:09

Satish


People also ask

How do you store a result of query in a temp table in SQL?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result. No you don't. If you want to fill a table that already exist with rows you need to use a different syntax.

Can we insert duplicate records in SQL?

Use the context menu on the same table, to get another script: "Script Table as | SELECT To | New Query Window". This will be a totally standard select list, with all your fields listed out. Copy the whole query and paste it in over the VALUES clause in your first query window. This will give you a complete INSERT ...

How do you create a temp table and insert data in SQL?

The syntax for creating a temp table with the select statement is as shown: SELECT column_list INTO #temporary_table_name FROM TABLE_NAME WHERE conditional_expression; We use the select statement followed by the name of the temporary table. The name of a temp table in SQL Server starts with a # sign.


2 Answers

Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).

For example, you can do:

SELECT *  INTO #YourTempTable FROM YourReportQuery 
like image 127
LittleBobbyTables - Au Revoir Avatar answered Sep 20 '22 13:09

LittleBobbyTables - Au Revoir


You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select * into #TempTable from YourTable  select * from #TempTable 
like image 21
Mikael Eriksson Avatar answered Sep 18 '22 13:09

Mikael Eriksson