Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNION the results of multiple stored procedures

I have a stored procedure I need to call several different times passing in different paramaters each time. I would like to collect the results as a single dataset. Is something like this possible ...

exec MyStoredProcedure 1 UNION exec MyStoredProcedure 2 UNION exec MyStoredProcedure 3 

I tried using the syntax above but got the error ...

Incorrect syntax near the keyword 'UNION' 

The stored procedures I am dealing with are pretty complex and sort of a "black box" to me, so I cannot get into the definition of the stored procedure and change anything. Any suggestions on how to gather the results together?

I am using SQL Server 2008 R2. Thanks for any help.

like image 747
webworm Avatar asked Mar 13 '11 20:03

webworm


People also ask

Can stored procedure return multiple result sets?

Most stored procedures return multiple result sets. Such a stored procedure usually includes one or more select statements. The consumer needs to consider this inclusion to handle all the result sets.

How do you get the result of a stored procedure?

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero. You should use the return value for status codes only.


2 Answers

You'd have to use a temp table like this. UNION is for SELECTs, not stored procs

CREATE TABLE #foo (bar int ...)  INSERT #foo exec MyStoredProcedure 1  INSERT #foo exec MyStoredProcedure 2  INSERT #foo exec MyStoredProcedure 3  ... 

And hope the stored procs don't have INSERT..EXEC.. already which can not be nested. Or multiple resultsets. Or several other breaking constructs

like image 171
gbn Avatar answered Sep 29 '22 18:09

gbn


You can use INSERT EXEC for this.

declare @myRetTab table (somcolumn ...) insert @myRetTab exec StoredProcName @param1 

Then use union on the table variable or variables.

like image 22
Ben Avatar answered Sep 29 '22 19:09

Ben