我正在寻找一种使用数组格式化字符串的简单方法,如下所示:
select format_using_array('Hello %s and %s', ARRAY['Jane', 'Joe']);
format_using_array
--------------------
Hello Jane and Joe
(1 row)
有一个格式函数,但它需要显式参数,而且我不知道数组中有多少项。我想出了一个这样的函数:
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
$$;
但也许有一种我不知道的更简单的方法,这是我第一天使用 pgsql。
您可以使用格式函数和 VARIADIC 关键字。需要9.3,其中修复了错误 http://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=760f3c043ad4ee622b596d005ec31bb5e0322c4a在可变参数函数实现中
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)