OleDB 查询不返回所有结果

OleDB Queries not Returning All Results

我希望我的代码做的是收集 SQLMigrationFl 字段中具有 'I' 的前十条记录,然后通过删除该 'I' 值来处理这十条记录。以下是处理此问题的代码部分。

string inProgressQuery = "SELECT TOP 10 IDType, ID, Program, Date, Body, 
                          AcctNo, ANPACAcctID, ANPACClientID, TEAMID, 
                          ImportDate, AnnualReview, TeamGUID, 
                          ANPACClientLastName, ANPACClientFirstName, " +
                          "PolicyNumber, AccountOwnerLastName, 
                           AccountOwnerFirstName, SCRACF, SCDateTime, NoteID 
                           FROM NoteTable WHERE SQLMigrationFl = ?";

command = new OleDbCommand(inProgressQuery, connection);
command.Parameters.AddWithValue("SQLMigrationFl", "I");
reader = command.ExecuteReader();

if(reader.HasRows)
{
    while(reader.Read())
    {
        //clear the In Progress flag
        query = "UPDATE NoteTable SET SQLMigrationFl = ? WHERE 
                 NoteTable.NoteID = " + reader[19].ToString();

        command = new OleDbCommand(query, connection);
        command.Parameters.AddWithValue("SQLMigrationFl", DBNull.Value);
        reader = command.ExecuteReader();
    }
}

我发现查询 returns 一个值,并对其进行处理。然后在五秒钟内找到另一条记录并重新处理该记录。 *五秒只是我们在代码中设置的延迟,以检查是否有更多要处理的记录。它一次处理一条记录,而不是抓取十条记录并在同一个 while 循环中一次处理这些记录。我的代码或查询有问题吗?

感谢您的帮助。

罪魁祸首是您使用 reader = command.ExecuteReader(); 重新分配数据 reader。现在将 return 1 个结果,您的下一个循环将超过该 1 个结果。对于非 SELECT 查询,请改用 ExecuteNonQuery。

您可以将代码更新为 "better" 的其他地方是

  1. 只要您有要在 sql 语句中使用的值,就可以使用参数。
  2. 始终指定所有参数的类型。
  3. 始终将实现 IDisposable 的类型实例包装在 using 块中,以确保资源得到清理。

我也建议你不要共享连接实例,下面好像某处可能有一个静态连接。最好不要共享一个,需要的时候create/open一个,然后close/dispose一个。

string inProgressQuery = "SELECT TOP 10 IDType, ID, Program, Date, Body, 
                      AcctNo, ANPACAcctID, ANPACClientID, TEAMID, 
                      ImportDate, AnnualReview, TeamGUID, 
                      ANPACClientLastName, ANPACClientFirstName, " +
                      "PolicyNumber, AccountOwnerLastName, 
                       AccountOwnerFirstName, SCRACF, SCDateTime, NoteID 
                       FROM NoteTable WHERE SQLMigrationFl = ?";

using(var command = new OleDbCommand(inProgressQuery, connection))
{
    // I guessed on the type and length
    command.Parameters.Add(new OleDbParameter("SQLMigrationFl", OleDbType.VarChar, 10)).Value = "I";
    using(var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            //clear the In Progress flag
            const string UpdateQuery = "UPDATE NoteTable SET SQLMigrationFl = ? WHERE NoteTable.NoteID = ?";
            using(var commandUpdate = new OleDbCommand(UpdateQuery, connection))
            {
                commandUpdate.Parameters.Add(new OleDbParameter("SQLMigrationFl", OleDbType.VarChar, 10)).Value = DBNull.Value;
                commandUpdate.Parameters.Add(new OleDbParameter("NoteId", OleDbType.Int)).Value = reader[19];
                commandUpdate.ExecuteNonQuery();
            }
        }
    }
}