如何比较.NET中的SQL时间戳?
我已经映射了entity framework实体。 SQL Server 2008中的每个表都包含Timestamp列,该列被映射为字节数组。 数组的长度始终为8。
现在我需要比较.NET中的时间戳值。 我有两个解决方案,但我不知道哪个更好?
- 将其与数组进行比较。 当第一对字节不同时返回false。
- 将字节数组转换为long,比较long。
哪种解决方案更好? 或者还有其他解决方案吗?
我们将它们作为字节数组进行比较。 对我们来说很好。
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 ) ; } } }