JSONB 使用 for 循环记录更新 - postgres

JSONB to record update using for loop - postgres

我正在尝试从 JSONB 更新多个字段,但收到类似 cannot call_populate composite on array 的错误。

我写了下面的代码:-

do $$
<<myjsonb>>

declare

spec jsonb:=('[
                              {"schema_name":"public",
                               "table_name":"temp",
                               "nw_schema":public,
                               "nw_table": "temp",
                               "nw_col":"id"},
                               {"schema_name":"public",
                               "table_name":"temp",
                               "nw_schema":public,
                               "nw_table": "temp",
                               "nw_col":"name"}
                            ]');
                            
i record;

BEGIN

for i in SELECT * from jsonb_to_record(spec) as (schema_name text, table_name text, nw_schema text, nw_table text, nw_col text)

LOOP

update my_table set schema_name=i->>schema_name, table_name=i->>table_name where nw_schema=i->>nw_schema and nw_table=i->>nw_table and nw_col=i->>nw_col;


end loop;

end myjsonb $$;

要触摸的东西有3个

  • 你的JSON语法无效,"nw_schema":public必须加引号;
  • jsonb_to_record 应变为 jsonb_to_recordset;
  • i->>schema_name 等表达式应变为 i.schema_name

所以这里更正一下:

do $$
declare
spec jsonb:='[
              {
               "schema_name":"public",
               "table_name":"temp",
               "nw_schema":"public",
               "nw_table": "temp",
               "nw_col":"id"
              },
              {
               "schema_name":"public",
               "table_name":"temp",
               "nw_schema":"public",
               "nw_table": "temp",
               "nw_col":"name"
              }
             ]';                           
i record;
begin
 for i in select * from jsonb_to_recordset(spec) as (schema_name text, table_name text, nw_schema text, nw_table text, nw_col text)
 loop
   update my_table 
    set schema_name = i.schema_name, table_name = i.table_name
    where nw_schema = i.nw_schema and nw_table = i.nw_table and nw_col = i.nw_col;
 end loop;
end $$;