首页 > 解决方案 > PostgreSQL存储过程中的递增序列

问题描述

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

我已经为每次运行中的下一个值分配了一个序列号,但我无法在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 = ??;

标签: postgresqlsequenceplpgsql

解决方案


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');

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

我有一个挥之不去的怀疑,这可能不是实现你未公开目标的最佳方式。


推荐阅读