Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VARCHAR to DECIMAL

Tags:

sql

sql-server

I want to convert a varchar(max) column to decimal(10,4).

When I try to use cast or convert I am getting an arithmetic overflow exception. The issue is that the data stored in the varchar column may contain different precisions and different scales. For example, 123456789.1234567', 1.12345678 or 123456.1234.

For values like 123456.1234 it is converting with out any issue but for other values I am having some problems.

like image 1000
Biju Thomas Avatar asked Jun 18 '12 18:06

Biju Thomas


People also ask

Can varchar have decimals?

3 Answers. Show activity on this post. The short answer is: No, it will hurt performance. The longer answer: VARCHAR fields are variable length, meaning, that the formatting of the database blocks cannot pre-account for the size of the data filling in there.

How do I convert varchar to numeric?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.

How do I convert a number to a DECIMAL in SQL?

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).


1 Answers

After testing I found that it was not the decimal place that was causing the problem, it was the precision (10)

This doesn't work: Arithmetic overflow error converting varchar to data type numeric.

DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'  SELECT CAST(@TestConvert AS DECIMAL(10, 4)) 

This worked

DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'  SELECT CAST(@TestConvert AS DECIMAL(13, 4)) 

Should be like 9 int + 4 floating = 13 chars

like image 194
codingbiz Avatar answered Oct 11 '22 13:10

codingbiz