postgresql 在 PL/pgSQL 中迭代 integer[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10214392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 23:27:02  来源:igfitidea点击:

Iterating over integer[] in PL/pgSQL

arrayspostgresqlloopsplpgsqlpostgresql-8.4

提问by Dipro Sen

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

我正在尝试integer[]在 plpgsql 函数中遍历整数数组 ( )。像这样的东西:

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 ais passed as parameter to the function. I get this error:

在我的实际用例中,整数数组a作为参数传递给函数。我收到此错误:

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

How to loop through the array properly?

如何正确循环数组?

回答by Erwin Brandstetter

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 FOREACHin PostgreSQL 9.1 or later:

或者FOREACH在 PostgreSQL 9.1 或更高版本中更简单:

   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 for big sets. Basic examples:

然而,使用generate_series()or的基于集合的解决方案unnest()通常比大集合的循环更快。基本示例:

Search the tags generate-seriesor unnestfor more.

搜索标签generate-seriesunnest以获取更多信息。