2

如何在 PostgreSQL 中动态创建数组?

考虑一下,例如:

CREATE OR REPLACE FUNCTION fun( )
RETURNS SETOF void AS
$BODY$
DECLARE

i numeric;

BEGIN

 FOR i in 1..10   LOOP
     //I have to create an array as 
     arr1[] ,arr2[] ... based on length
 END LOOP;
END;

$BODY$
LANGUAGE plpgsql
4

2 回答 2

7

为此目的有一个特殊的函数——array_fill:

postgres=# 选择 array_fill(0, ARRAY[10]);
      数组填充       
----------------------
 {0,0,0,0,0,0,0,0,0,0}
(1 行)

postgres=# select array_fill('Hello'::text, ARRAY[10]);
                          数组填充                           
-------------------------------------------------- -------------
 {你好,你好,你好,你好,你好,你好,你好,你好,你好}
(1 行)

postgres=# 选择 array_fill(0, ARRAY[3,3]);
        数组填充         
--------------------------
 {{0,0,0},{0,0,0},{0,0,0}}
(1 行)

在 PL/pgSQL 中(但对于大型数组(超过 100 项)来说速度要慢得多:

做$$
宣布
结果 int[] = '{}';
开始
  对于我在 1..10
  环形
    结果 := 结果 || 0;
  结束循环;
  RAISE NOTICE '%',结果;
结尾;
$$;
于 2013-08-28T12:10:57.420 回答
1

在不知道最终目标的情况下很难说应该走哪条路,Pavel Stehule 给了你关于填充数组的好建议,你可以使用临时表在函数中存储数组。
您还可以创建一个返回一组数组的函数,然后对其进行迭代,例如:

create or replace function fun1()
returns setof int[] as
$BODY$
declare
    i int;
begin
    for i in 1..10 loop
        return next array_fill(0, array[i]);
    end loop;
end;
$BODY$
language plpgsql;


create or replace function fun2()
returns setof int as
$BODY$
declare
    a int[];
begin
    for a in select * from fun1() loop
        return next array_length(a, 1);
    end loop;
end;
$BODY$
language plpgsql;

sql fiddle frmo

于 2013-08-29T08:52:29.420 回答