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

1 comment:

  1. 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

    ReplyDelete