Returning multiple tables from a stored procedure

69,406

Solution 1

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];

Solution 2

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.

Share:
69,406
Nithesh Narayanan
Author by

Nithesh Narayanan

I am Nithesh Adukkam Narayanan, a Full stack developer and Architect with 11+ years of experience in software development, design, best practices, and mentoring. My primary skillset in the .Net tech stack (C#, .net, .net core, Web API, MVC) along with the front end (React JS, JavaScript, Typescript, webpack). Been an innovator and played a key role in R&D projects using python, image processing, and ICR. Proven expertise in cutting-edge technologies like cloud (azure, aws), event-driven, micro-service architecture, micro front end architecture, Docker, and containers. Hands-on in CI/CD (Azure DevOps) and agile methodologies.

Updated on August 02, 2020

Comments

  • Nithesh Narayanan
    Nithesh Narayanan almost 4 years

    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?