2014-02-26 87 views
1

我想初始化一個數組array_entries。嘗試array_fill作爲array_fill(0,array_entries)但dint工作。如何初始化一個循環內的postgres中的數組

create or replace function vin_temp_test1(k date,x varchar) RETURNS float AS $$ 
    declare 
    array_entries int []; 
    curs4 CURSOR FOR select * from temp_table; 
    record_type1 record; 

    fetch curs4 into record_type1; 
      exit when not found; 
    loop 
    -- trying to intialize the array array_entries here 
     loop 
    --filling the array inside this loop. 
     end loop; 
    end loop; 

回答

0

也許你有NULL在array_entries

postgres=# select array_fill(0, NULL); 
ERROR: dimension array or low bound array cannot be null 
postgres=# select array_fill(0, ARRAY[10]); 
     array_fill  
----------------------- 
{0,0,0,0,0,0,0,0,0,0} 
(1 row) 

注意!

很高興知道,所以更大的陣列(大於20000場)更新很慢。比可重複更新快得多的是使用ARRAY(子選擇)構造函數

postgres=# DO $$ DECLARE x int[]; 
      begin 
       x := array_fill(0,ARRAY[100000]); 
       for i in 1..100000 loop 
       x[i] := 1; 
      end loop; end $$; 
DO 
Time: 5533.581 ms 
postgres=# DO $$ DECLARE x int[]; 
      begin x := ARRAY(SELECT 1 FROM generate_series(1,100000)); end $$; 
DO 
Time: 36.590 ms 
+0

實際上我沒有想要數組,因爲它是在declare節之後。我的意思是一個沒有數值的空數組。 – user2569524