Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast rowversion to bigint

Tags:

sql-server

In my C# program I don't want to work with byte array, therefore I cast rowversion data type to bigint:

SELECT CAST([version] AS BIGINT) FROM [dbo].[mytable]

So I receive a number instead of byte array. Is this conversion always successful and are there any possible problems with it? If so, in which data type should I cast rowversion instead?

like image 876
user1613797 Avatar asked Jun 04 '14 13:06

user1613797


People also ask

How do I CAST to Bigint?

You need to use the CAST operator along with CONV() function. The CONV() function can be used to convert one base number system to another base system. For Example, The 16 is one base system and 10 is another base system. The 16 base system is hexadecimal and 10 is a decimal.

What is Rowversion?

Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The rowversion data type is just an incrementing number and does not preserve a date or a time.

What is CAST () and convert () functions in SQL Server?

The T-SQL language offers two functions to convert data from one data type to a target data type: CAST and CONVERT. In many ways, they both do the exact same thing in a SELECT statement or stored procedure, but the SQL Server CONVERT function has an extra parameter to express style.

What is CAST in T SQL?

SQL Server CAST() Function The CAST() function converts a value (of any type) into a specified datatype.


1 Answers

rowversion and bigint both take 8 bytes so casting seems possible. However, the difference is that bigint is a signed integer, while rowversion is not.

This is a max value of rowversion that will cast properly to max positive bigint number (9223372036854775807):

select cast(0x7FFFFFFFFFFFFFFF as bigint)

But starting from here, you'll be getting negative numbers:

select cast(0x8000000000000000 as bigint)

I didn't check if the latter cast throws an error in C#.

You problably won't reach more than 9223372036854775807 rows in your table, but still it's something you should know about, and I personally wouldn't recommend doing this unless you are certain that this problem will never occur in your solution.

like image 81
AdamL Avatar answered Sep 25 '22 11:09

AdamL