使用数组的Postgres格式字符串 [英] Postgres format string using array
本文介绍了使用数组的Postgres格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种使用数组格式化字符串的简单方法,像这样:
I'm looking for an easy way to format a string using an array, like so:
select format_using_array('Hello %s and %s', ARRAY['Jane', 'Joe']);
format_using_array
--------------------
Hello Jane and Joe
(1 row)
有一个格式化函数,但是它需要显式的参数,我不知道其中有多少个项目数组。我想出了一个像这样的函数:
There's a format function but it needs explicit arguments and I don't know how many items are there in the array. I came up with a function like that:
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的第一天。
But maybe there's an easier way that I don't know of, it's my first day using pgsql.
推荐答案
您可以使用格式函数和VARIADIC关键字。它要求9.3,其中已修复的错误在可变函数实现中
You can use a format function and VARIADIC keyword. It requires 9.3, where is fixed bug in variadic function implementation
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)
这篇关于使用数组的Postgres格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文