如何知道查询是否在PLSQL中成功执行

时间:2016-03-24 11:30:38

标签: oracle function plsql

在我的函数中,我通过Select ..

进行INSERT
list3 = [x + y for x, y in zip(list1, list2)]

我如何知道我的INSERT已通过并且所有行都已成功录制?

如果一切正常,我的fontion应该返回1,否则返回0。

1 个答案:

答案 0 :(得分:3)

如果我是你,我不会将其编码为函数,我会将其作为一个过程来执行,如下所示:

create or replace procedure insert_data
as
begin
  insert into t_items (cd_1, cd_2, cd_3) 
  select cd_1, cd_2, cd_3
  from   rec_items;

  commit;
end;
/

如果我需要知道插入了多少行,我会添加一个out参数,如下所示:

create or replace procedure insert_data (p_num_rows_inserted out number)
as
begin
  insert into t_items (cd_1, cd_2, cd_3) 
  select cd_1, cd_2, cd_3
  from   rec_items;

  p_num_rows_inserted := sql%rowcount;

  commit;
end;
/

要确保在过程完成后回滚事务,可以添加一个exception子句来添加回滚。

以下是一个演示如何工作的示例:

create table t1 (col1 number, col2 number, col3 number, constraint t1_uq unique (col1, col2) using index);

begin
  insert into t1 (col1, col2, col3)
  select 1, 1, 1 from dual union all
  select 1, 2, 3 from dual;

  commit;

exception
  when dup_val_on_index then
    rollback;
    raise;
end;
/

 PL/SQL procedure successfully completed.

begin
  insert into t1 (col1, col2, col3)
  select 2, 2, 1 from dual union all
  select 2, 2, 3 from dual;

  commit;

exception
  when dup_val_on_index then
    rollback;
    raise;
end;
/

Error at line 10
ORA-00001: unique constraint (SCHEMA.T1_UQ) violated
ORA-06512: at line 11

N.B。我在上面的示例代码中留下了COMMIT / ROLLBACK,但正如Alex在下面的评论中所说的那样,通常你会留下调用过程的事务处理。

我强烈建议您阅读PL / SQL中的异常处理:http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/errors.htm#LNPLS00701