在plpgsql中循环数组维度

时间:2021-09-12 01:45:06

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)

1 个解决方案

#1


84  

Since PostgreSQL 9.1 there is the convenient FOREACH:

由于PostgreSQL 9.1,每个人都方便:

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[][]也没有区别。我在这里更详细地解释。

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,而语言plpgsql是默认的(因此可以省略声明)。

#1


84  

Since PostgreSQL 9.1 there is the convenient FOREACH:

由于PostgreSQL 9.1,每个人都方便:

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[][]也没有区别。我在这里更详细地解释。

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,而语言plpgsql是默认的(因此可以省略声明)。