在存储过程中commit和rollback
最近更新时间: 2024-10-17 17:10:00
postgres=# create table t_autonomous_transaction( f1 int,f2 int);
CREATE TABLE
postgres=# create or replace procedure t_autonomous_transaction_isnert() as
$$
begin
insert into t_autonomous_transaction values(1,1);
insert into t_autonomous_transaction values(2,2);
commit;
insert into t_autonomous_transaction values(3,3);
rollback;
end;
$$
language plpgsql;
CREATE PROCEDURE
postgres=# call t_autonomous_transaction_isnert();
CALL
postgres=# select * from t_autonomous_transaction ;
f1 | f2
----+----
1 | 1
2 | 2
(2 rows)
#在同一个存储过程中,记录1,2 commit,记录3 rollback
#另外,如果存储过程中使用了自冶事务,则这个存储过程就不能放在一个事务中调用,如下
postgres=# begin;
BEGIN
postgres=# call t_autonomous_transaction_isnert();
ERROR: invalid transaction termination
CONTEXT: PL/pgSQL function t_autonomous_transaction_isnert() line 5 at COMMIT
postgres=# rollback;
#用例,每插入10条记录提交一次
postgres=# create or replace procedure t_autonomous_transaction_isnert() as
$$
begin
for i in 1 .. 100 loop
insert into t_autonomous_transaction values(i,i);
if mod(i,10)=0 then
commit;
end if;
insert into t_autonomous_transaction values(i,i);
end loop;
end;
$$
language plpgsql;