Mar*_*inJ 5 arrays format postgresql
我正在寻找一种使用数组格式化字符串的简单方法,如下所示:
select format_using_array('Hello %s and %s', ARRAY['Jane', 'Joe']);
format_using_array
--------------------
Hello Jane and Joe
(1 row)
Run Code Online (Sandbox Code Playgroud)
有一个格式函数,但它需要显式参数,我不知道数组中有多少项.我提出了这样的功能:
CREATE FUNCTION format_using_array(fmt text, arr anyarray) RETURNS text
LANGUAGE plpgsql
AS $$
declare
t text;
length integer;
begin
length := array_length(arr, 1);
t := fmt;
for i in 1..length loop
t := regexp_replace(t, '%s', arr[i]);
end loop;
return t;
end
$$;
Run Code Online (Sandbox Code Playgroud)
但也许有一种我不知道的简单方法,这是我使用pgsql的第一天.
Pav*_*ule 13
您可以使用格式函数和VARIADIC关键字.它需要9.3,其中修复了可变函数实现中的bug
postgres=# SELECT format('%s %s', 'first', 'second');
format
--------------
first second
(1 row)
postgres=# SELECT format('%s %s', ARRAY['first', 'second']);
ERROR: too few arguments for format
postgres=# SELECT format('%s %s', VARIADIC ARRAY['first', 'second']);
format
--------------
first second
(1 row)
Run Code Online (Sandbox Code Playgroud)