事务内的过程调用

时间:2018-12-27 19:37:07

标签: transactions procedure postgresql-11

我有存储过程,该存储过程由表上的多个更新查询组成。它使用来自其他几个表的数据。因此,每个查询都在过程内提交,以释放查询中使用的表上的锁。 在某些时候,我需要使用一些测试数据来创建临时表。临时表名称与持久化表到影子持久化表的名称相同。而且我想使用“提交时丢失”,但是,如果我开始进行事务处理时,临时表的创建很顺利,但是在调用my_very_big_procedure()时,我收到了“事务处理错误”错误,并指向过程内的第一次提交。 >

为了使代码简短,我将使用一些虚拟示例:

create or replace procedure my_very_big_procedure() as 
$$ 
begin
   insert into maintable select from table1, some_table, some_other_table;
   commit;

   update maintable using table1;
   commit;

   update maintable using table2;
   commit;
end;
$$ language pgplsql

begin
    create temp table maintable (like public.maintable) on commit drop;
    create temp table table1 (like public.table1) on commit drop -- works fine
    insert into table1 values %s  -- also works fine
    create temp table table2 (like public.table2) on commit drop -- again it's OK
    insert into table2 values %s -- and data's got inserted
    call my_very_big_procedure() -- and here comes an ERROR :(
    commit
end

那么如何在事务块中使用过程调用?

UPD: 好吧,似乎我必须在会话中创建临时表并将其手动删除。然后必须使用表oid来确保临时表存在。 我认为是这样的:

select case when 'public.teblename'::regclass::oid = 'tablename'::regclass::oid then 'temp table exitsts' else 'no temp table - no drop' end.

1 个答案:

答案 0 :(得分:0)

  

那么如何在事务块中使用过程调用?

您不能这样做,如doc page for CALL所述:

  

如果在事务块中执行CALL,则调用过程   无法执行事务控制语句。

问题中显示的语句序列无论如何都不起作用,因为该过程想要更新一个临时表,而该表将被该更新正上方的提交删除。