2011-01-12 54 views
11

我已經映射實體框架實體。 SQL Server 2008中的每個表都包含映射爲字節數組的Timestamp列。陣列的長度總是8.如何比較.NET中的SQL時間戳?

現在我需要時間戳的值在.NET比較。我有兩個解決方案,但我不知道哪一個更好?

  • 比較它的陣列。當第一對字節不同時返回false。
  • 將字節數組轉換爲長整型,比較長整型。

哪種方案更好?或者還有其他解決方案嗎?

回答

11

我們通過將它們作爲字節數組進行比較來實現。爲我們工作得很好。

9

MS SQL Server的時間戳數據類型是語義上等價於二進制(8)(如果非空的)或varbinary(8)(如果爲空的)。 Ergo,將它們作爲字節數組進行比較。

且不說還有的開銷參與轉換爲長。你可以編寫一些不安全的代碼來獲取字節數組的地址,將它們轉換爲長指針並將它們解引用爲長整型,但是這樣做安全就意味着將它們固定在內存中,並使用大量難看的代碼來完成簡單的操作沒有比使用BitConverter更快)。

最快的方式做到這一點,如果性能真的那麼重要的,最快的方法是通過P/Invoke的使用標準C庫的memcmp()函數做比較:

using System; 
using System.Runtime.InteropServices; 

namespace TestDrive 
{ 
    class Program 
    { 
     static void Main() 
     { 
      byte[] a = { 1,2,3,4,5,6,7,8} ; 
      byte[] b = { 1,2,3,4,5,0,7,8} ; 
      byte[] c = { 1,2,3,4,5,6,7,8} ; 
      bool isMatch ; 

      isMatch = TimestampCompare(a , b) ; // returns false 
      isMatch = TimestampCompare(a , c) ; // returns true 

      return ; 
     } 

     [DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)] 
     static extern int memcmp(byte[] x , byte[] y , UIntPtr count) ; 

     static unsafe bool TimestampCompare(byte[] x , byte[] y) 
     { 
      const int LEN = 8 ; 
      UIntPtr cnt = new UIntPtr((uint) LEN) ; 

      // check for reference equality 
      if (x == y) return true ; 

      if (x == null || x.Length != LEN || y == null || y.Length != LEN) 
      { 
       throw new ArgumentException() ; 
      } 

      return (memcmp( x , y , cnt) == 0 ? true : false) ; 
     } 

    } 

} 
+0

@Nicholas非常酷 – 2011-01-12 22:51:32