如何比较.NET中的SQL时间戳?

Lad*_*nka 11 .net c# sql-server

我已经映射了实体框架实体.SQL Server 2008中的每个表都包含Timestamp列,该列被映射为字节数组.数组的长度始终为8.

现在我需要比较.NET中的时间戳值.我有两个解决方案,但我不知道哪个更好?

  • 比较它作为数组.当第一对字节不同时返回false.
  • 将字节数组转换为long,比较long.

哪种解决方案更好?或者还有其他解决方案吗?

Ran*_*der 11

我们将它们作为字节数组进行比较.对我们来说很好.


Nic*_*rey 9

MS SQL Server的时间戳数据类型在语义上等效于二进制(8)(如果不可为空)或varbinary(8)(如果可为空).因此,将它们作为字节数组进行比较.

更不用说转换为long的开销.您可以编写一些不安全的代码来获取字节数组的地址,将它们转换为长指针并将它们取消引用为long,但要安全地执行此操作意味着将它们固定在内存中并使用大量丑陋的代码来执行基本上简单的操作(并且可能不比使用BitConverter快.

最快的方法是,如果性能真的很重要,最快的方法是使用标准C库的memcmp()函数通过P/Invoke进行比较:

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 ) ;
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

  • 除非重新发明轮子,否则你使用标准的转换数据方式--BitConverter.ToInt64(binary.ToArray(),0),是的,它是单行的. (4认同)