I have got a database which needs fixing, there is a column named FullPrice (nvarcharMAX). Changing data type to decimal is giving following error
arithmetic overflow error converting expression to data type int
And when I try to change the properties in Design (SSMS) then I get a timeout error.
I tried to remove all whitespaces and any other special characters.
<Current column> <Desired column>
FullPrice FullPrice
31270 312.70
34040 340.40
41130 411.30
64 98 64.98
68 98 68.98
69 98 69.98
72 97 72.97
Remove whitespaces
UPDATE Table1
SET FullPrice = REPLACE(FullPrice, ' ', '')
Convert column and check if NULL values
Select FullPrice AS FullPrice_s, CASE WHEN Isnumeric(FullPrice) = 1
THEN CONVERT(DECIMAL(6,2),FullPrice)
ELSE 0 END AS FullPrice
From Table1
If you check the screenshot the prices should be like this 1813.78 169.99 etc
3条答案
按热度按时间bzzcjhmw1#
After removing the spaces, you can use the
STUFF()
to inject a decimal point into the proper position before converting toNUMERIC
.To inject the decimal point relative to the end of the string, calculate the inject position as an offset from
LEN(string)
. Alternately, the string can be reversed, the decimal point injected after the first two digits, and reversed again.To guard against short values such as "9" representing "0.09", padding the input value with leading zeros may be needed.
The above builds up the conversion step-by-step, using
CROSS APPLY
s to perform the calculations. For actual use, these calculations can be combined as follows. In this case, the reverse-stuff-reverse technique is used, because it eliminated the duplicate expression needed by theLEN()
function.Results:
See this db<>fiddle .
A more simplistic approach would be to convert to a larger type like
DECIMAL(8,2)
and divide the converted result by 100.tyu7yeag2#
Actual issue is
convert(decimal(6,2),FullPrice)
, the reason is the number of digits is more than 6 that's the reason you are getting Arithmetic overflow error converting nvarchar to data type numeric error.h43kikqp3#
My steps would be following:
TempFullPrice
for the target datatype (Decimal(18,2))FullPrice
, after performing some convert operationsTempFullPrice
toFullPrice
FullPrice
toDecimal(18,2)
Queries:
Alter table Table1 add TempFullPrice decimal(18,2)
update Table1 set TempFullPrice= convert(decimal(18,2) ,replace(FullPrice,' ',''))/100
update Table1 set FullPrice=TempFullPrice
alter table Table1 alter column FullPrice decimal(18,2)
alter table Table1 drop column TempFullPrice