Munatela
Munatela

Reputation: 99

Assign SQL result set to several variables

I am coding a Sharepoint 2010 Web Part and need to get a result set from SQL server and assign the results to five different variables in C#. My select is as follows:

    SELECT Col1, Col2, Col3, Col4, Col5
    FROM Table
    WHERE Id = 1

I want the results of this statement assigned to 5 different variable:

    var result1 = col1
    var result2 = col2
    var result3 = col3 
    var result4 = col4
    var result5 = col5

I know how to the ExecuteScalar method in cases where I am returning one item from my query but how do i achieve a similar operation from the above statement?

Upvotes: 0

Views: 154

Answers (1)

Derek W
Derek W

Reputation: 10026

Use ExecuteReader() to accomplish this.

Sample usage:

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (var cmd = new SqlCommand(queryString, conn))
    {
        using (var reader = cmd.ExecuteReader())
        {
           while (reader.Read())
           {
              result1 = reader[0];
              result2 = reader[1];
              // etc.
           }
        }
    }
}

Upvotes: 1

Related Questions