Exit execution when error occurs PL/SQL

execution, oracle

Solution

If you create a stored procedure, you have more control and can exit whenever you like with a return statement.

So create a stored proc:

create or replace procedure myProc as
begin
   dbms_ouput.put_line('i am here');
   return;
   dbms_ouput.put_line('and not here');
end;

Then in sqlplus or developer:

exec myProc();

Problem

I would like to know, how can I exit the execution when an error occurs. In Microsoft SQL Server there is a `RETURN` clause, which does the work. But I would like to know similar functionality in Oracle. I am using Oracle Sql Developer. Here is the script I am using: First block throws error due to Unique Key Violation, even though it throws error the execution goes to next block and executes the insert statement. I want to end the execution or exit at first block of code itself. Please help me to write the code. First anonymous PL/SQL block: ``` set serveroutput on; BEGIN insert into test values(1); insert into test values(1); COMMIT; dbms_output.put_line('PRINT SOMETHING 1'); EXCEPTION WHEN OTHERS THEN if sqlcode <> 0 then dbms_output.put_line(SQLCODE || ' ' || SQLERRM); RAISE; end if; return; END; / ``` Second anonymous PL/SQL block: ``` set serveroutput on; BEGIN insert into test values(6); COMMIT; dbms_output.put_line('PRINT SOMETHING'); EXCEPTION WHEN OTHERS THEN if sqlcode <> 0 then dbms_output.put_line(SQLCODE || ' ' || SQLERRM); RAISE; end if; return; END; / ```

Original source