1

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

    "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';
4

2 回答 2

1

无需在 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';

演示

于 2021-01-13T11:34:43.180 回答
1

问题的症结似乎是如何从 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;
于 2021-01-13T09:59:30.360 回答