I have a Postgresql PL/pgSQL function that has a double nested FOR loop, where I want to set column names dynamically. However I can't find a way of accessing RECORD columns programmatically.
I'll skip straight to an example with some code:
FOR loop_helper1 IN SELECT
id, name1, name2, name3, nameN,
FROM table1
LOOP
FOR loop_helper2 IN SELECT name FROM table2 LOOP
-- I want to set values of columns in loop_helper1,
-- with the column name given by loop_helper2.name
-- An EXECUTE would not allow me to do this:
EXECUTE 'loop_helper1.' || loop_helper2.name || ':= function_call(123);'
-- (Eg. 'loop_helper1.name2 := function_call(123);')
-- However, this produces: ERROR: syntax error at or near "loop_helper1"
END LOOP;
END LOOP;
Any ideas?
Surely there's gotta be a way to do this, but I just can't seem to find it. All help and suggestions are appreciated. Thanks.