将 SETOF 转换为字符串

Nul*_*lik 4 postgresql plpgsql

该函数json_object_keys(json)返回一个setof text. 如何将其转换setof text为所有元素均以 分隔的字符串','?我必须使用该函数array_to_string(),但它接受一个数组,而不是一个setof. 那么如何将 a 转换setof为数组。例如:

DECLARE 
    custom_fields   json;
BEGIN
    custom_fields:='{"name":"John Smith","age":23}';
    keys:=array_to_string(json_object_keys(custom_fields),','::text);
END
Run Code Online (Sandbox Code Playgroud)

上面的方法不起作用,我得到:

ERROR:  function array_to_string(text, text) does not exist
Run Code Online (Sandbox Code Playgroud)

那么,如何将 a 转换SETOF为 an ARRAY

Pat*_*ick 6

该函数json_object_keys()是一个返回集合的函数,因此您应该将其用作行源(= 在子句中FROM)。使用该string_agg()函数,您将得到结果:

SELECT string_agg(cf, ',') INTO keys
FROM json_object_keys(custom_fields) jok(cf);
Run Code Online (Sandbox Code Playgroud)

请注意,由于该INTO子句,这仅适用于 PL/pgSQL 函数。