Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read timestamp type's data from sql server using C#?

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?

like image 515
user980447 Avatar asked Nov 08 '11 06:11

user980447


2 Answers

Here's an one-liner:

var byteArray = new byte[] { 0, 0, 0, 0, 0, 0, 30, 138 };

var rowVersion = "0x" + string.Concat(Array.ConvertAll(byteArray, x => x.ToString("X2")));

The result is:

"0x0000000000001E8A"

Just be aware that there are other options that perform better.

like image 54
Marcos Dimitrio Avatar answered Oct 05 '22 09:10

Marcos Dimitrio


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:

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

var value = BitConverter.ToUInt64(byteArray.Reverse().ToArray(), 0);

Also, I thought it better to convert to UInt64.

like image 44
Phil Kloc Avatar answered Oct 05 '22 07:10

Phil Kloc