Using SQL Server 2008+.
I have a rowversion column (aka timestamp) which I retrieve from the database and convert into into a numeric(20,0) using the following code:
CONVERT(NUMERIC(20,0), RowVersionColumn + 0) AS [RowVersion]
Later on, I need to take that numeric value (which is stored in a ADO.NET DataSet as a ulong/UInt64), and convert it back into a rowversion data type.
This creates problems, though. It seems as though while you can convert out to numeric(20,0), the reverse operation fails to yield the correct value. For instance:
DECLARE @MyNumericValue NUMERIC(20,0)
DECLARE @MyRowVersionValue ROWVERSION
SET @MyNumericValue = 12345
SET @MyRowVersionValue = CONVERT(rowversion, @MyNumericValue)
PRINT CONVERT(NUMERIC(20,0), @MyRowVersionValue + 0)
Running this code prints out a value of 959447040, not 12345. Removing the “+ 0” from the CONVERT statement yeilds the correct result, but I’m still unable to reliably take a numeric value that used to be a rowversion and turn it back into a rowversion whose value is what it should be.
Below is an even better demonstration of this issue:
DECLARE @MyNumericValue NUMERIC(20,0)
DECLARE @MyRowVersionValue ROWVERSION
DECLARE @MyRowVersionValue2 ROWVERSION
SET @MyRowVersionValue = @@DBTS
SET @MyNumericValue = CONVERT(NUMERIC(20,0), @MyRowVersionValue + 0)
SET @MyRowVersionValue2 = CONVERT(rowversion, @MyNumericValue)
SELECT @MyRowVersionValue
SELECT @MyNumericValue
SELECT @MyRowVersionValue2
Your results will vary depending on your inputs, but as an example my output was:
0x0000000003ADBB2F
61717295
0x140000012FBBAD03
The first and last values should match, but they don’t. I’m guessing this has something to do with the fact that binary data conversions often result in padding, and this padding changes the value. See:
http://msdn.microsoft.com/en-us/library/aa223991(v=SQL.80).aspx
Thoughts?
EDIT: To clarify, the fact I’m dealing with rowversion/timestamp is incidental. This same issue happens with BINARY(8) instead of ROWVERSION, as they’re equivalent data types.
While I don’t understand why you would be converting a meaningless ROWVERSION value to a number and then back again, did you try with BIGINT – which matches the 8 bytes required by UInt64 and not the variable number of bytes (depending on the actual value) that forcing NUMERIC(20,0) would change it to?
Or taking your original sample and just swapping BIGINT in for NUMERIC(20,0):