具有 JSON 个参数的函数 postgreSQL

Function postgreSQL with JSON parameters

我必须创建一个接受这种类型对象的函数:

    "users":"John",
    "Level":"1",
    "list":[
      {"id":"1", "price1":"100.50", "price2":"90.50"},
      {"id":"2", "price1":"100.60", "price2":"80.50"},
      {"id":"2", "price1":"105.50", "price2":"700.50"}
    ]}

供参考 JSON 没有义务,但对我来说这是最简单的事情。但也许创建 POSTGRES 类型可以工作。

如果我使用 JSON 或 PostGres 类型,那么如何处理对象。

    CREATE OR REPLACE FUNCTION MYFUNCTION(myobject JSON ? CREATE TYPE ? )
      RETURNS TABLE (
        "OK" BOOLEAN,
        "NB" VARCHAR
      )
    
    AS $$
    
    DECLARE
    
    
    BEGIN
    
    -- I would like to get for each object in the list the price1 and price2 to 
       compare them. 
    
    END; $$
    
    LANGUAGE 'plpgsql';

问题的关键似乎是如何从 json 对象中提取值。这是一种方式:

select * from json_to_recordset('{
     "users":"John",
     "Level":"1",
     "list":[
      {"id":"1", "price1":"100.50", "price2":"90.50"},
      {"id":"2", "price1":"100.60", "price2":"80.50"},
      {"id":"2", "price1":"105.50", "price2":"700.50"}
    ]}'::json->'list') as foo(id int, price1 numeric, price2 numeric);

使用 json 变量而不是文字字符串:

select * from json_to_recordset(jsonvariable->'list') as foo(id int, price1 numeric, price2 numeric)

注意。您提供的 json 对象不合法。缺少一些逗号。我还建议您使用 jsonb 而不是 json.

已编辑:这是关于如何在 plpgsql 函数中使用它的框架:

create or replace function func(jsonvariable json) returns table (ok boolean, nb text) as 
$BODY$
declare 
    r record;
begin
    for r in (select * from json_to_recordset(jsonvariable->'list') as foo(id int, price1 numeric, price2 numeric)) loop
        --- DO THINGS
        ok:=(r.price1>r.price2);
        nb:='this is text returned';
        return next;
    end loop;
end;
$BODY$
language plpgsql;

无需使用循环处理 JSON ARRAY。您可以使用 JSONB_ARRAY_ELEMENTSJSONB_TO_RECORDSET 来满足您的要求,如下所示:

使用JSONB_TO_RECORDSET

CREATE OR REPLACE FUNCTION MYFUNCTION(myobject JSONB)
      RETURNS TABLE (ok BOOLEAN, nb VARCHAR)
      AS 
      $$
      BEGIN
       return query
        select 
           price1>price2,     -- you can change the condition here
           id::varchar        -- you can change the value as per your requirement
        from jsonb_to_recordset(myobject ->'list') as x(id int, price1 numeric, price2 numeric);
    
    END; 
$$
    
LANGUAGE 'plpgsql';

使用JSONB_ARRAY_ELEMENTS

CREATE OR REPLACE FUNCTION MYFUNCTION1(myobject JSONB)
      RETURNS TABLE (ok BOOLEAN, nb VARCHAR)
      AS 
      $$
      BEGIN
       return query
        select 
           (x->>'price1')::numeric > (x->>'price2')::numeric,     -- you can change the condition here
           (x->>'id')::varchar                                    -- you can change the value as per your requirement
        from jsonb_array_elements(myobject ->'list') as x;
    
    END; 
$$
    
LANGUAGE 'plpgsql';

DEMO