最初我试图创建一个异常来捕获一个不存在的表(-00942)。 基于Alex和Raj的反馈,我修改了代码以使用EXECUTE IMMEDIATE。 这有助于识别表格,但是当我从“雇员”那里更正了表格时。对员工'这是我的数据库中存在的表,我本来希望代码运行没有错误,就像我没有使用EXECUTE IMMEDIATE的情况一样。
使用EXECUTE IMMEDIATE时,代码是否可以毫无例外地运行,而不是生成catch all异常?
执行立即 ' SELECT last_name INTO v_name FROM employees WHERE salary = v_sal&#39 ;;
其他时间 :g_message:='发生了其他一些错误。&#39 ;;
我希望代码能够毫无例外地运行。
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
答案 0 :(得分:2)
尝试以下:
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;
/