Friday, September 27, 2013

How to handle the Exception in FORALL statement 11G Feature




The below mentioned way of handling the exceptions for FORALL statement is available in Oracle 11g DB version.

-- Temporary table for this example:
CREATE TABLE emp_temp AS SELECT * FROM employees;

DECLARE
   TYPE empid_tab IS TABLE OF employees.employee_id%TYPE;

   emp_sr                                            empid_tab;
-- Exception handler for ORA-24381:
   ERRORS                                            NUMBER;
   dml_errors                                        EXCEPTION;
   PRAGMA EXCEPTION_INIT (dml_errors, -24381);
BEGIN
   SELECT employee_id
   BULK COLLECT INTO emp_sr
     FROM emp_temp
    WHERE hire_date < '30-DEC-94';

-- Add '_SR' to job_id of most senior employees:
   FORALL i IN emp_sr.FIRST .. emp_sr.LAST SAVE EXCEPTIONS
      UPDATE emp_temp
      SET job_id = job_id || '_SR'
      WHERE  emp_sr (i) = emp_temp.employee_id;
-- If errors occurred during FORALL SAVE EXCEPTIONS,
-- a single exception is raised when the statement completes.
EXCEPTION
-- Figure out what failed and why
   WHEN dml_errors
   THEN
      ERRORS                                                   := SQL%BULK_EXCEPTIONS.COUNT;
      DBMS_OUTPUT.put_line ('Number of statements that failed: ' || ERRORS);

      FOR i IN 1 .. ERRORS
      LOOP
         DBMS_OUTPUT.put_line ('Error #' || i || ' occurred during ' || 'iteration #'
                               || SQL%BULK_EXCEPTIONS (i).ERROR_INDEX
                              );
         DBMS_OUTPUT.put_line ('Error message is ' || SQLERRM (-SQL%BULK_EXCEPTIONS (i).ERROR_CODE));
      END LOOP;
END;
/

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.