|
-
March 26th, 2009, 03:47 PM
#1
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(...)
...
-
March 26th, 2009, 06:19 PM
#2
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.
-
March 27th, 2009, 02:06 AM
#3
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?
-
March 27th, 2009, 02:22 AM
#4
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.
-
March 27th, 2009, 03:28 AM
#5
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|