postgresql Postgres在用户定义函数中调用内置函数时出错

7rfyedvj  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(164)

我有一个jsonb数组,看起来像这样

[{"name": "ARM", "object_key": "GOB-1211"}, {"name": "foo", "object_key": "GOB-1234"}]

字符串
我想写一个postgresql函数来获取{GOB-1211, GOB-1234}

CREATE OR REPLACE FUNCTION get_object_keys(jsonb_array jsonb)
RETURNS text[] AS $$
DECLARE
  object_keys text[];
BEGIN
  FOR item IN jsonb_array_elements(jsonb_array) LOOP
    object_keys := array_append(object_keys, item->>'object_key');
  END LOOP;
  RETURN object_keys;
END;
$$ LANGUAGE plpgsql;


但这会抛出一个错误

ERROR:  syntax error at or near "jsonb_array_elements"
LINE 6:   FOR item IN jsonb_array_elements(jsonb_array) LOOP


有人能指出我做错了什么吗?或者也许有一个更好的结构,我可以在连接或where子句中使用?

a14dhokn

a14dhokn1#

问题是for循环希望你在遍历变量时声明它--在使用它之前声明item

CREATE OR REPLACE FUNCTION get_object_keys(jsonb_array jsonb)
RETURNS text[] AS $$
DECLARE
  object_keys text[] := '{}';
  item jsonb;  -- HERE
BEGIN
  FOR item IN SELECT * FROM jsonb_array_elements(jsonb_array) LOOP
    object_keys := array_append(object_keys, item->>'object_key');
  END LOOP;
  RETURN object_keys;
END;
$$ LANGUAGE plpgsql;

字符串

相关问题