SQL Server CAST from varchar to numeric fails with error - sql-server

I have a column of data that contains 9 digits of numeric values, but the column is defined as a varchar. I need to CAST the field to a numeric value so I can divide the sum of the column by 100. e.g.
select CAST(field1 as numeric(9,2)) / 100 from table;
I get the following error when running the query: Arithmetic overflow error converting varchar to data type numeric.
If I perform a double CAST from varchar -> int -> numeric, the CAST works. e.g.
select CAST(CAST(field1 as int) as numeric(9,2)) / 100 from table;
Is there a reason why the single CAST from varchar -> numeric results in a SQL error, but the double CAST works?

If your field contains 9 digits, it could be a max of 999,999,999. My original thought was that your cast should be CAST (NUMERIC 11, 2)
edit
To be on the safe side, with 9 character length, you could have numbers ranging from 999,999,999 to 0.1234567. This means you need 9 digits before the decimal point and 7 after (total 16). Therefore your cast should be CAST (NUMERIC (16,7)
select CAST(field1 as numeric(16,7) from table;

The cause of the error was one row that had '-' as the value for the field. CASTing directly to NUMERIC doesn't work, but CASTing to INT first forced the '-' fields to return 0.

Related

Can select float value but fail to insert it

When I select I get the following value: 1.79769313486232E+308
The Column type is float.
When I'm trying to insert this value to the same table and column, I'm getting the following error:
The floating point value '1.79769313486232E+308' is out of the range of computer representation (8 byte)
When I select with master.dbo.fn_varbintohexstr(ColumnName) I'm getting
the hex value as 0x7fefffffffffffff which is less then 8 bytes...
Any explanation please?

Cast giving an error

Why is this simple code giving me an error:
Conversion failed when converting the varchar value '3.0' to data type
int.
select cast(value as INT)
from CV3BasicObservation (nolock)
where value >= 110
SQL Server doesn't want to convert a number string that looks like a decimal to integer because you could lose precision. You could trick it with the round function:
select cast(round(value,0) as INT)
from CV3BasicObservation (nolock)
where cast(round(value,0) as INT) >= 110
NOTE: You have to do it to all instances of the field value where you are explicitly converting it to int or where it is implicitly converting it for comparison an int type value.

How to remove two digits after decimal in SQL Server

I have a number with two digits after the decimal point; I try to cast this number using CAST for example:
Select SUM(CAST((123345.56) as decimal(28, 2))) * 100 AS AMOUNT
I get the following result
12334556.00
but I want get only 12334556 without displaying two digits after the decimal point.
Thank you.
It is not clear what you really want to do, but
SELECT SUM(CAST((123345.56 * 100.0) AS DECIMAL(28,0))) AS AMOUNT
gives 12334556.
When you use a number in the format 1234.56 it is a decimal literal in SQL Server: see "decimal constants" in Constants (Transact-SQL).
Integer data type is whole numbers, so cast your calculated value as int.
Select SUM(CAST((123345.56 * 100) as int)) AS AMOUNT

How do I do decimal arithmetic on two varchars and return result to an aliased column?

I have two fields of type varchar that contain numeric values or blank strings, the latter of which I have filtered out to avoid Divide by Zero errors.
I am attempting to determine the percentage value that num2 represents in relation to num1, i.e. (Num_2 * 1 / Num_1). Relatively simple math.
The problem I am having is that I cannot seem to do the math and then cast it to a decimal value. I keep receiving Arithmetic overflow error converting int to data type numeric errors.
Can someone help me out with the casting issue?
You didn't interpret the error correctly.
It is not about casting the result of your math to float, it is about implicit type casting before the equation is evaluated.
You have in your table some values that cannot be converted to numeric, because they are not valid numbers or numbers out of range. It is enough that one row contains invalid data to make fail the whole query.
perhaps you're looking for something similar to this?
declare #table table (
[numerator] [sysname]
, [denominator] [sysname]);
insert into #table
([numerator],[denominator])
values (N'1',N'2'),
(N'9999999999',N'88888888888');
select case
when isnumeric([numerator]) = 1
and isnumeric ([denominator]) = 1
then
cast([numerator] as [float]) / [denominator]
else
null
end
from #table;
Is this what you're looking for?
select cast('25.5' as decimal(15, 8)) / cast('100.0' as decimal(15, 8))
The example above will return this:
0.25500000000000000000000
In this case, I'm converting the operand types before they get used in the division.
Remember to replace the literals in my query by your field names.
you said that can be number or blank string.
son try something like this:
SELECT
(CASE WHEN NUM_2 = '' THEN 0 ELSE CAST(NUM_2 AS NUMERIC(15,4)) END)
/
(CASE WHEN NUM_1 = '' THEN 1 ELSE CAST(NUM_1 AS NUMERIC(15,4)) END)
you test if string is blank. if it is, you use 0 (or 1, to avoid division by zero)

Format string in SQL Server 2005 from numeric value

How I can format string with D in start and leading zeros for digits with length of less than four. E.g:
D1000 for 1000
D0100 for 100
I have tried to work with casting and stuff function, but it didn't work as I expected.
SELECT STUFF('D0000', LEN(#OperatingEndProc) - 2, 4, CAST((CAST(SUBSTRING(#OperatingEndProc, 2, 4) AS INT) + 1) AS VARCHAR(10)));
adding 10000 to the value will cause the number to have have extra zeros first, then casting it as varchar and only using the last 4 will ignore the added 10000. This require that all numbers are between 0 and 9999
declare #value int = 100
select 'D' + right(cast(#value + 10000 as varchar(5)), 4)
This illustration board can come in handy when you wanna get the proper casting practices..
This shows all explicit and implicit data type conversions that are
allowed for SQL Server system-supplied data types. These include xml,
bigint, and sql_variant. There is no implicit conversion on assignment
from the sql_variant data type, but there is implicit conversion to
sql_variant
You can download it here http://www.microsoft.com/en-us/download/details.aspx?id=35834

Resources