如何使用C#从sql server读取时间戳类型的数据?

use*_*447 12 c# timestamp rowversion

我在.NET中得到的结果如下:

var lastRowVersion = SqlHelper.ExecuteScalar(connStr, CommandType.Text, "select
top 1 rowversion from dbo.sdb_x_orginfo order by rowversion desc");
Run Code Online (Sandbox Code Playgroud)

结果是一个字节数组[0]= 0,[1]=0,[2]=0,[3]=0,[4]=0,[5]=0,[6]=30,[7]=138,但SQL Server中的结果是0x0000000000001E8A.

如何"0x0000000000001E8A"在.NET中获得价值?

小智 24

我发现从sql server返回的byte []具有错误的Endian-ness,因此转换为long(Int64)无法正常工作.我在将数据传递给BitConverter之前通过调用Reverse来解决了这个问题:

byte[] byteArray = {0, 0, 0, 0, 0, 0, 0, 8};

var value = BitConverter.ToUInt64(byteArray.Reverse().ToArray(), 0);
Run Code Online (Sandbox Code Playgroud)

另外,我认为最好转换为UInt64.


bob*_*mcr 5

如果你只想转换byte[]System.Int64(又名long)然后使用BitConverter.ToInt64:

SqlBinary binary = /* ... */;
long value = BitConverter.ToInt64(binary.Value, 0); // 0 is the start index in the byte array
Run Code Online (Sandbox Code Playgroud)

要将其显示为十六进制字符串,您可以使用X 格式说明符,例如:

Console.WriteLine("Value is 0x{0:X}.", value);
Run Code Online (Sandbox Code Playgroud)

  • 请参阅另一个答案 - SqlBinary.Value具有相反的字节顺序,因此您最有可能想要反转字节. (4认同)