mak*_*aks 4 sql oracle plsql ora-00942
我有这样的代码:
DECLARE
e_not_exist EXCEPTION;
PRAGMA EXCEPTION_INIT(e_not_exist, -942);
car_name VARCHAR2(20);
BEGIN
select name_of_factory into car_name from car where car_id = 1;
dbms_output.put_line(car_name);
EXCEPTION
when e_not_exist then
dbms_output.put_line('Table or view does not exist');
when OTHERS then
dbms_output.put_line(to_char(SQLCODE));
END;
Run Code Online (Sandbox Code Playgroud)
实际上,我的表名是CARS但不是CAR.但oracle不处理此异常并给我一个错误ORA-00942:表或视图不存在.我该如何处理这个异常?
你不能用静态SQL做到这一点.编译代码时,错误即将发生,而不是执行.试试这个:
execute immediate 'select name_of_factory from car where car_id = 1'
into car_name ;
Run Code Online (Sandbox Code Playgroud)
ORA-00942错误通常是编译时错误.Oracle必须在编译时解析表的名称.异常处理程序将在运行时捕获错误,而不是编译时.
如果您使用了动态SQL,则可以将名称的解析推迟到运行时,此时您可以捕获异常,即
SQL> ed
Wrote file afiedt.buf
1 declare
2 no_such_table exception;
3 pragma exception_init( no_such_table, -942 );
4 l_cnt integer;
5 begin
6 execute immediate 'select count(*) from emps' into l_cnt;
7 exception
8 when no_such_table
9 then
10 dbms_output.put_line( 'No such table' );
11* end;
SQL> /
No such table
PL/SQL procedure successfully completed.
Run Code Online (Sandbox Code Playgroud)
但是,编写存储过程通常不是一种明智的方法.您的程序应该知道实际存在哪些表,并且应该在开发期间识别和解决语法错误,而不是在运行时.