优化Access中非唯一记录的删除

时间:2017-08-30 08:27:07

标签: sql access-vba

我正在创建一个Recordset,其中包含多次出现的所有条目,然后遍历此RS中的每个元素并删除所有旧条目。 只应删除BTNR和ARPNR上不唯一的条目。 我也不想删除最新的多条记录。 有没有人知道如何让这个更快,因为它需要很长时间,因为它必须定期运行600多条记录。我是VBA和SQL的新手,所以可能有更好的方法来做到这一点。

Sub DeleteMult()
Dim allMult As DAO.Recordset
Dim strSQL As String

strSQL = "SELECT ARPs.ARPNR, ARPs.Änderungsdatum FROM ARPs WHERE ARPs.BTNR IN (SELECT BTNR FROM ARPs GROUP BY BTNR HAVING COUNT(BTNR) > 1);"

Set allMult = CurrentDb.OpenRecordset(strSQL)

With allMult

    'Check that RecordSet isn't empty
    If Not .BOF And Not .EOF Then

        .MoveLast
        .MoveFirst

        'Loop to the end of the RecordSet
        While (Not allMult.EOF)
            'Delete all multiple entries except the newest
            With CurrentDb.CreateQueryDef("", _
                "DELETE FROM ARPs WHERE ARPNR = prm0 AND Änderungsdatum < prm1")
                .Parameters("prm0") = allMult.Fields("ARPNR")
                .Parameters("prm1") = allMult.Fields("Änderungsdatum")
                .Execute
                .Close
            End With

            With CurrentDb.CreateQueryDef("", _
                "DELETE FROM KoGr WHERE ARPNR = prm0 AND Änderungsdatum < prm1")
                .Parameters("prm0") = allMult.Fields("ARPNR")
                .Parameters("prm1") = allMult.Fields("Änderungsdatum")
                .Execute
                .Close
            End With

            With CurrentDb.CreateQueryDef("", _
                "DELETE FROM SA WHERE ARPNR = prm0 AND Änderungsdatum < prm1")
                .Parameters("prm0") = allMult.Fields("ARPNR")
                .Parameters("prm1") = allMult.Fields("Änderungsdatum")
                .Execute
                .Close
            End With

            .MoveNext
        Wend

    End If

    .Close
End With

'empty Memory
Set allMult = Nothing

End Sub

这是一个数据集示例。应删除标记为读数的数据。当然每个BTNR通常有~60 KoGr和SA。如果最新的ARPNR中有超过1个BTNR,则应保留所有这些。 This is a sample Dataset. Data marked read should be deleted. Of course there are usually ~60 KoGr and SA for each BTNR. If the newest ARPNR has more than 1 BTNR in it all of them should be kept.

我现在尝试了一个SQL语句,因为我偶然发现了MAX()功能。

strSQL = "Delete A 
          FROM ARPs AS A 
               JOIN (SELECT BTNR, ARPNR, Änderungsdatum 
                     FROM ARPs AS A1 
                     WHERE A1.BTNR = A.BTNR 
                           AND A1.ARPNR = A.ARPNR 
                           AND A1.Änderungsdatum <> (SELECT MAX(Änderungsdatum) 
                                                     FROM ARPs 
                                                     WHERE BTNR = A1.BTNR 
                                                           AND ARPNR = A1.ARPNR)) AS R 
               ON R.ARPNR = A.ARPNR 
                  AND R.Änderungsdatum = T.Änderungdatum;"

但它在FROM子句中返回错误。

0 个答案:

没有答案