在 PL/pgSQL 中迭代 integer[] [英] Iterating over integer[] in PL/pgSQL
问题描述
我试图在 plpgsql 函数中遍历一个整数数组 (integer[]
).像这样:
声明一个整数[] = 数组[1,2,3];我大;开始因为我在环形提高通知 "% ",i;结束循环;返回真;结尾
在我的实际用例中,整数数组 a
作为参数传递给函数.我收到此错误:
错误:$1"处或附近的语法错误第 1 行:1 美元
如何正确遍历数组?
DO$做$宣布整数 [] := 数组 [1,2,3];i 整数;-- int,不是 bigint开始FOR i IN 1 .. array_upper(a, 1)环形提高通知 '%', a[i];-- 单引号结束循环;结尾$做$;
或者更简单的FOREACH
在 PostgreSQL 9.1 或更高版本中:
FOREACH i IN ARRAY a环形提高通知 '%', i;结束循环;
多维数组见:
但是,基于集合的解决方案使用 generate_series()
或 unnest()
通常比循环大集合更快.基本示例:
搜索标签 generate-series 或 unnest 了解更多.
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?
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 generate-series or unnest for more.
这篇关于在 PL/pgSQL 中迭代 integer[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!