简体   繁体   中英

How to convert varchar2 column containing decimal numbers to number

I have a column named discount of type varchar2. It contains decimal numbers as well as integers. I want to convert it into number type. So I used this query

update table_name set newdiscount=to_number(discount)

I am getting the "Not a valid number" error. Here new discount is of type number.

I checked if there are any commas present, but they aren't. Of course, there are many rows containing decimal points which are showing up in the result of query test to check any non digit values

SELECT discount FROM table_name  WHERE REGEXP_LIKE(discount, '[^[:digit:]]');

How to copy the discount values in to the newdiscount column of type number?

Probably NLS_NUMERIC_CHARACTERS parameter in Oracle session differs from decimal point.

You can test it such a way:

select 
  substr(VALUE ,1,1) as decimal_separator,
  substr(VALUE ,2,1) as group_separator
from 
  nls_session_parameters 
where 
  parameter = 'NLS_NUMERIC_CHARACTERS'

You can alter session before updating table to activate proper separator:

alter session set  NLS_NUMERIC_CHARACTERS = '.,' 

or substitute decimal point to current decimal separator each time:

update table_name 
set newdiscount = ( select to_number( replace(discount, '.', substr(value,1,1)) )
                    from nls_session_parameters 
                    where parameter = 'NLS_NUMERIC_CHARACTERS'                  
                  )

Some proof of concept demonstration can be found in this SQLFiddle .

You can try updating only those validates to be a numeric like,

update table_name
set new_discount = CASE WHEN regexp_like(discount, '^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$') THEN to_number(discount) ELSE -99999 END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM