Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert results of a stored procedure into a temporary table

How do I do a SELECT * INTO [temp table] FROM [stored procedure]? Not FROM [Table] and without defining [temp table]?

Select all data from BusinessLine into tmpBusLine works fine.

select * into tmpBusLine from BusinessLine 

I am trying the same, but using a stored procedure that returns data, is not quite the same.

select * into tmpBusLine from exec getBusinessLineHistory '16 Mar 2009' 

Output message:

Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'exec'.

I have read several examples of creating a temporary table with the same structure as the output stored procedure, which works fine, but it would be nice to not supply any columns.

like image 315
Ferdeen Avatar asked Mar 17 '09 10:03

Ferdeen


People also ask

How do I insert SELECT query results into a temp table in SQL?

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.

Can we use temp table in stored procedure SQL Server?

Stored procedures can reference temporary tables that are created during the current session. Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table with the same name.


1 Answers

You can use OPENROWSET for this. Have a look. I've also included the sp_configure code to enable Ad Hoc Distributed Queries, in case it isn't already enabled.

CREATE PROC getBusinessLineHistory AS BEGIN     SELECT * FROM sys.databases END GO  sp_configure 'Show Advanced Options', 1 GO RECONFIGURE GO sp_configure 'Ad Hoc Distributed Queries', 1 GO RECONFIGURE GO  SELECT * INTO #MyTempTable FROM OPENROWSET('SQLNCLI', 'Server=(local)\SQL2008;Trusted_Connection=yes;',      'EXEC getBusinessLineHistory')  SELECT * FROM #MyTempTable 
like image 81
Aaron Alton Avatar answered Oct 11 '22 07:10

Aaron Alton