1

I am intending to perform a call to ExecuteNonQuery() while the SqlDataReader is opened.

Code:

string commandString = "" //command string

using (SqlDataReader reader = cmd2.ExecuteReader())
{
    while (reader.Read())
    {
        string temp = Convert.ToString(reader["RequestID"]);
        string date;

        using (SqlCommand cmd3 = new SqlCommand(commandString, con))
        {
            date = Convert.ToString(cmd3.ExecuteScalar());
        }
    }
}

I tried executing this but I got the error:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
There is already an open DataReader associated with this Command which must be closed first.

I have the MultipleActiveResultSets set to True in the connection string. May I know if it is possible to do it?

3
  • 1
    MultipleActiveResultSets is exactly what you need to run this code. I suggest to recheck your code with the debugger at the moment in which you create the connection used here. Commented Jun 13, 2021 at 13:35
  • Is opening a second connection an option? Commented Jun 13, 2021 at 13:35
  • Why would you want to do this, why not just return all the results with one batch command? Commented Jun 13, 2021 at 15:32

2 Answers 2

3

While MARS should work, it's usually not the best choice. Simply load the results of the first query into a DataTable and iterate the rows.

var dt = new DataTable();
using (SqlDataReader reader = cmd2.ExecuteReader())
{
    dt.Load(reader);
}
foreach (DataRow row in dt.Rows)
{
    string temp = Convert.ToString(row["RequestID"]);
    string date;

    SqlCommand cmd3 = new SqlCommand(commandString, con)
    date = Convert.ToString(cmd3.ExecuteScalar());
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am curious now. Why is not the best choice against a Sql Server database? References?
MARS has performance overhead to manage the multiple logical sessions that is typically greater than the cost of buffering the result into client memory.
-1

You need to add MultipleActiveResultSets in your connection string, though you already added. Try below code that's executed successfully,

string conStr = "Data Source=DB_SERVER;Initial Catalog=DB_NAME;User Id=userId; Password=password;MultipleActiveResultSets=True";            
            using (SqlConnection con = new SqlConnection(conStr)) {
                try {
                    con.Open();
                    string commandText = @"Select Id from Table1";
                    string commandText1 = @"Select CreatedDate FROM Table2 Where table1_Id = @table1_Id";

                    SqlCommand sqlCommand = new SqlCommand(commandText, con);
                    var dataReader = sqlCommand.ExecuteReader();
                    string date;
                    while (dataReader.Read()) {
                        var vId = dataReader["Id"].ToString();
                        var sqlCommand1 = new SqlCommand(commandText1, con);                        
                        sqlCommand1.Parameters.AddWithValue("@table1_Id", vId);
                        date= sqlCommand1.ExecuteScalar().ToString();

                    }
                    con.Close();
                } catch (Exception ex) {
                    //Handle Exception                    
                }
            }

Comments

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.