如何使用串行主键进行升级

时间:2018-10-24 11:48:27

标签: postgresql plpgsql

我有一个存储过程来执行upsert。但是,冲突条件永远不会运行,传递现有ID总是会导致它创建新记录。

create or replace function upsert_email(v_id bigint, v_subject character varying)
  returns bigint
language plpgsql
as $$
declare
  v_id bigint;
begin
  insert into emails
    (id, subject)
    values (coalesce(v_id, (select nextval('serial'))), v_subject)
  on conflict(id)
    do update set (subject) = (v_subject) where emails.id = v_id
  returning id into v_id;

  return v_id;
end;
$$;

在运行select upsert_email(6958500, 'subject');(这是一条记录)时,它将始终创建一个新记录。

我已经研究过:Upsert/on conflict with serial primary key,这是最相似的问题,也是我的SQL建模的依据,但是我无法使其工作。

1 个答案:

答案 0 :(得分:0)

哇,年度白痴奖颁给了我。

我要使用一个名为v_id的参数,然后立即在声明中使用v_id覆盖它;它们应命名为2种不同的名称:

create or replace function upsert_email(v_id bigint, v_subject character varying)
  returns bigint
language plpgsql
as $$
declare
  v_return_id bigint;
begin
  insert into emails
    (id, subject)
    values (coalesce(v_id, (select nextval('serial'))), v_subject)
  on conflict(id)
    do update set (subject) = (v_subject) where emails.id = v_id
  returning id into v_return_id;

  return v_return_id;
end;
$$;