20

在一个程序中,我想做逻辑单元1,不管它是否失败,执行逻辑单元2

这似乎是一个典型的 try-catch 场景。但我怎么能在 pl/sql 中做到这一点?

create or replace
PACKAGE BUILD_PKG
AS
PROCEDURE reset_seq_and_truncate_tbl(
    p_seq_name   IN VARCHAR2,
    p_table_name IN VARCHAR2 );
END BUILD_PKG;
/
create or replace
PACKAGE BODY  BUILD_PKG
AS
BEGIN
PROCEDURE reset_seq_and_truncate_tbl(
    p_seq_name   IN VARCHAR2,
    p_table_name IN VARCHAR2 )
 IS
   l_val NUMBER;
 BEGIN
   BEGIN
     EXECUTE immediate 'truncate table ' || p_table_name;
   EXCEPTION 
        WHEN OTHERS 
        THEN dbms_output.put_line(SQLCODE);
   END;

   BEGIN
     EXECUTE immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
   EXCEPTION 
        WHEN OTHERS 
        THEN dbms_output.put_line(SQLCODE);
   END; 
 END reset_seq_and_truncate_tbl;

END BUILD_PKG;

如您所见,第二个异常块导致了问题。

4

2 回答 2

19

将第二个包含EXCEPTIONBEGIN..END块中。试试这个方法

PROCEDURE reset_seq_and_truncate_tbl(
    p_seq_name   IN VARCHAR2,
    p_table_name IN VARCHAR2 )
 IS
   l_val NUMBER;
 BEGIN
   EXECUTE immediate 'truncate table ' || p_table_name;
 EXCEPTION 
      WHEN OTHERS 
      THEN
      BEGIN
        dbms_output.put_line(SQLCODE);
        EXECUTE immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
       --this would cause compilation error
       EXCEPTION 
            WHEN OTHERS 
            THEN dbms_output.put_line(SQLCODE);
     END; 
 END reset_seq_and_truncate_tbl;

更新以回应评论

PROCEDURE reset_seq_and_truncate_tbl(
    p_seq_name   IN VARCHAR2,
    p_table_name IN VARCHAR2 )
 IS
   l_val NUMBER;
 BEGIN
   BEGIN
     EXECUTE immediate 'truncate table ' || p_table_name;
   EXCEPTION 
        WHEN OTHERS 
        THEN dbms_output.put_line(SQLCODE);
   END;

   BEGIN
     EXECUTE immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
   EXCEPTION 
        WHEN OTHERS 
        THEN dbms_output.put_line(SQLCODE);
   END; 
 END reset_seq_and_truncate_tbl;
于 2012-09-21T09:15:18.133 回答
1

程序 ( ) 是

开始

-- 逻辑单元 1 BEGIN ... 其他情况下除外 ... END;

-- 逻辑单元 2 BEGIN ... 其他情况下除外 ... END;

-- Final Exception Block EXCEPTION WHEN OTHERS THEN ...

结尾 ;

于 2013-01-09T11:19:56.897 回答