小编Mar*_*inJ的帖子

使用数组的Postgres格式字符串

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

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的第一天.

arrays format postgresql

5
推荐指数
1
解决办法
5521
查看次数

标签 统计

arrays ×1

format ×1

postgresql ×1