Reputation: 153
Initially i was trying to create an exception to catch a table that didnt exist (-00942). Based on the feedback from both Alex and Raj, i amended the code to use EXECUTE IMMEDIATE. This worked in identifying the table however when i corrected the table from 'employe' to 'employees' which is the table that existed in my DB, I would have expected the code to run without error as was the case when i didnt use EXECUTE IMMEDIATE.
Instead of generating the catch all exception, is it possible for the code to run through without exception when using EXECUTE IMMEDIATE?
EXECUTE IMMEDIATE 'SELECT last_name INTO v_name FROM employees WHERE salary = v_sal';
WHEN OTHERS THEN :g_message := 'Some other error occurred.';
I was hoping for the code to run through without exception.
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
Upvotes: 1
Views: 10338
Reputation: 9886
try below:
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;
/
Upvotes: 6