PL/SQL: is there an instruction to completely stop the script execution?

后端 未结 4 974
孤独总比滥情好
孤独总比滥情好 2021-02-13 16:23

I\'m trying to do some checkings on a DB schema at the beginning of a PL/SQL script.

If the checkings give unsuccessful results, I want to stop the script, to prevent th

4条回答
  •  死守一世寂寞
    2021-02-13 17:01

    The question shows a multi-statement batch script. RAISE_APPLICATION_ERROR() only exits out of a PL/SQL block (sub-program), not out of the overall script (as pointed out by Justin) so it will continue with statements that follow.

    For batch scripts, it is best to use WHENEVER SQLERROR EXIT. Yes, it is a SQLPlus directive, not standard SQL, but is fairly portable; most popular Oracle tools that support scripts support this directive, at least partially. The following example works in SQLPlus, SQL*Developer, Toad, SQLsmith and possibly others, and demonstrates the problem, if you comment the line out.

    set serveroutput on
    
    -- Without this line, things keep going
    WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK;
    
    BEGIN
      IF (1 > 0) THEN
        DBMS_OUTPUT.PUT_LINE('First thing');
        RAISE_APPLICATION_ERROR(-20000, 'Test failed'); -- not enough
      END IF;
    END;
    /
    
    -- This will execute if you remove WHEN SQLERROR.., so RAISE_APPLICATION_ERROR is not enough
    BEGIN
       DBMS_OUTPUT.PUT_LINE('Second thing - Executes anyway');
    END;
    /
    

    If you remove the WHEN SQLERROR, the script will continue and execute the 2nd block, etc. which is exactly what the question asks to avoid.

    The advantage, in this instance, of graphical tools that emulate sqlplus, is that they really stop the script and don't submit the remainder of the script to the command shell as shell commands, which is what happens if you paste scripts into SQLPlus running in a console window. SQLPlus may exit on error, but the remaining buffered commands will then be handled by the OS shell, which is a bit messy and potentially risky, if you had shell commands in the comments (which isn't unheard of). With SQLPlus, it is always best to connect, and then execute the script, or pass it in the < start > command line argument (sqlplus scott/tiger @foo.sql) to avoid this.

提交回复
热议问题