Iterating over integer[] in PL/pgSQL

…衆ロ難τιáo~ 提交于 2019-11-26 22:49:29

问题


I am trying to loop through an integer array (integer[]) in a plpgsql function. Something like this:

declare
    a integer[] = array[1,2,3];
    i bigint;
begin
    for i in a
loop 
    raise notice "% ",i;
end loop;
return true;
end

In my actual use case the integer array a is passed as parameter to the function. I get this error:

ERROR:  syntax error at or near "$1"
LINE 1:   $1

How to loop through the array properly?


回答1:


DECLARE
   a integer[] := array[1,2,3];
   i integer;                   -- int, not bigint!
BEGIN
FOR i IN 1 .. array_upper(a, 1)
LOOP
   RAISE NOTICE '%', a[i];      -- single quotes!
END LOOP;
RETURN TRUE;
END

Or try the new FOREACH in PostgreSQL 9.1:

FOREACH i IN ARRAY a
LOOP 
   RAISE NOTICE '%', i;
END LOOP;

However, set-based solutions with generate_series() or unnest() are often faster than looping for big sets.

Basic examples:

  • PostgreSQL: Frequency Table Expansion
  • Select each month between a start and end date

Search the tags generate-series or unnest for more.



来源:https://stackoverflow.com/questions/10214392/iterating-over-integer-in-pl-pgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!