How is the result of a SQL query inserted into a temp table?

I have a SQL query (SQL Server), and it generates reports, I want to save this exact report in the temp table, so I can play with it later. Now the question is, do I need to create a temporary table first and then save the result of the SQL query in it, or is there a way to dynamically create the table and save the query result?

+58
sql sql-server
Sep 07 '12 at 18:48
source share
5 answers

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

For example, you can:

SELECT * INTO #YourTempTable FROM YourReportQuery 
+94
Sep 07 '12 at 18:50
source share

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

 select * into #TempTable from YourTable select * from #TempTable 
+20
Sep 07
source share

In mysql: create temp table as select * from original_table

+3
Sep 07 '12 at 20:19
source share

Try:

 exec('drop table #tab') -- you can add condition 'if table exists' exec('select * into #tab from tab') 
+1
Sep 07 '12 at 18:53
source share

Suppose your existing reporting request

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

and you need to save this data in the tempory table, after which the request will be sent to

 Select EmployeeId,EmployeeName into #MyTempTable from Employee Where EmployeeId>101 order by EmployeeName 
0
Dec 07 '17 at 10:03
source share



All Articles