Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over array dimension in plpgsql

In plpgsql, I want to get the array contents one by one from a two dimension array.

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) 
like image 764
blue01 Avatar asked Mar 20 '12 08:03

blue01


People also ask

What is $$ in Plpgsql?

In PostgreSQL, the dollar-quoted string constants ($$) is used in user-defined functions and stored procedures. In PostgreSQL, you use single quotes for a string constant like this: select 'String constant'; When a string constant contains a single quote ('), you need to escape it by doubling up the single quote.

How do I find the length of an array in PostgreSQL?

PostgreSQL makes it less complicated for using arrays in a query and finding the length of a column using only the simple syntax array_length (column_name, int). The “array_length” in this syntax returns the length of an array of the first argument i.e., column_name, and “int” tells the dimension of the array measured.

How do you write a loop in PostgreSQL?

The syntax of the for loop statement to iterate over a result set of a dynamic query: [ <<label>> ] for row in execute query_expression [ using query_param [, ... ] ] loop statements end loop [ label ];


1 Answers

Since PostgreSQL 9.1 there is the convenient 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.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

like image 73
Erwin Brandstetter Avatar answered Oct 04 '22 08:10

Erwin Brandstetter