遍历表并更改值时访问崩溃

Posted

技术标签:

【中文标题】遍历表并更改值时访问崩溃【英文标题】:Access crashes when looping through a table and changing values 【发布时间】:2015-04-19 09:22:09 【问题描述】:

当我循环访问一个表并使用以下代码更改其中一个字段的值时,Access 不断崩溃:

Set db = CurrentDb
Set rs = db.OpenRecordset(prProdTblName)
'PrevDept , PrevOpNo, PrevPartNo
rs.MoveFirst
rs.Edit
rs![Op No] = 10
rs.Update
Do Until rs.EOF
    With rs
        PrevOpNo = ![Op No]
        PrevDept = ![Department Code]
        PrevPartNo = ![Part No]
        .MoveNext
        .Edit
        If (![Department Code] = "SMD" And PrevDept <> "SMD") Then
            ![Op No] = 500
        ElseIf (![Department Code] <> "SMD" And PrevDept = "SMD" And ![Part No] = PrevPartNo) Then
            ![Op No] = 1000
        ElseIf (rs![Part No] <> PrevPartNo) Then
            ![Op No] = 10
        Else
            ![Op No] = PrevOpNo + 10
        End If
        .Update
    End With
Loop
rs.Close
Set rs = Nothing

另外,当我尝试使用替代 SQL 代码时,它似乎是一个无休止的查询:

SQLcommandStr = "SELECT T1.[ID], (Select IIF((T1.[Department Code]='SMD') AND (T2.[Department Code]<>'SMD'),500,IIF((T1.[Department Code]<>'SMD') AND (T2.[Department Code]='SMD') AND (T1.[Part No] = T2.[Part No]),1000,IIF((T1.[Part No] <> T2.[Part No] OR (T1.[ID] = (SELECT MIN(T4.[ID]) FROM " & prProdTblName & " T4))),10,T2.[Op No] + 10))) From " & prProdTblName & " T2 WHERE T2.[ID] = (SELECT MAX(T3.[ID]) FROM " & prProdTblName & " T3 WHERE T1.[ID] > T3.[ID])) INTO TblTemp FROM " & prProdTblName & " T1"

DoCmd.RunSQL SQLcommandStr

【问题讨论】:

【参考方案1】:

你可能在 EOF 时反弹:

Set db = CurrentDb
Set rs = db.OpenRecordset(prProdTblName)
rs.MoveFirst
rs.Edit
rs![Op No] = 10
rs.Update
Do Until rs.EOF
    With rs
        PrevOpNo = ![Op No]
        PrevDept = ![Department Code]
        PrevPartNo = ![Part No]
        .MoveNext
        If .EOF = False Then
            .Edit
            If (![Department Code] = "SMD" And PrevDept <> "SMD") Then
                ![Op No] = 500
            ElseIf (![Department Code] <> "SMD" And PrevDept = "SMD" And ![Part No] = PrevPartNo) Then
                ![Op No] = 1000
            ElseIf (rs![Part No] <> PrevPartNo) Then
                ![Op No] = 10
            Else
                ![Op No] = PrevOpNo + 10
            End If
            .Update
        End If
    End With
Loop
rs.Close
Set rs = Nothing

【讨论】:

你是对的,问题是 EOF,但是因为 EOF 是一个指针而不是最后一行本身,所以循环仍然会反弹。我的解决方案是计算行数并在最后一行退出循环。 THX

以上是关于遍历表并更改值时访问崩溃的主要内容,如果未能解决你的问题,请参考以下文章

遍历html表并计算值

遍历表并在 js/jquery 中创建一个数组

Oracle - 遍历表并检查属性中的值

mysql 遍历所有表并条件查询

SQL遍历表并删除如果不是特定名称

遍历所有工作表并查找范围内的值。如果找到然后执行一些操作并转到