postgresql 在 plpgsql 中循环数组维度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9783422/
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
Loop over array dimension in plpgsql
提问by blue01
In plpgsql, I want to get the array contents one by one from a two dimension array.
在plpgsql中,我想从二维数组中一一获取数组内容。
DECLARE
m varchar[];
arr varchar[][] := array[['key1','val1'],['key2','val2']];
BEGIN
for m in select arr
LOOP
raise NOTICE '%',m;
END LOOP;
END;
But the above code returns:
但是上面的代码返回:
{{key1,val1},{key2,val2}}
in one line. I want to be able to loop over and call another function which takes parameters like:
在一行中。我希望能够循环并调用另一个采用以下参数的函数:
another_func(key1,val1)
回答by Erwin Brandstetter
Since PostgreSQL 9.1there is the convenient FOREACH
:
由于 PostgreSQL 9.1有方便的FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
旧版本的解决方案:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
此外,PostgreSQL 类型系统varchar[]
和varchar[][]
PostgreSQL 类型系统之间没有区别。我在这里更详细地解释。
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
该DO
语句至少需要 PostgreSQL 9.0,并且LANGUAGE plpgsql
是默认值(因此您可以省略声明)。