ORA-01722: Oracle 11g 的 Fr Locale 编号无效

ORA-01722: Invalid number for Fr Locale for Oracle 11g

我有一个名为 My_View 的视图,其中包含一个具有十进制数字数据的 varchar 列。 同时,select 计算平均值时出现错误

ORA-01722: Invalid number for Fr Locale

这是我试过但出现错误的 oracle 查询:

select (AVG(MY_COLUMN)) 
from  MY_TABLE;

select TO_NUMBER((AVG(MY_COLUMN)), '90.9999', 'NLS_NUMERIC_CHARACTERS='',.''') 
from  MY_TABLE
GROUP BY MY_COLUMN;

如何摆脱这个错误?

问题似乎出在不属于 "numeric" 的数据中(为什么要将数字保留在 VARCHAR2 列中)?例如,它包含“123A56”。该值的 AVG 是多少?

一个简单的选项是使用 REGEXP_LIKE 并仅对 "valid" 值执行数值运算。例如:

SQL> with test (col) as
  2    (select '1234.56' from dual union all  -- valid
  3     select '131'     from dual union all  -- valid
  4     select 'ABC'     from dual union all  -- invalid
  5     select 'xy.23'   from dual union all  -- invalid
  6     select '.3598'   from dual union all  -- invalid
  7     select '12.34.56'from dual            -- invalid
  8    )
  9  select col,
 10         to_number(col, '9999D9999', 'nls_numeric_characters = ''.,''') col_as_num
 11  from test
 12  where regexp_like(col, '^\d+\.?\d+$');

COL      COL_AS_NUM
-------- ----------
1234.56     1234,56
131             131

SQL>

现在您可以AVG这样的值:

SQL> with test (col) as
  2    (select '1234.56' from dual union all  -- valid
  3     select '131'     from dual union all  -- valid
  4     select 'ABC'     from dual union all  -- invalid
  5     select 'xy.23'   from dual union all  -- invalid
  6     select '.3598'   from dual union all  -- invalid
  7     select '12.34.56'from dual            -- invalid
  8    )
  9  select avg(to_number(col, '9999D9999', 'nls_numeric_characters = ''.,''')) result
 10  from test
 11  where regexp_like(col, '^\d+\.?\d+$');

    RESULT
----------
    682,78

SQL>

从Oracle 12.2开始,可以使用to_number()on conversion error子句在转换失败时return一个默认值。这对您的用例很方便:您可以 return null 转换错误,聚合函数 avg() 会很乐意忽略。

select avg(
    to_number(
        my_column default null on conversion error, 
        '9999d9999', 
        'nls_numeric_characters = ''.,'''
    )
) my_avg
from my_table;