将列数据类型为 varchar2 的 table 数据插入列数据类型为数字的 table

Insert table data with column datatype varchar2 to a table with column datatype as number

在 oracle DB 中,我有一个 table TABLE1,其列数据类型定义为 VARCHAR2(50)。我有另一个 table TABLE2,其列数据类型定义为 NUMBER。 TABLE1 中存在的行数约为 23k,它们似乎都是数字。但是当我尝试插入命令时,出现以下错误。

    Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 -  "invalid number"
*Cause:    
*Action:

这显然意味着有几行不是数字。但我无法识别那些没有数字的案例。如何识别非数字行。

P.S: Oracle 数据库版本:9.2.0.8.0

是的,我知道它很古老。

为什么要将数字存储在字符串中?这是根本问题。

您可以使用 where 子句避免这些行:

insert into table2( . . .)
    select . . .
    from table1 t1
    where regexp_like(numbercol, '^[0-9]+$')

这里假定 "number" 表示 "non-negative integer"。显然,该模式可以推广到其他范围 and/or 数字格式。

您可以通过 运行 类似 select:

来识别非数字行
    select . . .
    from table1 t1
    where not regexp_like(numbercol, '^[0-9]+$')

下面是用于识别差异情况的 PL SQL 块。在我的案例中,特殊字符是双引号。出现问题的情况很少,因此打印输出是可行的。如果有更多的差异案例,那么在 table 列中捕获错误消息将会有所帮助。

declare
cursor cur is
select * from TABLE1 ;           ----- cursor to loop through cases individually
begin
for rec in cur 
loop 
begin
insert into table2 (column1)
select to_number(column1)
from table1
where
column1=rec.column1 ;
exception when others
then
Dbms_Output.Put_Line('error for '||rec.column1||' '||substr(sqlerrm,0,150)); --- error msg with discrepancy case
end;
end loop;
end;
/