ghell
11-25-2005, 03:36 PM
the full error is:System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.i am trying to loop through a SqlDataReader and then on each pass use the data i got from it to SqlCommand.ExecuteNonQuery().
This works:SqlCommand objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, 'Hello')", objConn);
objInsertCommand.ExecuteNonQuery();
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, 'Hello')", objConn);
objInsertCommand.ExecuteNonQuery();but when i stick it in a loop like this it doesnt:objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);
objDataReader = objCommand.ExecuteReader();
while (objDataReader.Read())
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')", objConn);
objInsertCommand.ExecuteNonQuery();
}
objDataReader.Close();(i am not just copying data, this is a simplified version of my code) if there is a better way of getting the data and closing the datareader before the loop (eg recordset.GetRows() in asp3) or a way of batching all my inserts into one and running it after closing this datareader, i am open to that
EDIT: Currently i am just concatenating all my insert statements with a semicolon and appending to a StringBuilder then running that at the end, dont know if this is the best way of doing it though.
This works:SqlCommand objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, 'Hello')", objConn);
objInsertCommand.ExecuteNonQuery();
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, 'Hello')", objConn);
objInsertCommand.ExecuteNonQuery();but when i stick it in a loop like this it doesnt:objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);
objDataReader = objCommand.ExecuteReader();
while (objDataReader.Read())
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')", objConn);
objInsertCommand.ExecuteNonQuery();
}
objDataReader.Close();(i am not just copying data, this is a simplified version of my code) if there is a better way of getting the data and closing the datareader before the loop (eg recordset.GetRows() in asp3) or a way of batching all my inserts into one and running it after closing this datareader, i am open to that
EDIT: Currently i am just concatenating all my insert statements with a semicolon and appending to a StringBuilder then running that at the end, dont know if this is the best way of doing it though.