C# 我可以使 (SqlDataReader) 处于暂停状态吗?

C# Can I make (SqlDataReader) in pause status?

我收到此错误:

There is already an open DataReader associated with this Command which must be closed first

这是我的代码:

String sql_get_completed_tasks = "select * from tasks where Ending_date is not null order by Ending_date asc";
SqlCommand command_get_completed_tasks_ = new SqlCommand(sql_get_completed_tasks, cn);

SqlDataReader reader = command_get_completed_tasks_.ExecuteReader();

while (reader.Read())
{  
    String sql_insert_completed_tasks_toTheNewTable = "insert into history_of_tasks_achievements values ("+
                reader[1] +" , N'"+ reader[2]+"' , @image , N'"+ reader[4] +"' , N'"+reader[5]+"' , N'"+ reader[6]+"' , "+
                reader[7] +" , N'"+reader[8]+"' , N'"+reader[9] +"' , "+reader[10]+" , @start_date , @end_date , "+reader[13]+
            ")";

    SqlCommand com_insert_completed_tasks_toTheNewTable = new SqlCommand(sql_insert_completed_tasks_toTheNewTable, cn);

    com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@image", reader[3]));
    com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@start_date", reader[11]));
    com_insert_completed_tasks_toTheNewTable.Parameters.Add(new SqlParameter("@end_date", reader[12]));

    com_insert_completed_tasks_toTheNewTable.ExecuteNonQuery();
}    // end of while loop

reader.Close();

MessageBox.Show("Done");

要跳过此错误,我可以为 SqlDataReader 创建暂停或关闭,然后从中断值重新打开吗?什么是最好的解决方案?

在这种情况下,您可以使用 using 语句。

// set up connection, command

using (var reader = command_get_completed_tasks_.ExecuteReader())
{
    // do the reader stuff
    reader.Close();
}

// Done

那实际上应该只是 1 个语句,没有必要迭代 select 的结果只是为了使用 insert.[=15= 将它们推回同一个数据库]

const string sqlInsert = 
@"INSERT INTO [history_of_tasks_achievements] (col1, col2, col3, ...) 
SELECT col1, col2, col3, ... FROM [tasks] WHERE [Ending_date] IS NOT NULL ORDER BY [Ending_date] ASC";

using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(sqlInsert, con))
{
  con.Open();
  var inserted = command.ExecuteNonQuery();
}

务必对齐 SELECTINSERT 之间的列,以便它们匹配。