I have a situation where two persons might work on the same order (stored in an MS SQL database) from two different computers. To prevent data loss in the case where one would save his copy of the order first, and then a little later the second would save his copy and overwrite the first, I've added a check against the lastSaved field (datetime) before saving.
The code looks roughly like this:
private bool orderIsChangedByOtherUser(Order localOrderCopy)
{
// Look up fresh version of the order from the DB
Order databaseOrder = orderService.GetByOrderId(localOrderCopy.Id);
if (databaseOrder != null &&
databaseOrder.LastSaved > localOrderCopy.LastSaved)
{
return true;
}
else
{
return false;
}
}
This works for most of the time, but I have found one small bug.
If orderIsChangedByOtherUser returns false, the local copy will have its lastSaved updated to the current time and then be persisted to the database. The value of lastSaved in the local copy and the DB should now be the same. However, if orderIsChangedByOtherUser is run again, it sometimes returns true even though no other user has made changes to the DB.
When debugging in Visual Studio, databaseOrder.LastSaved and localOrderCopy.LastSaved appear to have the same value, but when looking closer they some times differ by a few milliseconds.
I found this article with a short notice on the millisecond precision for datetime in SQL:
Another problem is that SQL Server stores DATETIME with a precision of 3.33 milliseconds (0. 00333 seconds).
The solution I could think of for this problem, is to compare the two datetimes and consider them equal if they differ by less than say 10 milliseconds.
My question to you is then: are there any better/safer ways to compare two datetime values in MS SQL to see if they are exactly the same?