In my project,i have one function to retrieve data from Sql2005 Server
like this,
SqlConnection sqlCnn = new SqlConnection("");
SqlCommand sqlCmd = new SqlCommand("Select user_id from users");
SqlDataReader sqlReader = null;
sqlCnn.Open();
sqlCmd.Connection = sqlCnn;
sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
while (sqlReader.Read())
{
if(user_id == 1)
{
SqlCommand sqlCmd2 = new SqlCommand("Select mobile from tbl");
sqlCmd2.Connection = sqlCnn;
sqlCmd2.ExecuteReader();
}
}
}
I got the following error when sqlcmd2 is executed.
There is already an open DataReader
associated with this Command which
must be closed first.
I don’t want to create a new sqlconnection at there. Is there any way to solve
this problem?
To open two readers per connection you need to enable MARS (multiple active result sets).
You can do this via connection string:
However, it is not recommended approach.
I’m sure you can retrieve the data you need with one query.
You need to explain what you need to retrieve, if you want and advice on a single query.
I assumed that the code you showed just a sample, not a real one, as it does not make much sense.
Look at ‘Is MARS all good news, or is there any downside?’ section here.