This guide demonstrates a streamlined method for populating a temporary table with the output of a stored procedure using the OPENROWSET
function. This approach eliminates the need for manual column definition in your temporary table.
Here's a step-by-step walkthrough:
Enabling Ad Hoc Distributed Queries: Before using OPENROWSET
, you must enable ad hoc distributed queries. Execute these SQL commands:
<code class="language-sql"> sp_configure 'Show Advanced Options', 1; GO RECONFIGURE; GO sp_configure 'Ad Hoc Distributed Queries', 1; GO RECONFIGURE; GO</code>
Creating the Stored Procedure: Create the stored procedure (getBusinessLineHistory
in this example):
<code class="language-sql"> CREATE PROC getBusinessLineHistory AS BEGIN SELECT * FROM sys.databases; END; GO</code>
Inserting Data via OPENROWSET: Use OPENROWSET
to insert the stored procedure's results into a temporary table (#MyTempTable
):
<code class="language-sql"> SELECT * INTO #MyTempTable FROM OPENROWSET('SQLNCLI', 'Server=(local)\SQL2008;Trusted_Connection=yes;', 'EXEC getBusinessLineHistory');</code>
Retrieving the Data: Access the data within the temporary table using a standard SELECT
statement:
<code class="language-sql"> SELECT * FROM #MyTempTable;</code>
This OPENROWSET
method offers a clean and efficient solution for integrating stored procedure results into temporary tables, simplifying the process and enhancing flexibility. Note that the server and connection details within the OPENROWSET
command should be adjusted to match your specific environment.
The above is the detailed content of How Can I Efficiently Insert Stored Procedure Results into a Temporary Table?. For more information, please follow other related articles on the PHP Chinese website!