CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2007
    Posts
    56

    Question Nestled SqlCommand

    I need to nestle two SqlCommand calls but I get the exception 'System.InvalidOperationException' and it says that "There is already an open DataReader associated with this Command which must be closed first."

    How should I code this one? Here follows what I´ve been trying so far:

    SqlConnection ^conn = gcnew SqlConnection;
    conn->ConnectionString = "Data Source=localhost\\SQLEXPRESS;"
    "Initial Catalog=Test;Integrated Security=SSPI;";
    try
    {
    conn->Open();
    SqlCommand ^cmdA = gcnew SqlCommand();
    cmdA->Connection = conn;
    cmdA->CommandType = CommandType::Text;
    cmdA->CommandText = (String^)"SELECT * FROM mytable1";
    SqlDataReader ^readerA = cmdA->ExecuteReader();

    while(readerA->Read())
    {
    SqlCommand ^cmdB = gcnew SqlCommand();
    cmdB->Connection = conn;
    cmdB->CommandType = CommandType::Text;
    cmdB->CommandText = String::Format("SELECT * FROM mytable2 "
    "WHERE mytable2.id= '{0}'",(int)readerA["id"]);
    SqlDataReader ^readerB = cmdB->ExecuteReader(); // HERE COMES THE EXCEPTION!
    if(readerB->Read())
    {
    ...
    }
    }
    }
    catch(...)
    ...

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: Nestled SqlCommand

    Use an SQL join on the 2 tables instead. This will be MUCH more efficient than doing it the way you're trying to (on client) anyway.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  3. #3
    Join Date
    Feb 2007
    Posts
    56

    Re: Nestled SqlCommand

    Ok, I can see that, but what if I need to do something like this? The example could be a lot more complex. I sure should be able to use another SqlCommand while processing the first one, shouldnt I?

  4. #4
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: Nestled SqlCommand

    No you can't on the same connection. You could open another connection though.

    The usual way of doing this is to load all data from the first select into memory then execute the second select i.e. don't have a nested loop.

    However 99.9% of the time you don't need to - because you get SQL server to do the matching for you and return the dataset which you require.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  5. #5
    Join Date
    Feb 2007
    Posts
    56

    Re: Nestled SqlCommand

    Ok, that was what I wanted to know. Thankyou.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured