2011-01-12 50 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