如何在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
答案 0 :(得分:6)
为此目的有一个特殊功能 - array_fill:
postgres=# select array_fill(0, ARRAY[10]); array_fill ----------------------- {0,0,0,0,0,0,0,0,0,0} (1 row) postgres=# select array_fill('Hello'::text, ARRAY[10]); array_fill --------------------------------------------------------------- {Hello,Hello,Hello,Hello,Hello,Hello,Hello,Hello,Hello,Hello} (1 row) postgres=# select array_fill(0, ARRAY[3,3]); array_fill --------------------------- {{0,0,0},{0,0,0},{0,0,0}} (1 row)
在PL / pgSQL中(但对于大型数组(超过100个项目)来说速度要慢得多:
DO $$ DECLARE result int[] = '{}'; BEGIN FOR i IN 1..10 LOOP result := result || 0; END LOOP; RAISE NOTICE '%', result; END; $$;
答案 1 :(得分: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;