Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a given list of values in PL/pgSQL

I'm trying to loop through few fields and run a function on them:

FOR field IN ARRAY['f1','f2'] LOOP
    execute pg_temp.converFieldToLower(newTableNameRaw,field)
END LOOP;

This is the function i'm trying to use:

CREATE OR REPLACE FUNCTION pg_temp.converFieldToLower(t varchar, f varchar) RETURNS void AS $$
#variable_conflict use_variable
BEGIN
  EXECUTE concat_ws (' ', 'UPDATE',t,'SET',f,'= LOWER(',f,')');
END;
$$ LANGUAGE plpgsql;

It looks like it's not the right way to declare an array, what am I doing wrong?

ERROR:  syntax error at or near "ARRAY"
LINE 49:         FOR field IN ARRAY['f1','f2'] LOOP
like image 798
Guy s Avatar asked Feb 15 '17 13:02

Guy s


1 Answers

The FOREACH loop is designed specifically for iterating through the elements of an array value, e.g.:

FOREACH field IN ARRAY ARRAY['f1','f2'] LOOP
    execute pg_temp.converFieldToLower(newTableNameRaw,field) into res;
END LOOP;

The feature was introduced in Postgres 9.1.

like image 64
klin Avatar answered Oct 16 '22 12:10

klin