Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

ms access - Time comparison in VBA: inequal while same time

I'm moving a database from Microsoft Access to SQL server, and am validating data equality between the remote and the local table. While doing so, I encountered an oddity when comparing a time field.

I'm using the following function:

Public Function CheckAllFieldsEqual(rs1 As DAO.Recordset, rs2 As DAO.Recordset) As Boolean
    Dim fld As DAO.Field
    CheckAllFieldsEqual = True
    For Each fld In rs1.Fields
        If fld.Value <> rs2.Fields(fld.NAME).Value Then GoTo ReturnFalse
    Next fld
    Exit Function
ReturnFalse:
    Debug.Print "Fields inequal! " & fld.NAME & ": " & fld.Value & " - "; rs2.Fields(fld.NAME).Value
    CheckAllFieldsEqual = False
    MsgBox "Inequal!", vbCritical
    Stop
End Function

rs1 is the remote recordset, set to a random row. rs2 is the local variant, set to a row with the same primary key. They should be identical, since I just created the remote table by moving the local table using DoCmd.TransferDatabase

Debug.Print fld.Value returns 09:46:00. Debug.Print rs2.Fields(fld.NAME).Value also returns 09:46:00. However, the comparison doesn't pass.

The odd part:

Debug.Print CDbl(fld.Value) returns 0.406944444444444

Debug.Print CDbl(rs2.Fields(fld.NAME).Value) returns 0.406944444444445

How do I avoid these kinds of errors? Should I add type checking and check equality for time fields with a certain precision, or is there a more simple way to avoid this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use DateDiff. It is exactly for a purpose like this to ignore the floating point errors:

If DateDiff("s", fld.Value, rs2.Fields(fld.NAME).Value) <> 0 Then GoTo ReturnFalse

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...