Oracle 错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4208451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle errors handling
提问by maks
I have such code:
我有这样的代码:
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;
Actually, my table name is CARS but not CAR. But oracle doesn't handle this exception and gives me an error ORA-00942: Table or view doesn't exist. How can I handle this exception?
实际上,我的表名是 CARS 但不是 CAR。但是 oracle 不处理这个异常并给我一个错误 ORA-00942:表或视图不存在。我该如何处理这个异常?
回答by Justin Cave
An ORA-00942 error is generally going to be a compile time error. Oracle has to resolve the name(s) of the tables at compile time. Exception handlers will trap errors at runtime, not compile time.
ORA-00942 错误通常是编译时错误。Oracle 必须在编译时解析表的名称。异常处理程序将在运行时捕获错误,而不是编译时。
If you used dynamic SQL, you can postpone the resolution of names to runtime at which point you can catch the exception, i.e.
如果您使用动态 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.
But that is not a sensible way, in general, to write stored procedures. Your procedures should know what tables actually exist and syntax errors should be identified and resolved during development, not at runtime.
但这通常不是一种明智的方式来编写存储过程。您的过程应该知道哪些表实际存在,并且应该在开发过程中而不是在运行时识别和解决语法错误。
回答by Dan
You can't do that with static SQL. The error is coming when the code is being compiled, not executed. Try this instead:
你不能用静态 SQL 做到这一点。代码正在编译而不是执行时会出现错误。试试这个:
execute immediate 'select name_of_factory from car where car_id = 1'
into car_name ;