我的PostgreSQL 16.1数据库中有一个运行在Debian 12.2上的函数:
CREATE OR REPLACE FUNCTION ref.lookup_xxx(
in_code character varying,
in_description character varying)
RETURNS integer
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
declare id_val integer;
begin
if in_code is null then -- nothing to do
return null;
end if;
-- check if code is already present in the table:
id_val = (select min(id) from ref.xxx where code = in_code);
if id_val is null then -- insert new code, desc into reference table:
insert into ref.xxx (code, description) values (in_code, in_description) returning id_val;
end if;
return id_val; -- return id of new or existing row
exception
when others then
raise exception 'lookup_xxx error code, desc = %, %', in_code, in_description;
end;
$BODY$;
它返回一个错误:
ERROR: lookup_xxx error code, desc = 966501, <NULL>
CONTEXT: PL/pgSQL function ref.lookup_xxx(character varying,character varying) line 15 at RAISE
SQL state: P0001
如果我运行下面的特殊查询,它会成功:
insert into ref.xxx (code, description) values ('966501', null);
我无法运行此即席查询-它可能无法运行:
do $$
declare x integer;
begin
insert into ref.xxx (code, description) values ('966501', null) returning x;
raise notice 'x is %', x;
end;
$$
我正在寻找任何建议来纠正这个功能-我已经判断了Postgres文档,但没有找到任何有用的东西.单步执行调试器中的函数会显示它在INSERT语句中失败.我在其他plpgsql函数中也有类似的查询,它们工作正常.