Cannot SUM(TO_NUMBER(varchar2 field)) :ORA 01722 [ORACLE]

為{幸葍}努か 提交于 2019-12-13 22:01:31

问题


I have myfield as varchar2 type and I try to sum this field by using sum(to_number(myfield)) but the result is ORA-01722 invalid number.

before this error occured I used SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:alpha:]]', ''))) and it works but last week I put some decimal value in myfield so this code not work anymore.

Here is my example of data in myfield 10,12,13.5,NULL


回答1:


If you're getting that error from a string like 13.5 then your session's NLS_NUMERIC_CHARACTERS seems to be set to use a comma as the decimal separator:

alter session set nls_numeric_characters=',.';

with your_table (bikou) as (
  select '10' from dual
  union all select '12' from dual
  union all select '13.5' from dual
  union all select null from dual
)
select SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:alpha:]]', '')))
from your_table;

SQL Error: ORA-01722: invalid number

You can either explicitly set the session to use a period as the decimal separator, or provide a format mask that uses a period:

select SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:alpha:]]', ''), '99999999.99999'))
from your_table;

SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:
---------------------------------------
                                   35,5

Or use the decimal separator marker in the model and override the session's NLS setting:

select SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:alpha:]]', ''),
  '99999999D99999', 'nls_numeric_characters=''.,'''))
from your_table;

SUM(TO_NUMBER(REGEXP_REPLACE(BIKOU,'[[:
---------------------------------------
                                   35,5

The mask obviously has to be suitable for all the values you expect back from your regex; what I've used may not be quite right for your data.

This kind of issue is why you should not store numbers or dates as strings. Use the correct data type for your columns.



来源:https://stackoverflow.com/questions/37478848/cannot-sumto-numbervarchar2-field-ora-01722-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!