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