简体   繁体   English

从语言 sql postgresql 中的 upsert 过程返回 ID

[英]Returning ID from the upsert procedure in language sql postgresql

I have a SQL upsert query and I want to return inserted record ID or updated record ID of the locations table.我有一个 SQL upsert 查询,我想返回位置表的插入记录 ID 或更新记录 ID。 What changes do I need in the query?我需要在查询中进行哪些更改? (Note: the name column is unique) (注: name栏是唯一的)

CREATE OR REPLACE PROCEDURE locations_upsert
(
    _name        TEXT,
    _address     TEXT,
    _postal_code TEXT,
    _country     TEXT
)
LANGUAGE SQL
AS $$
    INSERT INTO locations
    (
        name,
        address,
        postal_code,
        country
    )
    VALUES
    (
        _name,
        _address,
        _postal_code,
        _country
    )
    ON CONFLICT (name)
    DO UPDATE  
    SET 
        address = _address,
        postal_code = _postal_code,
        country = _country
$$;

Change definition of procedure to function which returns integer value and use将过程的定义更改为返回整数值并使用的函数

INSERT INTO ... RETURNING id

UPDATE ... RETURNING id

expression.表达。

Change the procedure to a function and declare either int or bigint as return type:将过程更改为函数并声明intbigint作为返回类型:

CREATE OR REPLACE FUNCTION locations_upsert(
  _name        TEXT,
  _address     TEXT,
  _postal_code TEXT,
  _country     TEXT
) RETURNS bigint
AS $$ 
  INSERT INTO locations  
    (name, address, postal_code, country) VALUES
    (_name,_address,_postal_code,_country)
   ON CONFLICT (name)
   DO UPDATE SET 
     address = _address,
     postal_code = _postal_code,
     country = _country
   RETURNING id;    
$$ LANGUAGE sql;

Alternatively you can use the table name as return data type - RETURNS locations -, which will enable you to return the whole record - RETURNING * :或者,您可以使用表名作为返回数据类型 - 返回RETURNS locations -,这将使您能够返回整个记录 - RETURNING *

CREATE OR REPLACE FUNCTION locations_upsert(
  _name        TEXT,
  _address     TEXT,
  _postal_code TEXT,
  _country     TEXT
) RETURNS locations
AS $$ 
  INSERT INTO locations  
    (name, address, postal_code, country) VALUES
    (_name,_address,_postal_code,_country)
    ON CONFLICT (name)
    DO UPDATE SET 
      address = _address,
      postal_code = _postal_code,
      country = _country
  RETURNING *;  
$$ LANGUAGE sql;

Demo: db<>fiddle演示: db<>fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM