为什么在使用字符串函数和字符串数据时出现无效数字错误?

Why invalid number error when working with string functions and string data?

Using LPAD requirement,我的表情都是汉字。 为什么我会收到 ORA-01722: invalid number 消息?

我想用前导零填充我的 varchar2 值。 我所有的 airpor_codes 最多三个字节,如有必要,我想用前导零填充。

在这个例子中,我想要 07770LAX

/* This works */ 
with numeric_airport_code 
as (select '777' as airport from dual)
select airport,
       to_char(airport,'0000') as to_char_padding,
       lpad(airport,4,'000')    as lpadding
from numeric_airport_code;


/* This gives invalid number error */

with alpha_airport_code
as (select 'LAX' as airport from dual)
select airport,
        to_char(airport,'000') as to_char_padding,
       lpad(airport,4,'000')    as lpadding
from  alpha_airport_code;    

lpad 不是问题,问题是 to_char()。在您执行的第二个查询中:

to_char('LAX', '000')

首先尝试隐式转换为数字:

to_char(to_number('LAX'), '000')

... 和 to_number('LAX') 当然得到 ORA-01722。为已经是字符串的内容调用 to_char() 是没有意义的。充其量你会得到不必要的转换,但通常 - 就像这里 - 那些是隐式的 and/or 会失败。

如果您使用lpad,它会如您所愿:

with airport_code as (
  select '777' as airport from dual
  union all select 'LAX' as airport from dual
)
select airport,
       lpad(airport, 4, '0') as lpadding
from airport_code;

AIR LPAD
--- ----
777 0777
LAX 0LAX

另请注意,第三个参数中只需要一个零。