plpgsql 编程 - JSON数组循环
背景
PostgreSQL的plpgsql编程语言和Oracle PL/SQL编程语言类似,是功能很强大的数据库编程语言。
JSON是PG支持的非结构化类型,那么如何在PLPGSQL中LOOP JSON数组呢?
https://www.postgresql.org/docs/9.6/static/plpgsql-control-structures.html#PLPGSQL-FOREACH-ARRAY
例子
例子1
postgres=# do language plpgsql $$
declare
rec jsonb;
begin
for rec in select jsonb_array_elements('[{"lat":30.27699965,"lng":120.02319424},{"lat":30.27700545,"lng":120.02321551}]')
loop
raise notice '%', rec;
end loop;
end;
$$;
NOTICE: {"lat": 30.27699965, "lng": 120.02319424}
NOTICE: {"lat": 30.27700545, "lng": 120.02321551}
DO
例子2
DO
$BODY$
DECLARE
omgjson json := '[{ "type": false }, { "type": "photo" }, {"type": "comment" }]';
i json;
BEGIN
FOR i IN SELECT * FROM json_array_elements(omgjson)
LOOP
RAISE NOTICE 'output from space %', i->>'type';
END LOOP;
END;
$BODY$ language plpgsql