如何使用C#从sql server读取时间戳类型的数据?
我在 .NET 中得到的结果如下:
var lastRowVersion = SqlHelper.ExecuteScalar(connStr, CommandType.Text, "select
top 1 rowversion from dbo.sdb_x_orginfo order by rowversion desc");
结果是一个字节数组 [0]= 0,[1]=0,[2]=0,[3]=0,[4]=0,[ 5]=0,[6]=30,[7]=138
,但 SQL Server 中的结果是0x0000000000001E8A
。
如何在 .NET 中获取值 "0x0000000000001E8A"
?
I get the result in .NET like this:
var lastRowVersion = SqlHelper.ExecuteScalar(connStr, CommandType.Text, "select
top 1 rowversion from dbo.sdb_x_orginfo order by rowversion desc");
The result is a byte array [0]= 0,[1]=0,[2]=0,[3]=0,[4]=0,[5]=0,[6]=30,[7]=138
, but the result in SQL Server is 0x0000000000001E8A
.
How can I get the value "0x0000000000001E8A"
in .NET?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我发现从 sql server 返回的 byte[] 具有错误的 Endian-ness,因此转换为 long (Int64) 无法正常工作。我通过在将数组传递到 BitConverter 之前调用 Reverse 解决了这个问题:
另外,我认为最好转换为 UInt64。
I found that the byte[] returned from sql server had the wrong Endian-ness and hence the conversion to long (Int64) did not work correctly. I solved the issue by calling Reverse on the array before passing it into BitConverter:
Also, I thought it better to convert to UInt64.
如果您只想将
byte[]
转换为System.Int64
(又名long
),则使用BitConverter.ToInt64
:要将其显示为十六进制字符串,您可以可以使用
X
格式说明符,例如:If you just want to convert
byte[]
to aSystem.Int64
(akalong
) then useBitConverter.ToInt64
:To display it as a hex string, you can use the
X
format specifier, e.g.:这是一句俏皮话:
结果是:
请注意,有 其他性能更好的选项。
Here's an one-liner:
The result is:
Just be aware that there are other options that perform better.
您可以使用以下查询,该查询将返回 bigint 而不是返回十六进制。
从 dbo.sdb_x_orginfo order by rowversion desc 中选择前 1 个类型转换(rowversion as bigint)rowversion
You can use following query which will return bigint instead of returning hex.
select top 1 cast(rowversion as bigint) rowversion from dbo.sdb_x_orginfo order by rowversion desc
与“Ashish Singh”相同,我在 DB 上转换为 bigint 后返回到 c#,并在代码端使用 Int64。
在 c#/VB 中转换为 long/Int64/UInt64 给出了错误的结果。(即使在由于小端问题而反转数组之后。)
请注意 DB 端 RowVersion 时间戳具有 MIN_ACTIVE_ROWVERSION() ,它指示最后提交的时间戳
Same as "Ashish Singh" I returned to c# after converting to bigint on DB and used Int64 on the code side.
Converting to long/Int64/UInt64 in c#/VB gave wrong results.(even after reversing the array because of the little endian issue.)
Pay attention on the DB side that RowVersion timestamp has MIN_ACTIVE_ROWVERSION() which indicates the last commited timestamp
对我来说效果很好
Works fine for me