title: MS SQL datetime precision problem
body: <p>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 <em>lastSaved</em> field (datetime) before saving.</p>
  
  <p>The code looks roughly like this:</p>
  
  <pre><code>private bool orderIsChangedByOtherUser(Order localOrderCopy)
  {
      // Look up fresh version of the order from the DB
      Order databaseOrder = orderService.GetByOrderId(localOrderCopy.Id);
  
      if (databaseOrder != null &amp;&amp;
          databaseOrder.LastSaved &gt; localOrderCopy.LastSaved)
      {
          return true;
      }
      else
      {
          return false;
      }
  }
  </code></pre>
  
  <p>This works for most of the time, but I have found one small bug.</p>
  
  <p>If <em>orderIsChangedByOtherUser</em> returns <em>false</em>, the local copy will have its <em>lastSaved</em> updated to the current time and then be persisted to the database. The value of <em>lastSaved</em> in the local copy and the DB should now be the same. However, if <em>orderIsChangedByOtherUser</em> is run again, it sometimes returns <em>true</em> even though no other user has made changes to the DB.</p>
  
  <p>When debugging in Visual Studio, <em>databaseOrder.LastSaved</em> and <em>localOrderCopy.LastSaved</em> appear to have the same value, but when looking closer they some times differ by a few milliseconds.</p>
  
  <p>I found <a href="http://www.sql-server-performance.com/articles/dev/advanced_date_datetime_handling_p1.aspx" rel="noreferrer">this article</a> with a short notice on the millisecond precision for datetime in SQL:</p>
  
  <blockquote>
    <p>Another problem is that SQL Server
    stores DATETIME with a precision of
    3.33 milliseconds (0. 00333 seconds).</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>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 <em>exactly</em> the same?</p>