I've been banging my head against the wall with this one all morning.
The following SQL code and its' result makes no sense to me:
select CONVERT(INT, CONVERT(BINARY(30),2691485888))
which results in:
-1060082528
What? Why doesn't the result equal my original integer?
My whole objective is to convert an integer into bytes and store those bytes into the database, but without getting this basic example to work I am stuck. Can anyone explain what I'm doing wrong?
By the way, I am using Sql Server 2005 (9.0.4340)
Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).
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.
The CONVERT() function converts a value (of any type) into a specified datatype.
TO_NUMBER converts a string to a number of data type NUMERIC. TO_CHAR performs the reverse operation; it converts a number to a string. CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER.
As I noted in my earlier comment, 2,691,485,888 is larger than what an INT can hold.
This will work:
select CONVERT(BIGINT, CONVERT(BINARY(30), CONVERT(BIGINT, 2691485888)))
The value 2691485888
cannot be held in an INT - it is too large:
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
There is a good chance you are seeing the result of an overflow.
A data type that can handle that value is BIGINT.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With