SQL Server: Handling Multiple Result sets in a Procedure

Suppose you have a SQL Server stored procedure that returns multiple result sets and you want to store all these results into another table. I will show you how to do so. Consider the following stored procedure

create procedure test
as
select 1 as id, 'test1' as name
select 2 as id, 'test2' as name


When you execute this procedure, it returns two result sets. The following code will copy these two result sets in a table variable

declare @t table(id int, names varchar(100))
insert into @t
exec test

select * from @t

sql-proc-multiple






Note: In order to copy multiple result sets from a stored procedure, both result sets should have the same number of columns and datatype which are compatible with the target table. If not, an error message will be thrown for invalid number of columns/data type


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

1 comment:

Anonymous said...

USE [AdventureWorks]

GO



SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO



CREATE PROCEDURE [dbo].[Demo_MultipleResultSets]



AS

BEGIN



SET NOCOUNT ON;





SELECT TOP 2 * from Production.Product;

SELECT TOP 2 * from Sales.Customer;



SET NOCOUNT OFF;

END