PostgreSQL 存储过程中的增量序列

increment sequence in PostgreSQL stored procedure

如何为存储过程的每个 运行 自动增加一次序列号以及如何在 update 语句的 where 条件中使用它?

我已经为每个 运行 中的下一个值分配了一个序列号,但我无法在 where 条件下使用它。

CREATE OR REPLACE FUNCTION ops.mon_connect_easy()
   RETURNS void
   LANGUAGE plpgsql
AS $function$

declare
   _inserted_rows bigint = 0;
   sql_run bigint = 0;

   --assigning the sequence number to the variable 
   select nextval('ops.mon_connecteasy_seq') into run_seq_num; 


   -- use for selection iteration_id. this is hwere I'm getting stuck 

   update t_contract c
   set end_date = ce.correct_end_date, status='Active',
       orig_end_date =ce.correct_end_date
   from ops.t_mon_ConnectEasy ce
   where c.contract_id = ce.contract_id
     and run_seq_num = ??;

nextval() 在返回结果值之前自动推进序列。你不需要任何额外的东西。直接在查询中使用该函数即可:

update t_contract c
set    end_date = ce.correct_end_date
     , status = 'Active'
     , orig_end_date = ce.correct_end_date
from   ops.t_mon_ConnectEasy ce
where  c.contract_id = ce.contract_id
and    iteration_id = nextval('ops.mon_connecteasy_seq');

请注意,并发事务 可能会推进序列,从而在序列号中创建虚拟间隙。

而且我一直怀疑这可能不是实现您未公开目标的最佳方式。