Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

arrays - Iterating over integer[] in PL/pgSQL

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
DO
$do$
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;
END
$do$;

Or simpler with FOREACH in PostgreSQL 9.1 or later:

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

For multi-dimensional arrays see:

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

Search the tags or for more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...