Why does MS SQL CAST as bigint result in int overflow? - sql

Why does the following T-SQL statement:
select CAST(COALESCE('3537601039',0) as bigint)
result in the following error when run against MS SQL Server 10?
The conversion of the varchar value '3537601039' overflowed an int
column.
Is there a "more correct" way to do this conversion of a varchar to a bigint that would avoid this problem when the number is within range of a bigint?

The first thing that is happening is that your string is trying to convert to a regular int to match the 0. Try this:
select CAST(COALESCE('3537601039','0') as bigint)

It appears that putting the unqualified zero in the coalesce is implying a conversion to a smaller int before it is explicitly recast to a bigint.
The following simple change to make it a coalesce of string values solves the problem:
select CAST(COALESCE('3537601039','0') as bigint)

Cast first, then do ISNULL
select ISNULL(CAST('3537601039' as bigint), 0)
select ISNULL(NULLIF(ISNULL(CAST('3537601039' as bigint), 0), 0), 1) + 3537601039
sql server firstly discovers isnull(string, numeric) and that numeric zero is by default int. So it tries to convert that string containing bigint to int. You were trying to cast to bigint too late.
another try:
select ISNULL('3537601039', 100000000000)

Related

How do I convert a varchar into a negative number?

I have a table where a column has data such as ($23,324.09). If it's $23,324.09, then I can convert it to money, then a float. But the ( ) is causing errors when I try that. Will I have to apply a UDF to that column or is there another way to convert such a value.
NOTE: I don't have control on how the data gets to that table.
You could also use PARSE or TRY_PARSE
SELECT TRY_PARSE('($23,324.09)' AS MONEY USING 'en-US')
Returns
-23324.09
using a few replace():
declare #col varchar(32) = '($23,324.09)'
select convert(decimal(19,4),replace(replace(replace(replace(#col,'(','-'),',',''),')',''),'$',''))
returns: -23324.0900
Running a simple test, this is runs in about 1/3rd of the time as the parse() equivalent.
dbfiddle: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=675f6eb70986bd24880c66a8be4f5cbd
Here is a shorter alternative that uses the money data type:
select convert(money,replace(replace(#col,'(','-'),')',''))
dbfiddle: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=31bfc3e1e48b8f863e89bcef9a6ffddc

Sql Server SUM function with Int and Decimal Conversion

Recently I was Playing with SQL Server data types, and a Large number of data in the table and trying to figure out the Performance with Varchar and Numeric data. But, I got some error which I don't think should not have been but it is. My problem is below :
I have a table :
create table sa(f1 varchar(100))
I have a Stored Procedure that Inserts 100000 data into the table :
create proc sad
as
begin
declare #i int=0
while #i<100000
begin
insert into sa values(#i)
set #i=#i+1
end
end
exec sad
And I have tested the following:
select CONVERT(int,f1) from sa //Works Fine, i tested after the Problem
select sum(convert(int,f1)) from sa //Didn't Worked, So i tested above and Below
select sum(convert(decimal(18,2),f1)) from sa //And, it again works fine
But, When I sum Converting F1 to Int, it shows me an error.
But, when I only select Converting to Int it's fine.
And, when I sum Converting F1 to decimal it works Fine.
What is the SUM function data type?
On the Above data, it works well with Decimal but not Int?
Why?
I'm Getting the Following error
Arithmetic overflow error converting expression to data type int.
You're summing as INT which has a range that cannot hold that sum.
The DECIMAL can.
The sum of all values from 1 up to 99999 is 4999950000, the maximum INT value is 2147483647, less than half of what the sum ends up as.
When you sum INT's, you're getting a new INT. When you're summing DECIMAL's, you're getting a new DECIMAL, so the input type defines the output type.
You can switch to using bigint instead, and it should "be fine".
Also, on a second note, please don't store numbers as text!
According to MS documentation (see https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql), the SUM() function returns values of a different type, according to the datatype of the column you are adding: if the column is of type int, tinyint, or smallint, then SUM returns values of type int.
Converting to bigint or decimal makes SUM() return a larger datatype, this explains why in that case you have no overflow.
Expect you have exceeded the maximum int value that SQL Server allows (2,147,483,647) - see https://learn.microsoft.com/en-us/sql/t-sql/data-types/int-bigint-smallint-and-tinyint-transact-sql.
Decimal allows a far higher limit of up to 10^38 - 1 (i.e. 1 with 38 zeros after) - see https://learn.microsoft.com/en-us/sql/t-sql/data-types/decimal-and-numeric-transact-sql.
However, if the values are of type int, I wouldn't recommend converting to decimal. Decimal values are useful when you have figures with possible numbers after the decimal place with a known precision and scale (e.g. for currency, percentages etc.) As another poster has suggested, the best conversion here would be to a bigint:
select sum(cast(f1 as bigint)) from sa
Looks like your resulting sum is too big for int, use bigint, also check int, bigint, smallint, and tinyint (Transact-SQL)
select sum(convert(bigint,f1)) from sa
Try this:
CONVERT(NUMERIC(18,2),SUM(0))

Convert nvarchar to bigint in Sql server 2008

I want insert all rows of a table into another table, and I also want convert a nvarchar field into bigint, but when I use convert(bigint, col1) SQL Server shows an error:
Error converting data type nvarchar
to bigint
How can I fix this problem?
You could try to use ISNUMERIC to determine those rows that are indeed numeric:
UPDATE dbo.YourTable
SET BigIntColumn = CAST(NVarcharColumn AS BIGINT)
WHERE ISNUMERIC(NVarcharColumn) = 1
That would convert those rows that can be converted - the others need to be dealt with manually.
You should convert bigint to nvarchar not vice versa
cast(Other_Column_name as nvarchar) not cast (Column_Name as bigint)
you can try this:
CAST(CAST(col1 as NUMERIC) as BIGINT)
Here I convert navrchar value of column into bigInt and than perform Addition of thos two columns find blow :
SELECT (CAST(col1 AS BIGINT) + CAST(col2 AS BIGINT)) AS TotalValue from tableName

Arithmetic overflow error when summing an INT, how do I cast it as a BIGINT?

When I try to get the sum of a column from a table I get the error Arithmetic overflow error converting expression to data type int because the resulting number is to big for an INT. So I tried to CAST to a BIGINT using the following
SELECT CAST(SUM(columnname) AS BIGINT) FROM tablename
This gives me the same error. Any ideas what i'm doing wrong?
Try converting it before summing. eg.
SELECT SUM(CONVERT(bigint, columnname)) FROM tablename
or
SELECT SUM(CAST(columnname AS BIGINT)) FROM tablename

Convert a string to int using sql query

How to convert a string to integer using SQL query on SQL Server 2005?
You could use CAST or CONVERT:
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.
Conversion failed when converting the varchar value '56.72' to data type int.
To get around this just do two converts as follows:
STRING -> NUMERIC -> INT
or
SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)
When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):
INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA
Try this one, it worked for me in Athena:
cast(MyVarcharCol as integer)