Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning multiple tables from a stored procedure

In my winform application I have the following scenario:

I want to get multiple tables on a single event. Returning all tables as dataset in single server cycle, or getting one table at time and using separate server cycle for each table which one is better? What are the advantages one over another?

like image 659
Nithesh Narayanan Avatar asked Aug 30 '11 06:08

Nithesh Narayanan


People also ask

Can a stored procedure return multiple tables?

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.

Is it possible to return a collection of tables from stored procedures?

The RETURN exits the stored procedure, and nothing that follows it will be executed, including the SELECT statement on the following line. Otherwise, if you want the data for the entire table, as your question shows, add a SELECT after the INSERT . But don't put RETURN in front of it!

How can I get multiple output from stored procedure in SQL?

In order to fetch the multiple returned values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword. You can also make use of the Split function to split the comma separated (delimited) values into rows.

Can we return multiple values from procedure?

You can't return multiple values from stored procedure in the way you are doing it now. You can, however, specify your parameters to be OUTPUT so you can access them. See here[^] for additional explanation.


2 Answers

The normal way is to get all at once.

just construct your SELECT's and you will have a DataSet filled with all tables.

using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(myConnString)) {     using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())     {         cmd.CommandText = "myMultipleTablesSP";         cmd.Connection = conn;         cmd.CommandType = CommandType.StoredProcedure;          conn.Open();          System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(cmd);          DataSet ds = new DataSet();         adapter.Fill(ds);          conn.Close();     } } 

if for example you return 2 tables in your SP, like:

SELECT * FROM [TableA]; SELECT * FROM [TableB]; 

you would access this tables as:

DataTable tableA = ds.Tables[0]; DataTable tableB = ds.Tables[1]; 
like image 181
balexandre Avatar answered Oct 08 '22 15:10

balexandre


If you load each table separately and use threads you can greatly improve the performance.

Datasets are also very heavy weight... so try avoiding them if possible.

like image 24
c0deNinja Avatar answered Oct 08 '22 16:10

c0deNinja