1

最初我试图创建一个异常来捕获一个不存在的表(-00942)。根据 Alex 和 Raj 的反馈,我修改了代码以使用 EXECUTE IMMEDIATE。这有助于识别表,但是当我将表从“员工”更正为“员工”时,这是我的数据库中存在的表,我希望代码能够正常运行,就像我没有使用 EXECUTE IMMEDIATE 时一样.

在使用 EXECUTE IMMEDIATE 时,代码是否可以无异常地运行,而不是生成捕获所有异常?

EXECUTE IMMEDIATE 'SELECT last_name INTO v_name FROM employees WHERE Salary = v_sal';

WHEN OTHERS THEN :g_message := '发生了其他错误。';

我希望代码能够毫无例外地运行。

VARIABLE g_message VARCHAR2(250)

DEFINE p_sal = 12000

DECLARE 
   v_name employees.last_name%TYPE;
   v_sal employees.salary%TYPE := &p_sal;

   table_does_not_exist exception;  
   PRAGMA EXCEPTION_INIT(table_does_not_exist, -942);

BEGIN

   EXECUTE IMMEDIATE
   'SELECT last_name INTO v_name FROM employees WHERE salary = v_sal';

   DBMS_OUTPUT.put_line(v_name);


 EXCEPTION 

   WHEN table_does_not_exist then 
   :g_message := 'table dose not exist';  


   WHEN NO_DATA_FOUND THEN 
   :g_message := 'No employee with a salary of '||TO_CHAR(v_sal);  

   WHEN OTHERS THEN
   :g_message := 'Some other error occurred.';
 END;
 /
 PRINT g_message
4

1 回答 1

5

试试下面:

DECLARE 
   v_name employee.emp_name%TYPE;
   v_sal employee.emp_sal%TYPE := 12000;

   table_does_not_exist exception;  
   PRAGMA EXCEPTION_INIT(table_does_not_exist, -942);

BEGIN

execute immediate
   'SELECT emp_name        
   FROM employee_l
   WHERE emp_sal = v_sal' INTO v_name;

   DBMS_OUTPUT.put_line(v_name);


 EXCEPTION 

   WHEN table_does_not_exist then 
   dbms_output.put_line( 'table dose not exist');  


   WHEN NO_DATA_FOUND THEN 
   dbms_output.put_line(  'No employee with a salary of '||TO_CHAR(v_sal));  

   WHEN OTHERS THEN
   dbms_output.put_line( 'Some other error occurred.');
 END;
 /
于 2016-07-27T10:15:57.963 回答