一种选择是定义 SQL*Plus 脚本以接受字符串而不是数字,然后定义一个尝试将输入转换为数字的函数。如果你声明一个函数my_to_number
SQL> ed
Wrote file afiedt.buf
1 create or replace function my_to_number( p_str in varchar2 )
2 return number
3 is
4 l_num number;
5 begin
6 l_num := to_number( p_str );
7 return l_num;
8 exception
9 when others
10 then
11 raise_application_error( -20001, p_str || ' is not a number' );
12* end;
SQL> /
Function created.
然后您的 SQL*Plus 脚本可能看起来像这样。如果用户输入了一个有效的数字,脚本就会按预期工作。如果不是,则会引发函数中定义的自定义错误。
SQL> declare
2 v_n number(3) := my_to_number( '&sv_n' );
3 begin
4 dbms_output.put_line( 'The number is ' || v_n );
5 end;
6 /
Enter value for sv_n: 123
old 2: v_n number(3) := my_to_number( '&sv_n' );
new 2: v_n number(3) := my_to_number( '123' );
The number is 123
PL/SQL procedure successfully completed.
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_n number(3) := my_to_number( '&sv_n' );
3 begin
4 dbms_output.put_line( 'The number is ' || v_n );
5* end;
SQL> /
Enter value for sv_n: abc
old 2: v_n number(3) := my_to_number( '&sv_n' );
new 2: v_n number(3) := my_to_number( 'abc' );
declare
*
ERROR at line 1:
ORA-20001: abc is not a number
ORA-06512: at "SCOTT.MY_TO_NUMBER", line 11
ORA-06512: at line 2