【问题标题】:How to use JSONB_SET for updating JSONB Column in PostgreSQL Procedure如何使用 JSONB_SET 更新 PostgreSQL 程序中的 JSONB 列
【发布时间】:2022-01-24 20:52:48
【问题描述】:

我正在使用存储过程来更新表中的 JSONB 列,但它似乎不起作用。任何帮助将非常感激。非常感谢。

我的桌子是:

CREATE TABLE mn_customer (
cust_id int,
f_name varchar(20),
l_name varchar(20),
json_payload jsonb);

我的 SPROC 是:

create or replace procedure update_mn_customer
(
update_cust_id int DEFAULT null,
update_json_payload jsonb DEFAULT null
)
language plpgsql as
$proc$
begin
    
    update mn_customer
        set json_payload = jsonb_set(json_payload, update_json_payload)
    where  cust_id = update_cust_id;
    commit;

end
$proc$;

我对执行更新的过程的调用是:

call update_mn_customer(
1998, to_jsonb('{"jsonpayload-fld1": "John Davis", "jsonpayload-fld2": "Lenny Pascoe","jsonpayload-fld3": "Undefined"}'::text)
);

我不断收到错误:

ERROR:  function jsonb_set(jsonb, jsonb) does not exist
LINE 2:         set json_payload = jsonb_set(json_payload, update_js...
                                   ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
QUERY:  update mn_customer
        set json_payload = jsonb_set(json_payload, update_json_payload)
    where  cust_id = update_cust_id
CONTEXT:  PL/pgSQL function update_mn_customer(integer,jsonb) line 8 at SQL statement

【问题讨论】:

    标签: postgresql stored-procedures jsonb


    【解决方案1】:

    当您只想用新的 jsonb 值替换由路径标识的 jsonb 数据的一部分时,您可以使用 jsonb_set。在您的情况下,update_json_payload 似乎是 json_payload 列的新值,因此您只需更新它:

    update mn_customer
       set json_payload = update_json_payload
     where  cust_id = update_cust_id ;
    

    那么你就不需要在 plpgsql 过程中提交了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 2015-07-16
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2016-07-14
      • 2021-12-31
      相关资源
      最近更新 更多