gpt4 book ai didi

arrays - 使用数组的 Postgres 格式化字符串

转载 作者:行者123 更新时间:2023-11-29 11:26:20 25 4
gpt4 key购买 nike

我正在寻找一种使用数组格式化字符串的简单方法,如下所示:

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,fixed 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)

关于arrays - 使用数组的 Postgres 格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com