遍历整数[]在PL / pgSQL里 [英] Iterating over integer[] in PL/pgSQL
问题描述
我通过在PLPGSQL函数整数数组(整数[]
)试图循环。事情是这样的:
申报
一个整数[] =数组[1,2,3]
我BIGINT;
开始
因为我在
循环
募集的通知%,我;
结束循环;
返回true;
结束
在我的实际使用情况的整数数组 A
作为参数传递给函数传递。我得到这个错误:
错误:语法错误或接近$ 1
LINE 1:$ 1
块引用>如何通过数组循环是否正常?
解决方案DECLARE
一个整数[] =数组[1,2,3]
我整数; - 诠释,而不是BIGINT!
开始
因我1 .. array_upper(一,1)
循环
RAISE NOTICE'%',一[I] - 单引号!
END LOOP;
返回TRUE;
结束或者尝试<一个href=\"http://www.postgresql.org/docs/current/interactive/plpgsql-control-structures.html#PLPGSQL-FOREACH-ARRAY\"相对=nofollow>新的
FOREACH
PostgreSQL中的 9.1 :FOREACH我阵列一
循环
RAISE NOTICE'%',我;
END LOOP;然而,基于集的解决方案
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?
解决方案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()
orunnest()
are often faster than looping for big sets.Basic examples:
Search the tags generate-series or unnest for more.
这篇关于遍历整数[]在PL / pgSQL里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!