Oracle PL/SQL - 如果不满足条件则退出开始结束块

Oracle PL/SQL - Exit begin end block if condition is not met

如果不满足条件,是否可以从 begin end 块中 exit/skip?

示例:

DECLARE
    my_var BOOLEAN := TRUE;

BEGIN
    IF my_var THEN
        EXIT_BEGIN_END_HERE;  -- Exits the block but continue execution after it!
    END IF;

    -- Other stuff happens here. Won't be executed if IF above is true
    INSERT INTO asdf
    VALUES ('asdf', 'asdf');
END;

-- Other stuff happens here

如果想从最外面的街区退出,那么可以使用RETURN

DECLARE
    my_var BOOLEAN := TRUE;

BEGIN
    IF my_var THEN
        RETURN;  -- Exits the block but continue execution after it!
    END IF;

    -- Other stuff happens here. Won't be executed if IF above is true
    INSERT INTO asdf
    VALUES ('asdf', 'asdf');
END;

-- Other stuff happens here

请注意,正如@MT0 所指出的,由于它从最外层的块退出,因此 INSERT INTO asdf 波纹管将不会被执行:

DECLARE
    my_var BOOLEAN := TRUE;

BEGIN
    BEGIN
        IF my_var THEN
            RETURN;  -- Exits the outermost block but continue execution after it!
        END IF;

        INSERT INTO qwerty
        VALUES ('qwerty', 'qwerty');
    END;

    -- Other stuff happens here. Won't be executed if IF above is true
    INSERT INTO asdf
    VALUES ('asdf', 'asdf');
END;

-- Other stuff happens here

RETURN 也可以在程序内部使用。

查看类似问题:Abort a PL/SQL program

我认为以下是一个更好的示例(和解决方案),可以说明您要实现的目标。

DECLARE
    my_var BOOLEAN := TRUE;
BEGIN
    BEGIN
        IF my_var THEN
            RAISE PROGRAM_ERROR;
        END IF;
        -- Other stuff happens here. Won't be executed if IF above is true
        DBMS_OUTPUT.PUT_LINE('Not here!');
    EXCEPTION
        WHEN OTHERS THEN
            NULL;
    END;
    -- Other stuff happens here
    DBMS_OUTPUT.PUT_LINE('Continuing.');
END;

你只想退出内部的BEGIN-END,对吧?所以可以使用RAISE语句。
如果你运行上面的代码,它会显示Continuing.

使用带有标签的GOTO

BEGIN
  DECLARE
    my_var BOOLEAN := TRUE;
  BEGIN
    IF my_var THEN
      GOTO skip_insert;
    END IF;

    -- Other stuff happens here. Won't be executed if IF above is true
    DBMS_OUTPUT.PUT_LINE( 'This should be skipped' );
  END;
  <<skip_insert>>
    DBMS_OUTPUT.PUT_LINE( 'Continue from here.' );
END;
/

或使用IF ... THEN ... ELSE ... END IF:

DECLARE
  my_var BOOLEAN := TRUE;
BEGIN
  IF my_var THEN
    NULL
  ELSE
    -- Other stuff happens here. Won't be executed if IF above is true
    DBMS_OUTPUT.PUT_LINE( 'This should be skipped' );
  END IF;

  DBMS_OUTPUT.PUT_LINE( 'Continue from here.' );
END;
/

这两个输出:

Continue from here.

db<>fiddle here