Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit execution when error occurs PL/SQL

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;
/ 
like image 871
user3311382 Avatar asked Jan 11 '23 05:01

user3311382


2 Answers

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();
like image 198
Brian McGinity Avatar answered Jan 19 '23 00:01

Brian McGinity


You can nest the blocks into a single 'program unit'. In this way an exception in the first block will stop the whole program unit from executing, rather than just being limited in scope to the first block.

set serveroutput on;

BEGIN
  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;
  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;
END;
/ 
like image 25
Gary Myers Avatar answered Jan 19 '23 00:01

Gary Myers