postgresql - 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 = ??;
解决方案
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');
请注意,并发事务也可能会推进序列,从而在序列号中创建虚拟间隙。
我有一个挥之不去的怀疑,这可能不是实现你未公开目标的最佳方式。
推荐阅读
- python - 致命的 Python 错误:Py_Initialize:无法加载文件系统编解码器和 ModuleNotFoundError
- javascript - 是否可以在 Firestore 中读取文档然后将其锁定,以便其他人无法读取它?
- php - 获取使用短代码的所有页面/帖子 ID
- css - 我如何将 CSS 样式表链接到反应类
- python - 如何在 Flask 中分别渲染两个 html 文件?
- perl - 在 Perl 中使用 MySQL 选择多行
- azure - 如何在单个应用服务上部署 aspnet core web api 和 aspnet webapi
- python - 如何从 Kaggle Football 数据中找到具有多个匹配项的 id
- java - 如何正确使用 Scanner 打印输出流
- swift - 如何使用 MDL 对边界框进行命中测试