How SQL query result insert in temp table?

SqlSql Server

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

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

Solution 3 - Sql

In MySQL:

create table temp as select * from original_table

Solution 4 - Sql

Try:

exec('drop table #tab') -- you can add condition 'if table exists'
exec('select * into #tab from tab')

Solution 5 - Sql

Suppose your existing reporting query is

Select EmployeeId,EmployeeName 
from Employee 
Where EmployeeId>101 order by EmployeeName

and you have to save this data into temparory table then you query goes to

Select EmployeeId,EmployeeName 
into #MyTempTable 
from Employee 
Where EmployeeId>101 order by EmployeeName	

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSatishView Question on Stackoverflow
Solution 1 - SqlLittleBobbyTables - Au RevoirView Answer on Stackoverflow
Solution 2 - SqlMikael ErikssonView Answer on Stackoverflow
Solution 3 - SqlHunterView Answer on Stackoverflow
Solution 4 - SqlRobertView Answer on Stackoverflow
Solution 5 - SqlRoshanView Answer on Stackoverflow