postgresql - 调用函数后获取诊断
问题描述
我有一个我正在调用的 plpgsql 过程,它具有相当简单的逻辑。
在该过程中,我想不断调用一个函数,直到该函数不再插入任何行。该函数从另一个表迭代地向一个表添加行,直到另一个表没有更多行要添加。我正在考虑使用GET DIAGNOSTICS
这个。
我调用的函数有时有两个不同的插入,取决于某些子句。大致遵循这样的逻辑:
create or replace function func_name(_id bigint) returns void as
$$
declare
q text;
begin
select format($q$
with insert_data as (
--removing logic
)
insert into table(col_1,col_2,col_3,col_4,col_5)
select
--removing logic
from insert_data i
on conflict on constraint ssm_unique do nothing;
$q$,
--removing these for now
) into q;
execute q;
if (certain_threshold > 0) then
--do another insert into a different table
end if;
我知道我可以通过在调用执行查询命令之后添加类似的内容来为每个步骤添加 row_count,get diagnostics inserted = row_count;
但是有没有办法从过程中获取 row_count?理论上,我可以在两次插入后获取 row_count,然后添加它们并返回值,但我认为可能有更好的方法来做到这一点。
该过程如下所示:
create or replace procedure proc_1(_id bigint) as
$$
declare
returned bigint;
begin
loop
perform func_name(_id);
get diagnostics returned = row_count;
exit when returned = 0;
end loop;
end;
$$ language plpgsql;
所以本质上,如果两个插入都没有实际添加任何行,那么返回值 0 作为 row_count?
解决方案
将函数声明为RETURNS bigint
而不是RETURNS void
并返回插入的行数,如GET DIAGNOSTICS
在函数内部找到的那样。
推荐阅读
- python - 在 Holoview 条形图中具有 2 个关键尺寸的尺寸标签(KeyError:未找到尺寸)
- webpack - 带有@types/webpack-env 1.16.0 的 Webpack 5.10.0 - HMR 错误“类型 'NodeModule' 上不存在属性 'hot'”
- c# - 接口成员中定义的可空引用类型在实现中不需要可空的原因是什么?
- qt - 如何编译 qtimageformats?
- javascript - 制表符 getElement 不是函数
- google-apps-script - Google Apps 脚本 -- 创建过滤器超时
- sql - 如何从 SQL 中的查询结果中删除 NULL 值
- python - Python xrange 和生成器之间的区别?
- python - 使用 toPandas() 和 databricks 连接时遇到“java.lang.OutOfMemoryError: Java heap space”
- javascript - React js无法读取API调用属性未定义的属性'id'