Retrieve data from stored procedure which has multiple result sets












20















Given a stored procedure in SQL Server which has multiple select statements, is there a way to work with those results separately while calling the procedure?



For example:



alter procedure dbo.GetSomething
as
begin
select * from dbo.Person;
select * from dbo.Car;
end;


In .NET, if I call this proc, I can use a SqlDataReader to move between the two result sets, so I can easily retrieve all people and cars. In SQL however, when I execute the proc directly, I get both result sets.



If I call:



insert @myTempTable
exec dbo.GetSomething;


Then it errors because the column definition doesn't match. If by some chance Person and Car have the same columns, it concatenates the two together, and @myTempTable gets all records from both tables, which obviously is no good either.



I can define new custom types representing the two result sets, and make those output parameters instead of having the multiple select statements, but I'm wondering if there's a better way - some way of pulling both results into temporary tables, or looping through the results, or something.



EDIT



Actually, after looking more closely, even output table parameters won't solve this - they're readonly, and that's still true in SQL 2012. (Connect ticket asking for this to be added)










share|improve this question




















  • 2





    No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

    – Kermit
    Nov 19 '13 at 21:56











  • Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

    – marc_s
    Nov 19 '13 at 22:00











  • Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

    – NoChance
    Nov 19 '13 at 22:23











  • @EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

    – Joe Enos
    Nov 19 '13 at 22:30











  • Thanks for clarification, I re-read your text, I was thinking of somersetting else.

    – NoChance
    Nov 19 '13 at 22:33
















20















Given a stored procedure in SQL Server which has multiple select statements, is there a way to work with those results separately while calling the procedure?



For example:



alter procedure dbo.GetSomething
as
begin
select * from dbo.Person;
select * from dbo.Car;
end;


In .NET, if I call this proc, I can use a SqlDataReader to move between the two result sets, so I can easily retrieve all people and cars. In SQL however, when I execute the proc directly, I get both result sets.



If I call:



insert @myTempTable
exec dbo.GetSomething;


Then it errors because the column definition doesn't match. If by some chance Person and Car have the same columns, it concatenates the two together, and @myTempTable gets all records from both tables, which obviously is no good either.



I can define new custom types representing the two result sets, and make those output parameters instead of having the multiple select statements, but I'm wondering if there's a better way - some way of pulling both results into temporary tables, or looping through the results, or something.



EDIT



Actually, after looking more closely, even output table parameters won't solve this - they're readonly, and that's still true in SQL 2012. (Connect ticket asking for this to be added)










share|improve this question




















  • 2





    No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

    – Kermit
    Nov 19 '13 at 21:56











  • Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

    – marc_s
    Nov 19 '13 at 22:00











  • Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

    – NoChance
    Nov 19 '13 at 22:23











  • @EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

    – Joe Enos
    Nov 19 '13 at 22:30











  • Thanks for clarification, I re-read your text, I was thinking of somersetting else.

    – NoChance
    Nov 19 '13 at 22:33














20












20








20


4






Given a stored procedure in SQL Server which has multiple select statements, is there a way to work with those results separately while calling the procedure?



For example:



alter procedure dbo.GetSomething
as
begin
select * from dbo.Person;
select * from dbo.Car;
end;


In .NET, if I call this proc, I can use a SqlDataReader to move between the two result sets, so I can easily retrieve all people and cars. In SQL however, when I execute the proc directly, I get both result sets.



If I call:



insert @myTempTable
exec dbo.GetSomething;


Then it errors because the column definition doesn't match. If by some chance Person and Car have the same columns, it concatenates the two together, and @myTempTable gets all records from both tables, which obviously is no good either.



I can define new custom types representing the two result sets, and make those output parameters instead of having the multiple select statements, but I'm wondering if there's a better way - some way of pulling both results into temporary tables, or looping through the results, or something.



EDIT



Actually, after looking more closely, even output table parameters won't solve this - they're readonly, and that's still true in SQL 2012. (Connect ticket asking for this to be added)










share|improve this question
















Given a stored procedure in SQL Server which has multiple select statements, is there a way to work with those results separately while calling the procedure?



For example:



alter procedure dbo.GetSomething
as
begin
select * from dbo.Person;
select * from dbo.Car;
end;


In .NET, if I call this proc, I can use a SqlDataReader to move between the two result sets, so I can easily retrieve all people and cars. In SQL however, when I execute the proc directly, I get both result sets.



If I call:



insert @myTempTable
exec dbo.GetSomething;


Then it errors because the column definition doesn't match. If by some chance Person and Car have the same columns, it concatenates the two together, and @myTempTable gets all records from both tables, which obviously is no good either.



I can define new custom types representing the two result sets, and make those output parameters instead of having the multiple select statements, but I'm wondering if there's a better way - some way of pulling both results into temporary tables, or looping through the results, or something.



EDIT



Actually, after looking more closely, even output table parameters won't solve this - they're readonly, and that's still true in SQL 2012. (Connect ticket asking for this to be added)







sql-server stored-procedures






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '13 at 22:16







Joe Enos

















asked Nov 19 '13 at 21:54









Joe EnosJoe Enos

30.6k1059122




30.6k1059122








  • 2





    No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

    – Kermit
    Nov 19 '13 at 21:56











  • Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

    – marc_s
    Nov 19 '13 at 22:00











  • Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

    – NoChance
    Nov 19 '13 at 22:23











  • @EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

    – Joe Enos
    Nov 19 '13 at 22:30











  • Thanks for clarification, I re-read your text, I was thinking of somersetting else.

    – NoChance
    Nov 19 '13 at 22:33














  • 2





    No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

    – Kermit
    Nov 19 '13 at 21:56











  • Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

    – marc_s
    Nov 19 '13 at 22:00











  • Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

    – NoChance
    Nov 19 '13 at 22:23











  • @EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

    – Joe Enos
    Nov 19 '13 at 22:30











  • Thanks for clarification, I re-read your text, I was thinking of somersetting else.

    – NoChance
    Nov 19 '13 at 22:33








2




2





No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

– Kermit
Nov 19 '13 at 21:56





No. If you want to work with a single result set from one procedure, then you can only be returning one result set.

– Kermit
Nov 19 '13 at 21:56













Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

– marc_s
Nov 19 '13 at 22:00





Surprisingly, you can access multiple result sets from an ADO.NET app using SqlDataReader as you mentioned - but you cannot access multiple result sets from T-SQL ..... never made sense to me, but that's the way it is (at least for now)

– marc_s
Nov 19 '13 at 22:00













Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

– NoChance
Nov 19 '13 at 22:23





Say you have a column called 'type' on both Car and Person table, the new table can't have 2 columns named 'type'. It is possible that you explicitly list the column names on 1 of the selects, e.g. SELECT type AS carType from Car.

– NoChance
Nov 19 '13 at 22:23













@EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

– Joe Enos
Nov 19 '13 at 22:30





@EmmadKareem It doesn't create one big result set with both sets of columns - rather if the two queries happen to have the same columns, you get a unioned result set when you select from the proc. Even that would only potentially be useful when I want the two queries to give identical types of results. The idea is these two queries give totally unrelated results, different number and types and names of columns.

– Joe Enos
Nov 19 '13 at 22:30













Thanks for clarification, I re-read your text, I was thinking of somersetting else.

– NoChance
Nov 19 '13 at 22:33





Thanks for clarification, I re-read your text, I was thinking of somersetting else.

– NoChance
Nov 19 '13 at 22:33












8 Answers
8






active

oldest

votes


















8














String myConnString  = "User ID="username";password="password";Initial Catalog=pubs;Data Source=Server";
SqlConnection myConnection = new SqlConnection(myConnString);
SqlCommand myCommand = new SqlCommand();
SqlDataReader myReader ;

myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Connection = myConnection;
myCommand.CommandText = "MyProc";

try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();

while (myReader.Read())
{
//Write logic to process data for the first result.
}

myReader.NextResult();
while (myReader.Read())
{
//Write logic to process data for the second result.
}
}





share|improve this answer


























  • myReader.NextResult(); //is return the second result data

    – Mahesh Gaikwad
    Dec 18 '14 at 9:59





















4














In TSQL land, you're stuck.



Here is a trick (some may call semi-hacky) way that I used one time.



/*  START TSQL CODE */

/* Stored Procedure Definition */

Use Northwind
GO


IF EXISTS
(
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'
)
BEGIN
DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
END


GO

CREATE Procedure dbo.uspOrderDetailsByCustomerId
(
@CustomerID nchar(5)
, @ResultSetIndicator smallint = 0
)
AS

BEGIN

SET NOCOUNT ON



/* ResultSet #1 */

if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 1)
BEGIN
SELECT
c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
FROM
Customers c
JOIN Orders o ON c.CustomerID = o.CustomerID
WHERE
c.CustomerID = @CustomerID
END


/* */
/* ResultSet #2 */

if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 2)
BEGIN

SELECT o.OrderID,o.CustomerID /* ,o.EmployeeID,o.OrderDate,o.RequiredDate,o.ShippedDate,o.ShipVia ,o.Freight,o.ShipName,o.ShipAddress,o.OrderID,o.CustomerID,o.EmployeeID,o.OrderDate */
FROM
Orders o
WHERE
o.CustomerID = @CustomerID
ORDER BY
o.CustomerID , o.OrderID

END


/* */
/* ResultSet #3 */

if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 3)
BEGIN
SELECT od.OrderID,od.ProductID /* ,od.UnitPrice,od.Quantity,od.Discount */
FROM
[Order Details] od
WHERE
exists (select null from dbo.Orders innerOrds where innerOrds.OrderID = od.OrderID and innerOrds.CustomerID = @CustomerID )
ORDER BY
od.OrderID

END

SET NOCOUNT OFF


END

GO
/* Get everything */


exec dbo.uspOrderDetailsByCustomerId 'ALFKI'




IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
begin
drop table #TempCustomer
end


CREATE TABLE #TempCustomer
(
[CustomerID] nchar(5)
, [CompanyName] nvarchar(40)
)

INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 1

Select * from #TempCustomer



IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
begin
drop table #TempOrders
end


CREATE TABLE #TempOrders
(
OrderID int
, [CustomerID] nchar(5)

)

INSERT INTO #TempOrders ( OrderID , [CustomerID] )
exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 2

Select * from #TempOrders






IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
begin
drop table #TempOrderDetails
end


CREATE TABLE #TempOrderDetails
(
OrderID int
, [ProductID] int

)

INSERT INTO #TempOrderDetails ( OrderID , [ProductID] )
exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 3

Select * from #TempOrderDetails


IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
begin
drop table #TempOrders
end


IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
begin
drop table #TempOrders
end



IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
begin
drop table #TempCustomer
end





share|improve this answer


























  • That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

    – Joe Enos
    Nov 20 '13 at 20:40











  • I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

    – granadaCoder
    Nov 20 '13 at 20:48











  • Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

    – Jaans
    Feb 5 '16 at 15:01



















4














While this does not appear to be supported natively in T-SQL, if using a CLR Stored Procedure is an option for you, then you should be able to create a Stored Procedure in your preferred .Net language that uses the SqlDataReader.NextResult() method to advance to the desired result set and then send the SqlDataReader back via the SqlPipe.Send(SqlDataReader) method. You would just need to pass in the SQL to execute and the desired result set as parameters to this proc.



This would allow you to work with the proc as is, without modifying it to send back all or only one result set.






share|improve this answer



















  • 1





    Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

    – Joe Enos
    Nov 20 '13 at 20:43



















2














It seems like there's no good simple way to do this, without a hack or a major paradigm shift. It looks like the best way is to just split out the original procs and end up with one more proc than before:



Old way:



create procedure dbo.GetSomething
as
begin
select * from dbo.Person;
select * from dbo.Car;
end;


New way:



create procedure dbo.GetPeople
as
begin
select * from dbo.Person;
end;

create procedure dbo.GetCars
as
begin
select * from dbo.Car;
end;

-- This gives the same result as before
create procedure dbo.GetSomething
as
begin
exec dbo.GetPeople;
exec dbo.GetCars;
end;


Then when I'm in a different proc and need both result sets, I'd just have to call them one at a time.






share|improve this answer































    2














    You can put multiple result set in form of xml to a table



    So that when you want to access all these result you parse those result set column to a tabular form






    share|improve this answer































      1














      Der. Read the whole question before writing an answer! :-P



      If you're trying to work with the results in TSQL land you're going to need to use some way to keep the results separate. Writing results to Temp tables is possibly your best bet since you won't need to depend on columns lining up (or not, as the case may be) and can deal with the data in a "natural" fashion for SQL Server. E.g.



      create proc test_something
      as begin
      select a, b into temp1 from table1
      select b, c into temp2 from table2
      end
      go

      exec dbo.test_something()

      select * from temp1
      select * from temp2





      share|improve this answer





















      • 1





        This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

        – Solomon Rutzky
        Nov 20 '13 at 19:11











      • This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

        – Steve G
        Dec 4 '13 at 20:20





















      1














      Would passing a parameter to the sp do the trick
      ----------------------
      CREATE PROCEDURE dostuff @parm1 int
      AS

      BEGIN
      Declare @resultset Int
      Set @resultset = @parm1

      --0 = Select ranks
      --1 = Select suits
      --other - Select ALL

      If @resultset = 0
      SELECT [rank] FROM [ranks]
      Else If @resultset = 1
      SELECT [suit] FROM [suits]
      Else
      SELECT * FROM [suits]
      cross join [ranks]
      END
      GO

      declare @mytemptbl table (rank text)
      insert @mytemptbl
      exec dostuff 0

      select * from @mytemptbl





      share|improve this answer































        0














        Create an SqlDataAdapter, set its SelectCommand to execute the SP "GetSomething", and then use the data adapter to fill a DataSet. The DataSet will contain as many DataTable's as you have "select" statements returning recordsets from the SP.



        Here's what your code would look like:



        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.Connection = myConnectionObject;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "GetSomething";
        da.SelectCommand = cmd;

        System.Data.DataSet ds = new DataSet();
        da.Fill(ds);
        // at this point, the (ds) object contains DataTables created from the recordsets returned by the SP
        DataTable dt0 = ds.Tables[0];
        DataTable dt1 = ds.Tables[1];

        // note that dt0 corresponds to the FIRST recordset returned by the SP, etc.





        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20082889%2fretrieve-data-from-stored-procedure-which-has-multiple-result-sets%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          8 Answers
          8






          active

          oldest

          votes








          8 Answers
          8






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          String myConnString  = "User ID="username";password="password";Initial Catalog=pubs;Data Source=Server";
          SqlConnection myConnection = new SqlConnection(myConnString);
          SqlCommand myCommand = new SqlCommand();
          SqlDataReader myReader ;

          myCommand.CommandType = CommandType.StoredProcedure;
          myCommand.Connection = myConnection;
          myCommand.CommandText = "MyProc";

          try
          {
          myConnection.Open();
          myReader = myCommand.ExecuteReader();

          while (myReader.Read())
          {
          //Write logic to process data for the first result.
          }

          myReader.NextResult();
          while (myReader.Read())
          {
          //Write logic to process data for the second result.
          }
          }





          share|improve this answer


























          • myReader.NextResult(); //is return the second result data

            – Mahesh Gaikwad
            Dec 18 '14 at 9:59


















          8














          String myConnString  = "User ID="username";password="password";Initial Catalog=pubs;Data Source=Server";
          SqlConnection myConnection = new SqlConnection(myConnString);
          SqlCommand myCommand = new SqlCommand();
          SqlDataReader myReader ;

          myCommand.CommandType = CommandType.StoredProcedure;
          myCommand.Connection = myConnection;
          myCommand.CommandText = "MyProc";

          try
          {
          myConnection.Open();
          myReader = myCommand.ExecuteReader();

          while (myReader.Read())
          {
          //Write logic to process data for the first result.
          }

          myReader.NextResult();
          while (myReader.Read())
          {
          //Write logic to process data for the second result.
          }
          }





          share|improve this answer


























          • myReader.NextResult(); //is return the second result data

            – Mahesh Gaikwad
            Dec 18 '14 at 9:59
















          8












          8








          8







          String myConnString  = "User ID="username";password="password";Initial Catalog=pubs;Data Source=Server";
          SqlConnection myConnection = new SqlConnection(myConnString);
          SqlCommand myCommand = new SqlCommand();
          SqlDataReader myReader ;

          myCommand.CommandType = CommandType.StoredProcedure;
          myCommand.Connection = myConnection;
          myCommand.CommandText = "MyProc";

          try
          {
          myConnection.Open();
          myReader = myCommand.ExecuteReader();

          while (myReader.Read())
          {
          //Write logic to process data for the first result.
          }

          myReader.NextResult();
          while (myReader.Read())
          {
          //Write logic to process data for the second result.
          }
          }





          share|improve this answer















          String myConnString  = "User ID="username";password="password";Initial Catalog=pubs;Data Source=Server";
          SqlConnection myConnection = new SqlConnection(myConnString);
          SqlCommand myCommand = new SqlCommand();
          SqlDataReader myReader ;

          myCommand.CommandType = CommandType.StoredProcedure;
          myCommand.Connection = myConnection;
          myCommand.CommandText = "MyProc";

          try
          {
          myConnection.Open();
          myReader = myCommand.ExecuteReader();

          while (myReader.Read())
          {
          //Write logic to process data for the first result.
          }

          myReader.NextResult();
          while (myReader.Read())
          {
          //Write logic to process data for the second result.
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 18 '14 at 10:16









          Romasz

          27.2k1164120




          27.2k1164120










          answered Dec 18 '14 at 9:57









          Mahesh GaikwadMahesh Gaikwad

          389148




          389148













          • myReader.NextResult(); //is return the second result data

            – Mahesh Gaikwad
            Dec 18 '14 at 9:59





















          • myReader.NextResult(); //is return the second result data

            – Mahesh Gaikwad
            Dec 18 '14 at 9:59



















          myReader.NextResult(); //is return the second result data

          – Mahesh Gaikwad
          Dec 18 '14 at 9:59







          myReader.NextResult(); //is return the second result data

          – Mahesh Gaikwad
          Dec 18 '14 at 9:59















          4














          In TSQL land, you're stuck.



          Here is a trick (some may call semi-hacky) way that I used one time.



          /*  START TSQL CODE */

          /* Stored Procedure Definition */

          Use Northwind
          GO


          IF EXISTS
          (
          SELECT * FROM INFORMATION_SCHEMA.ROUTINES
          WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'
          )
          BEGIN
          DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
          END


          GO

          CREATE Procedure dbo.uspOrderDetailsByCustomerId
          (
          @CustomerID nchar(5)
          , @ResultSetIndicator smallint = 0
          )
          AS

          BEGIN

          SET NOCOUNT ON



          /* ResultSet #1 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 1)
          BEGIN
          SELECT
          c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
          FROM
          Customers c
          JOIN Orders o ON c.CustomerID = o.CustomerID
          WHERE
          c.CustomerID = @CustomerID
          END


          /* */
          /* ResultSet #2 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 2)
          BEGIN

          SELECT o.OrderID,o.CustomerID /* ,o.EmployeeID,o.OrderDate,o.RequiredDate,o.ShippedDate,o.ShipVia ,o.Freight,o.ShipName,o.ShipAddress,o.OrderID,o.CustomerID,o.EmployeeID,o.OrderDate */
          FROM
          Orders o
          WHERE
          o.CustomerID = @CustomerID
          ORDER BY
          o.CustomerID , o.OrderID

          END


          /* */
          /* ResultSet #3 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 3)
          BEGIN
          SELECT od.OrderID,od.ProductID /* ,od.UnitPrice,od.Quantity,od.Discount */
          FROM
          [Order Details] od
          WHERE
          exists (select null from dbo.Orders innerOrds where innerOrds.OrderID = od.OrderID and innerOrds.CustomerID = @CustomerID )
          ORDER BY
          od.OrderID

          END

          SET NOCOUNT OFF


          END

          GO
          /* Get everything */


          exec dbo.uspOrderDetailsByCustomerId 'ALFKI'




          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end


          CREATE TABLE #TempCustomer
          (
          [CustomerID] nchar(5)
          , [CompanyName] nvarchar(40)
          )

          INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 1

          Select * from #TempCustomer



          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end


          CREATE TABLE #TempOrders
          (
          OrderID int
          , [CustomerID] nchar(5)

          )

          INSERT INTO #TempOrders ( OrderID , [CustomerID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 2

          Select * from #TempOrders






          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrderDetails
          end


          CREATE TABLE #TempOrderDetails
          (
          OrderID int
          , [ProductID] int

          )

          INSERT INTO #TempOrderDetails ( OrderID , [ProductID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 3

          Select * from #TempOrderDetails


          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrders
          end


          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end



          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end





          share|improve this answer


























          • That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

            – Joe Enos
            Nov 20 '13 at 20:40











          • I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

            – granadaCoder
            Nov 20 '13 at 20:48











          • Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

            – Jaans
            Feb 5 '16 at 15:01
















          4














          In TSQL land, you're stuck.



          Here is a trick (some may call semi-hacky) way that I used one time.



          /*  START TSQL CODE */

          /* Stored Procedure Definition */

          Use Northwind
          GO


          IF EXISTS
          (
          SELECT * FROM INFORMATION_SCHEMA.ROUTINES
          WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'
          )
          BEGIN
          DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
          END


          GO

          CREATE Procedure dbo.uspOrderDetailsByCustomerId
          (
          @CustomerID nchar(5)
          , @ResultSetIndicator smallint = 0
          )
          AS

          BEGIN

          SET NOCOUNT ON



          /* ResultSet #1 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 1)
          BEGIN
          SELECT
          c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
          FROM
          Customers c
          JOIN Orders o ON c.CustomerID = o.CustomerID
          WHERE
          c.CustomerID = @CustomerID
          END


          /* */
          /* ResultSet #2 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 2)
          BEGIN

          SELECT o.OrderID,o.CustomerID /* ,o.EmployeeID,o.OrderDate,o.RequiredDate,o.ShippedDate,o.ShipVia ,o.Freight,o.ShipName,o.ShipAddress,o.OrderID,o.CustomerID,o.EmployeeID,o.OrderDate */
          FROM
          Orders o
          WHERE
          o.CustomerID = @CustomerID
          ORDER BY
          o.CustomerID , o.OrderID

          END


          /* */
          /* ResultSet #3 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 3)
          BEGIN
          SELECT od.OrderID,od.ProductID /* ,od.UnitPrice,od.Quantity,od.Discount */
          FROM
          [Order Details] od
          WHERE
          exists (select null from dbo.Orders innerOrds where innerOrds.OrderID = od.OrderID and innerOrds.CustomerID = @CustomerID )
          ORDER BY
          od.OrderID

          END

          SET NOCOUNT OFF


          END

          GO
          /* Get everything */


          exec dbo.uspOrderDetailsByCustomerId 'ALFKI'




          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end


          CREATE TABLE #TempCustomer
          (
          [CustomerID] nchar(5)
          , [CompanyName] nvarchar(40)
          )

          INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 1

          Select * from #TempCustomer



          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end


          CREATE TABLE #TempOrders
          (
          OrderID int
          , [CustomerID] nchar(5)

          )

          INSERT INTO #TempOrders ( OrderID , [CustomerID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 2

          Select * from #TempOrders






          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrderDetails
          end


          CREATE TABLE #TempOrderDetails
          (
          OrderID int
          , [ProductID] int

          )

          INSERT INTO #TempOrderDetails ( OrderID , [ProductID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 3

          Select * from #TempOrderDetails


          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrders
          end


          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end



          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end





          share|improve this answer


























          • That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

            – Joe Enos
            Nov 20 '13 at 20:40











          • I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

            – granadaCoder
            Nov 20 '13 at 20:48











          • Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

            – Jaans
            Feb 5 '16 at 15:01














          4












          4








          4







          In TSQL land, you're stuck.



          Here is a trick (some may call semi-hacky) way that I used one time.



          /*  START TSQL CODE */

          /* Stored Procedure Definition */

          Use Northwind
          GO


          IF EXISTS
          (
          SELECT * FROM INFORMATION_SCHEMA.ROUTINES
          WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'
          )
          BEGIN
          DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
          END


          GO

          CREATE Procedure dbo.uspOrderDetailsByCustomerId
          (
          @CustomerID nchar(5)
          , @ResultSetIndicator smallint = 0
          )
          AS

          BEGIN

          SET NOCOUNT ON



          /* ResultSet #1 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 1)
          BEGIN
          SELECT
          c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
          FROM
          Customers c
          JOIN Orders o ON c.CustomerID = o.CustomerID
          WHERE
          c.CustomerID = @CustomerID
          END


          /* */
          /* ResultSet #2 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 2)
          BEGIN

          SELECT o.OrderID,o.CustomerID /* ,o.EmployeeID,o.OrderDate,o.RequiredDate,o.ShippedDate,o.ShipVia ,o.Freight,o.ShipName,o.ShipAddress,o.OrderID,o.CustomerID,o.EmployeeID,o.OrderDate */
          FROM
          Orders o
          WHERE
          o.CustomerID = @CustomerID
          ORDER BY
          o.CustomerID , o.OrderID

          END


          /* */
          /* ResultSet #3 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 3)
          BEGIN
          SELECT od.OrderID,od.ProductID /* ,od.UnitPrice,od.Quantity,od.Discount */
          FROM
          [Order Details] od
          WHERE
          exists (select null from dbo.Orders innerOrds where innerOrds.OrderID = od.OrderID and innerOrds.CustomerID = @CustomerID )
          ORDER BY
          od.OrderID

          END

          SET NOCOUNT OFF


          END

          GO
          /* Get everything */


          exec dbo.uspOrderDetailsByCustomerId 'ALFKI'




          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end


          CREATE TABLE #TempCustomer
          (
          [CustomerID] nchar(5)
          , [CompanyName] nvarchar(40)
          )

          INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 1

          Select * from #TempCustomer



          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end


          CREATE TABLE #TempOrders
          (
          OrderID int
          , [CustomerID] nchar(5)

          )

          INSERT INTO #TempOrders ( OrderID , [CustomerID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 2

          Select * from #TempOrders






          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrderDetails
          end


          CREATE TABLE #TempOrderDetails
          (
          OrderID int
          , [ProductID] int

          )

          INSERT INTO #TempOrderDetails ( OrderID , [ProductID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 3

          Select * from #TempOrderDetails


          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrders
          end


          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end



          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end





          share|improve this answer















          In TSQL land, you're stuck.



          Here is a trick (some may call semi-hacky) way that I used one time.



          /*  START TSQL CODE */

          /* Stored Procedure Definition */

          Use Northwind
          GO


          IF EXISTS
          (
          SELECT * FROM INFORMATION_SCHEMA.ROUTINES
          WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'
          )
          BEGIN
          DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
          END


          GO

          CREATE Procedure dbo.uspOrderDetailsByCustomerId
          (
          @CustomerID nchar(5)
          , @ResultSetIndicator smallint = 0
          )
          AS

          BEGIN

          SET NOCOUNT ON



          /* ResultSet #1 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 1)
          BEGIN
          SELECT
          c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
          FROM
          Customers c
          JOIN Orders o ON c.CustomerID = o.CustomerID
          WHERE
          c.CustomerID = @CustomerID
          END


          /* */
          /* ResultSet #2 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 2)
          BEGIN

          SELECT o.OrderID,o.CustomerID /* ,o.EmployeeID,o.OrderDate,o.RequiredDate,o.ShippedDate,o.ShipVia ,o.Freight,o.ShipName,o.ShipAddress,o.OrderID,o.CustomerID,o.EmployeeID,o.OrderDate */
          FROM
          Orders o
          WHERE
          o.CustomerID = @CustomerID
          ORDER BY
          o.CustomerID , o.OrderID

          END


          /* */
          /* ResultSet #3 */

          if (@ResultSetIndicator = 0 OR @ResultSetIndicator = 3)
          BEGIN
          SELECT od.OrderID,od.ProductID /* ,od.UnitPrice,od.Quantity,od.Discount */
          FROM
          [Order Details] od
          WHERE
          exists (select null from dbo.Orders innerOrds where innerOrds.OrderID = od.OrderID and innerOrds.CustomerID = @CustomerID )
          ORDER BY
          od.OrderID

          END

          SET NOCOUNT OFF


          END

          GO
          /* Get everything */


          exec dbo.uspOrderDetailsByCustomerId 'ALFKI'




          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end


          CREATE TABLE #TempCustomer
          (
          [CustomerID] nchar(5)
          , [CompanyName] nvarchar(40)
          )

          INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 1

          Select * from #TempCustomer



          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end


          CREATE TABLE #TempOrders
          (
          OrderID int
          , [CustomerID] nchar(5)

          )

          INSERT INTO #TempOrders ( OrderID , [CustomerID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 2

          Select * from #TempOrders






          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrderDetails
          end


          CREATE TABLE #TempOrderDetails
          (
          OrderID int
          , [ProductID] int

          )

          INSERT INTO #TempOrderDetails ( OrderID , [ProductID] )
          exec dbo.uspOrderDetailsByCustomerId 'ALFKI' , 3

          Select * from #TempOrderDetails


          IF OBJECT_ID('tempdb..#TempOrderDetails') IS NOT NULL
          begin
          drop table #TempOrders
          end


          IF OBJECT_ID('tempdb..#TempOrders') IS NOT NULL
          begin
          drop table #TempOrders
          end



          IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
          begin
          drop table #TempCustomer
          end






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '13 at 19:34

























          answered Nov 20 '13 at 16:42









          granadaCodergranadaCoder

          14.8k55379




          14.8k55379













          • That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

            – Joe Enos
            Nov 20 '13 at 20:40











          • I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

            – granadaCoder
            Nov 20 '13 at 20:48











          • Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

            – Jaans
            Feb 5 '16 at 15:01



















          • That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

            – Joe Enos
            Nov 20 '13 at 20:40











          • I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

            – granadaCoder
            Nov 20 '13 at 20:48











          • Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

            – Jaans
            Feb 5 '16 at 15:01

















          That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

          – Joe Enos
          Nov 20 '13 at 20:40





          That's an interesting idea, thanks. A little bit hackish as you mention, but looks like it would work.

          – Joe Enos
          Nov 20 '13 at 20:40













          I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

          – granadaCoder
          Nov 20 '13 at 20:48





          I used it one time, on some code I inherited. I def do NOT recommend it as a best practice. But it works.

          – granadaCoder
          Nov 20 '13 at 20:48













          Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

          – Jaans
          Feb 5 '16 at 15:01





          Ah... I see what you did there. Will definitely help me out of a tight spot where I only need access to the one result set from a special case location.

          – Jaans
          Feb 5 '16 at 15:01











          4














          While this does not appear to be supported natively in T-SQL, if using a CLR Stored Procedure is an option for you, then you should be able to create a Stored Procedure in your preferred .Net language that uses the SqlDataReader.NextResult() method to advance to the desired result set and then send the SqlDataReader back via the SqlPipe.Send(SqlDataReader) method. You would just need to pass in the SQL to execute and the desired result set as parameters to this proc.



          This would allow you to work with the proc as is, without modifying it to send back all or only one result set.






          share|improve this answer



















          • 1





            Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

            – Joe Enos
            Nov 20 '13 at 20:43
















          4














          While this does not appear to be supported natively in T-SQL, if using a CLR Stored Procedure is an option for you, then you should be able to create a Stored Procedure in your preferred .Net language that uses the SqlDataReader.NextResult() method to advance to the desired result set and then send the SqlDataReader back via the SqlPipe.Send(SqlDataReader) method. You would just need to pass in the SQL to execute and the desired result set as parameters to this proc.



          This would allow you to work with the proc as is, without modifying it to send back all or only one result set.






          share|improve this answer



















          • 1





            Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

            – Joe Enos
            Nov 20 '13 at 20:43














          4












          4








          4







          While this does not appear to be supported natively in T-SQL, if using a CLR Stored Procedure is an option for you, then you should be able to create a Stored Procedure in your preferred .Net language that uses the SqlDataReader.NextResult() method to advance to the desired result set and then send the SqlDataReader back via the SqlPipe.Send(SqlDataReader) method. You would just need to pass in the SQL to execute and the desired result set as parameters to this proc.



          This would allow you to work with the proc as is, without modifying it to send back all or only one result set.






          share|improve this answer













          While this does not appear to be supported natively in T-SQL, if using a CLR Stored Procedure is an option for you, then you should be able to create a Stored Procedure in your preferred .Net language that uses the SqlDataReader.NextResult() method to advance to the desired result set and then send the SqlDataReader back via the SqlPipe.Send(SqlDataReader) method. You would just need to pass in the SQL to execute and the desired result set as parameters to this proc.



          This would allow you to work with the proc as is, without modifying it to send back all or only one result set.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '13 at 20:09









          Solomon RutzkySolomon Rutzky

          32.1k374114




          32.1k374114








          • 1





            Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

            – Joe Enos
            Nov 20 '13 at 20:43














          • 1





            Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

            – Joe Enos
            Nov 20 '13 at 20:43








          1




          1





          Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

          – Joe Enos
          Nov 20 '13 at 20:43





          Thanks - not a huge fan of CLR procs just because they're a pain to work with, but that sounds like an interesting approach.

          – Joe Enos
          Nov 20 '13 at 20:43











          2














          It seems like there's no good simple way to do this, without a hack or a major paradigm shift. It looks like the best way is to just split out the original procs and end up with one more proc than before:



          Old way:



          create procedure dbo.GetSomething
          as
          begin
          select * from dbo.Person;
          select * from dbo.Car;
          end;


          New way:



          create procedure dbo.GetPeople
          as
          begin
          select * from dbo.Person;
          end;

          create procedure dbo.GetCars
          as
          begin
          select * from dbo.Car;
          end;

          -- This gives the same result as before
          create procedure dbo.GetSomething
          as
          begin
          exec dbo.GetPeople;
          exec dbo.GetCars;
          end;


          Then when I'm in a different proc and need both result sets, I'd just have to call them one at a time.






          share|improve this answer




























            2














            It seems like there's no good simple way to do this, without a hack or a major paradigm shift. It looks like the best way is to just split out the original procs and end up with one more proc than before:



            Old way:



            create procedure dbo.GetSomething
            as
            begin
            select * from dbo.Person;
            select * from dbo.Car;
            end;


            New way:



            create procedure dbo.GetPeople
            as
            begin
            select * from dbo.Person;
            end;

            create procedure dbo.GetCars
            as
            begin
            select * from dbo.Car;
            end;

            -- This gives the same result as before
            create procedure dbo.GetSomething
            as
            begin
            exec dbo.GetPeople;
            exec dbo.GetCars;
            end;


            Then when I'm in a different proc and need both result sets, I'd just have to call them one at a time.






            share|improve this answer


























              2












              2








              2







              It seems like there's no good simple way to do this, without a hack or a major paradigm shift. It looks like the best way is to just split out the original procs and end up with one more proc than before:



              Old way:



              create procedure dbo.GetSomething
              as
              begin
              select * from dbo.Person;
              select * from dbo.Car;
              end;


              New way:



              create procedure dbo.GetPeople
              as
              begin
              select * from dbo.Person;
              end;

              create procedure dbo.GetCars
              as
              begin
              select * from dbo.Car;
              end;

              -- This gives the same result as before
              create procedure dbo.GetSomething
              as
              begin
              exec dbo.GetPeople;
              exec dbo.GetCars;
              end;


              Then when I'm in a different proc and need both result sets, I'd just have to call them one at a time.






              share|improve this answer













              It seems like there's no good simple way to do this, without a hack or a major paradigm shift. It looks like the best way is to just split out the original procs and end up with one more proc than before:



              Old way:



              create procedure dbo.GetSomething
              as
              begin
              select * from dbo.Person;
              select * from dbo.Car;
              end;


              New way:



              create procedure dbo.GetPeople
              as
              begin
              select * from dbo.Person;
              end;

              create procedure dbo.GetCars
              as
              begin
              select * from dbo.Car;
              end;

              -- This gives the same result as before
              create procedure dbo.GetSomething
              as
              begin
              exec dbo.GetPeople;
              exec dbo.GetCars;
              end;


              Then when I'm in a different proc and need both result sets, I'd just have to call them one at a time.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 20 '13 at 22:49









              Joe EnosJoe Enos

              30.6k1059122




              30.6k1059122























                  2














                  You can put multiple result set in form of xml to a table



                  So that when you want to access all these result you parse those result set column to a tabular form






                  share|improve this answer




























                    2














                    You can put multiple result set in form of xml to a table



                    So that when you want to access all these result you parse those result set column to a tabular form






                    share|improve this answer


























                      2












                      2








                      2







                      You can put multiple result set in form of xml to a table



                      So that when you want to access all these result you parse those result set column to a tabular form






                      share|improve this answer













                      You can put multiple result set in form of xml to a table



                      So that when you want to access all these result you parse those result set column to a tabular form







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 14 '16 at 13:49









                      abdulla wasayabdulla wasay

                      373




                      373























                          1














                          Der. Read the whole question before writing an answer! :-P



                          If you're trying to work with the results in TSQL land you're going to need to use some way to keep the results separate. Writing results to Temp tables is possibly your best bet since you won't need to depend on columns lining up (or not, as the case may be) and can deal with the data in a "natural" fashion for SQL Server. E.g.



                          create proc test_something
                          as begin
                          select a, b into temp1 from table1
                          select b, c into temp2 from table2
                          end
                          go

                          exec dbo.test_something()

                          select * from temp1
                          select * from temp2





                          share|improve this answer





















                          • 1





                            This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                            – Solomon Rutzky
                            Nov 20 '13 at 19:11











                          • This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                            – Steve G
                            Dec 4 '13 at 20:20


















                          1














                          Der. Read the whole question before writing an answer! :-P



                          If you're trying to work with the results in TSQL land you're going to need to use some way to keep the results separate. Writing results to Temp tables is possibly your best bet since you won't need to depend on columns lining up (or not, as the case may be) and can deal with the data in a "natural" fashion for SQL Server. E.g.



                          create proc test_something
                          as begin
                          select a, b into temp1 from table1
                          select b, c into temp2 from table2
                          end
                          go

                          exec dbo.test_something()

                          select * from temp1
                          select * from temp2





                          share|improve this answer





















                          • 1





                            This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                            – Solomon Rutzky
                            Nov 20 '13 at 19:11











                          • This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                            – Steve G
                            Dec 4 '13 at 20:20
















                          1












                          1








                          1







                          Der. Read the whole question before writing an answer! :-P



                          If you're trying to work with the results in TSQL land you're going to need to use some way to keep the results separate. Writing results to Temp tables is possibly your best bet since you won't need to depend on columns lining up (or not, as the case may be) and can deal with the data in a "natural" fashion for SQL Server. E.g.



                          create proc test_something
                          as begin
                          select a, b into temp1 from table1
                          select b, c into temp2 from table2
                          end
                          go

                          exec dbo.test_something()

                          select * from temp1
                          select * from temp2





                          share|improve this answer















                          Der. Read the whole question before writing an answer! :-P



                          If you're trying to work with the results in TSQL land you're going to need to use some way to keep the results separate. Writing results to Temp tables is possibly your best bet since you won't need to depend on columns lining up (or not, as the case may be) and can deal with the data in a "natural" fashion for SQL Server. E.g.



                          create proc test_something
                          as begin
                          select a, b into temp1 from table1
                          select b, c into temp2 from table2
                          end
                          go

                          exec dbo.test_something()

                          select * from temp1
                          select * from temp2






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 20 '13 at 19:09

























                          answered Nov 20 '13 at 18:54









                          Steve GSteve G

                          8671711




                          8671711








                          • 1





                            This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                            – Solomon Rutzky
                            Nov 20 '13 at 19:11











                          • This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                            – Steve G
                            Dec 4 '13 at 20:20
















                          • 1





                            This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                            – Solomon Rutzky
                            Nov 20 '13 at 19:11











                          • This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                            – Steve G
                            Dec 4 '13 at 20:20










                          1




                          1





                          This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                          – Solomon Rutzky
                          Nov 20 '13 at 19:11





                          This will not work unless temp1 and temp2 are created outside of the proc, before the proc is called. Temp tables created within a sub-process are dropped when returning to the calling process.

                          – Solomon Rutzky
                          Nov 20 '13 at 19:11













                          This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                          – Steve G
                          Dec 4 '13 at 20:20







                          This does work for me in SQL Server 2008. There's no need to create temp1 and temp2 outside of the proc since they're not actually temp tables, they're real tables. Of course, now you have to clean up after yourself... And, as always, YMMV. :)

                          – Steve G
                          Dec 4 '13 at 20:20













                          1














                          Would passing a parameter to the sp do the trick
                          ----------------------
                          CREATE PROCEDURE dostuff @parm1 int
                          AS

                          BEGIN
                          Declare @resultset Int
                          Set @resultset = @parm1

                          --0 = Select ranks
                          --1 = Select suits
                          --other - Select ALL

                          If @resultset = 0
                          SELECT [rank] FROM [ranks]
                          Else If @resultset = 1
                          SELECT [suit] FROM [suits]
                          Else
                          SELECT * FROM [suits]
                          cross join [ranks]
                          END
                          GO

                          declare @mytemptbl table (rank text)
                          insert @mytemptbl
                          exec dostuff 0

                          select * from @mytemptbl





                          share|improve this answer




























                            1














                            Would passing a parameter to the sp do the trick
                            ----------------------
                            CREATE PROCEDURE dostuff @parm1 int
                            AS

                            BEGIN
                            Declare @resultset Int
                            Set @resultset = @parm1

                            --0 = Select ranks
                            --1 = Select suits
                            --other - Select ALL

                            If @resultset = 0
                            SELECT [rank] FROM [ranks]
                            Else If @resultset = 1
                            SELECT [suit] FROM [suits]
                            Else
                            SELECT * FROM [suits]
                            cross join [ranks]
                            END
                            GO

                            declare @mytemptbl table (rank text)
                            insert @mytemptbl
                            exec dostuff 0

                            select * from @mytemptbl





                            share|improve this answer


























                              1












                              1








                              1







                              Would passing a parameter to the sp do the trick
                              ----------------------
                              CREATE PROCEDURE dostuff @parm1 int
                              AS

                              BEGIN
                              Declare @resultset Int
                              Set @resultset = @parm1

                              --0 = Select ranks
                              --1 = Select suits
                              --other - Select ALL

                              If @resultset = 0
                              SELECT [rank] FROM [ranks]
                              Else If @resultset = 1
                              SELECT [suit] FROM [suits]
                              Else
                              SELECT * FROM [suits]
                              cross join [ranks]
                              END
                              GO

                              declare @mytemptbl table (rank text)
                              insert @mytemptbl
                              exec dostuff 0

                              select * from @mytemptbl





                              share|improve this answer













                              Would passing a parameter to the sp do the trick
                              ----------------------
                              CREATE PROCEDURE dostuff @parm1 int
                              AS

                              BEGIN
                              Declare @resultset Int
                              Set @resultset = @parm1

                              --0 = Select ranks
                              --1 = Select suits
                              --other - Select ALL

                              If @resultset = 0
                              SELECT [rank] FROM [ranks]
                              Else If @resultset = 1
                              SELECT [suit] FROM [suits]
                              Else
                              SELECT * FROM [suits]
                              cross join [ranks]
                              END
                              GO

                              declare @mytemptbl table (rank text)
                              insert @mytemptbl
                              exec dostuff 0

                              select * from @mytemptbl






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 24 '18 at 20:41









                              level3looperlevel3looper

                              49416




                              49416























                                  0














                                  Create an SqlDataAdapter, set its SelectCommand to execute the SP "GetSomething", and then use the data adapter to fill a DataSet. The DataSet will contain as many DataTable's as you have "select" statements returning recordsets from the SP.



                                  Here's what your code would look like:



                                  System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                                  System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                                  cmd.Connection = myConnectionObject;
                                  cmd.CommandType = CommandType.StoredProcedure;
                                  cmd.CommandText = "GetSomething";
                                  da.SelectCommand = cmd;

                                  System.Data.DataSet ds = new DataSet();
                                  da.Fill(ds);
                                  // at this point, the (ds) object contains DataTables created from the recordsets returned by the SP
                                  DataTable dt0 = ds.Tables[0];
                                  DataTable dt1 = ds.Tables[1];

                                  // note that dt0 corresponds to the FIRST recordset returned by the SP, etc.





                                  share|improve this answer




























                                    0














                                    Create an SqlDataAdapter, set its SelectCommand to execute the SP "GetSomething", and then use the data adapter to fill a DataSet. The DataSet will contain as many DataTable's as you have "select" statements returning recordsets from the SP.



                                    Here's what your code would look like:



                                    System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                                    cmd.Connection = myConnectionObject;
                                    cmd.CommandType = CommandType.StoredProcedure;
                                    cmd.CommandText = "GetSomething";
                                    da.SelectCommand = cmd;

                                    System.Data.DataSet ds = new DataSet();
                                    da.Fill(ds);
                                    // at this point, the (ds) object contains DataTables created from the recordsets returned by the SP
                                    DataTable dt0 = ds.Tables[0];
                                    DataTable dt1 = ds.Tables[1];

                                    // note that dt0 corresponds to the FIRST recordset returned by the SP, etc.





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Create an SqlDataAdapter, set its SelectCommand to execute the SP "GetSomething", and then use the data adapter to fill a DataSet. The DataSet will contain as many DataTable's as you have "select" statements returning recordsets from the SP.



                                      Here's what your code would look like:



                                      System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                                      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                                      cmd.Connection = myConnectionObject;
                                      cmd.CommandType = CommandType.StoredProcedure;
                                      cmd.CommandText = "GetSomething";
                                      da.SelectCommand = cmd;

                                      System.Data.DataSet ds = new DataSet();
                                      da.Fill(ds);
                                      // at this point, the (ds) object contains DataTables created from the recordsets returned by the SP
                                      DataTable dt0 = ds.Tables[0];
                                      DataTable dt1 = ds.Tables[1];

                                      // note that dt0 corresponds to the FIRST recordset returned by the SP, etc.





                                      share|improve this answer













                                      Create an SqlDataAdapter, set its SelectCommand to execute the SP "GetSomething", and then use the data adapter to fill a DataSet. The DataSet will contain as many DataTable's as you have "select" statements returning recordsets from the SP.



                                      Here's what your code would look like:



                                      System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                                      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                                      cmd.Connection = myConnectionObject;
                                      cmd.CommandType = CommandType.StoredProcedure;
                                      cmd.CommandText = "GetSomething";
                                      da.SelectCommand = cmd;

                                      System.Data.DataSet ds = new DataSet();
                                      da.Fill(ds);
                                      // at this point, the (ds) object contains DataTables created from the recordsets returned by the SP
                                      DataTable dt0 = ds.Tables[0];
                                      DataTable dt1 = ds.Tables[1];

                                      // note that dt0 corresponds to the FIRST recordset returned by the SP, etc.






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 9 '18 at 9:10









                                      Olivier RASSIOlivier RASSI

                                      1




                                      1






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20082889%2fretrieve-data-from-stored-procedure-which-has-multiple-result-sets%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Contact image not getting when fetch all contact list from iPhone by CNContact

                                          count number of partitions of a set with n elements into k subsets

                                          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks