首页 > 解决方案 > 调用函数后获取诊断

问题描述

我有一个我正在调用的 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?

标签: postgresql

解决方案


将函数声明为RETURNS bigint而不是RETURNS void并返回插入的行数,如GET DIAGNOSTICS在函数内部找到的那样。


推荐阅读