Node17
Node17

Reputation: 537

Separate Stored Procedure result sets into Temporary tables

I have a a stored procedure that returns 2 result sets. I'm trying to call the stored procedure and insert the values of the first result set into a temporary table, but I am unable to do this because I'm returning 2 result sets.

Is there a way to return just one result set or both of them into seperate temporary tables. I am unable to change the stored procedure.

Stored procedure result set 1

column a | column b | coulmn c 

Stored procedure result set 2

column x | column y

What I am doing is

DECLARE @ResultSet1Table 
TABLE (
        column a
       ,column b
       ,column c
       )

INSERT INTO @ResultSet1Table 
   EXEC StoredProc

And receiveing the error message

Column name or number of supplied values does not match table definition

because of the second result set.

Upvotes: 3

Views: 389

Answers (2)

Stephan
Stephan

Reputation: 6018

I think I have a reasonable work around. Just add columns to identify each result set. Then separate them with queries. Check it out:

CREATE PROCEDURE usp_test
AS
SELECT  colA = 'A',
        colB = 'B',
        colC = 'C';

SELECT  colX = 'X',
        colY = 'Y',
        '!';
GO

DECLARE @ResultSetTable TABLE(col1 CHAR,col2 CHAR,col3 CHAR);

INSERT INTO @ResultSetTable
    EXEC usp_test

--Set 1
SELECT *
FROM @ResultSetTable
WHERE col3 <> '!'

--Set 2
SELECT *
FROM @ResultSetTable
WHERE col3 ='!'

Results for Set 1:

col1 col2 col3
---- ---- ----
A    B    C

Results for Set 2:

col1 col2 col3
---- ---- ----
X    Y    !

Upvotes: 0

Steve Ford
Steve Ford

Reputation: 7753

Ok this is a bit of a hack:

CREATE PROCEDURE SPMultipleResultsSets
AS

SELECT *
FROM 
    ( VALUES (1),(2),(3),(4)) Vals(Num)

SELECT *
FROM 
    ( VALUES ('ABC'),('DEF'),('GHI'),('JKL')) Strings(string)

You need to have ad-hoc distributed queries turned on:

sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

SELECT * INTO #Temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC DBNAME.dbo.SPMultipleResultsSets')
-- Select Table
SELECT *
FROM #Temp;

Returns:

Num
1
2
3
4

Upvotes: 2

Related Questions