Irakli Shalamberidze
Irakli Shalamberidze

Reputation: 320

How to executequery while reading data from another sql query in c#?

I want to ExecuteQuery() while reading data from another resultset of ExecuteQuery.

SqlCommand cmd1 = new SqlCommand("pgwp_teamtypeselect", con);
cmd1.CommandType = CommandType.StoredProcedure;

rdr = cmd1.ExecuteReader();

string ehtml = null;
string tipi = null;
int che = 0;

while (rdr.Read())
{
    SqlCommand cmd2 = new SqlCommand("pgwp_goalselect", con);
    cmd2.CommandType = CommandType.StoredProcedure;

    rdr2 = cmd2.ExecuteReader();

    while (rdr2.Read())
    {
        do something.....
    }
}

Upvotes: 1

Views: 2729

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176936

There is nothing wrong in executing query with in query but I suggest do it making use of using as in below example , So that object get dispose once execution finish

using(var command = new SqlCommand("pgwp_teamtypeselect", connection))
{
  command.CommandType = CommandType.StoredProcedure;
  using(var dataReader = command.ExecuteReader())
  {
    while (dataReader.Read()) 
    {
          using(var command1 = new SqlCommand("pgwp_goalselect",  
                       connection))
           {
             command1.CommandType = CommandType.StoredProcedure;

             using(var dataReader2 =command1.ExecuteReader())
             {
             }
           }
    }
}

}

You should also add this in your connection string MultipleActiveResultSets=True"

string connectionString = @"Data Source=GTL-263\SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI;MultipleActiveResultSets=True";

you can read this :Multiple Active Result Sets (MARS - ADO.NET 2.0) things you are doing is correct.

Upvotes: 1

Related Questions