PL/SQL 使用 EXECUTE IMMEDIATE 时块不会执行到结束

PL/SQL block does not execute to end when using EXECUTE IMMEDIATE

我想达到什么目的?

我卡在哪里了?

以下两段代码演示了该问题。第一个块按预期执行。第二块不完整执行。有编译错误的过程 p3 不是问题所在。我的问题是没有创建过程 p4。

-- creates procedure p1 and p2
BEGIN

  EXECUTE IMMEDIATE 'create or replace procedure p1 is begin null; end;';
  EXECUTE IMMEDIATE 'create or replace procedure p2 is begin null; end;';

  dbms_output.put_line('Done!');

END;
-- creates only procedure p3 and exits with no error
BEGIN

  EXECUTE IMMEDIATE 'create or replace procedure p3 is begin null end;'; -- compilation error (missing semicolon)
  EXECUTE IMMEDIATE 'create or replace procedure p4 is begin null; end;';

  dbms_output.put_line('Done!');

END;

是的,出现异常。你看,"Success with compilation error" 一个例外。您可以通过定义异常变量并使用 EXCEPTION_INIT:

对其进行初始化来捕获它
eCompilation_error EXCEPTION;
PRAGMA EXCEPTION_INIT(eCompilation_error, -24344);

db<>fiddle here

要更详细地了解 Bob 的回答:如果您想忽略编译异常,您需要将每个 execute immediate 包装在一个匿名块中。

BEGIN

  BEGIN
    EXECUTE IMMEDIATE 'create or replace procedure p3 is begin null end;'; -- compilation error (missing semicolon)
  EXCEPTION WHEN OTHERS THEN null; -- ignore exceptions
  END;

  BEGIN
    EXECUTE IMMEDIATE 'create or replace procedure p4 is begin null; end;';
  EXCEPTION WHEN OTHERS THEN null; -- ignore exceptions
  END;

  dbms_output.put_line('Done!');

END;