1

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.....
    }
}
9
  • Are you getting an exception or do you want a better way of doing it? Commented Jul 9, 2015 at 16:56
  • 2
    It seems your inner while (rdr.Read()) must be while (rdr2.Read()) Commented Jul 9, 2015 at 16:58
  • I am trying to get data with query while in the loop of reading data from another query Commented Jul 9, 2015 at 16:59
  • what is the problem are you getting any error or you want some other way to do it ? Commented Jul 9, 2015 at 17:00
  • I am new to c# querys to sql , I think I have a wrong logic of code Commented Jul 9, 2015 at 17:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

where do I write this? - cmd1.CommandType = CommandType.StoredProcedure;
@IrakliShalamberidze - just before exeucting ..I just want to say you whatever written by you is ok just wrap the thing in using {} you can also visit link and follow the code it is also ok
@IrakliShalamberidze - weldome check updated answer and dont forget to mark it as accpeted if it works for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.