PostgreSQL plpgsql函数问题

zzoitvuj  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(179)

我在Debian 12.2上运行的PostgreSQL 16.1数据库中有一个函数:

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函数中找到了类似的查询,它们都能正常工作。

6tdlim6h

6tdlim6h1#

看起来你需要这个:返回id到id_瓦尔;

CREATE OR REPLACE FUNCTION ref.lookup_xxx(
    in_code CHARACTER VARYING,
    in_description CHARACTER VARYING)
    RETURNS INTEGER
    LANGUAGE 'plpgsql'
    COST 10
    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 
            INTO id_val; -- <-- this one
    END IF;
    RETURN id_val; -- return id of new or existing row
EXCEPTION -- Why? You will be hiding the real error
    WHEN OTHERS THEN
        RAISE EXCEPTION 'lookup_xxx error code, desc = %, %', in_code, in_description;
END;
$BODY$;

字符串

相关问题