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)
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.
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.
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 ];
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With