1

This is related to:

I want to loop over values returned in a single column.

In other words:

FOR my_var IN select distinct some_column from some_table LOOP
  -- do stuff with my_var
END LOOP;

(The type of some_column is text, by the way.)

However, I get an error (line break added for readability):

ERROR:  loop variable of loop over rows must be a record
or row variable or list of scalar variables

I believe I can work around this with something like:

DECLARE
  somerow RECORD;
  my_var TEXT;
FOR somerow IN select distinct some_column from some_table LOOP
  my_var := somerow.somecolumn;
  -- do stuff with my_var
END LOOP;

Or perhaps even:

DECLARE
  idontcare INT;
  my_var TEXT;
FOR my_var, idontcare IN select distinct some_column, 1 from some_table LOOP
  -- do stuff with my_var
END LOOP;

But, isn't there any way I can just have a single variable in a comma-separated list? Or is that impossible?

(If it's impossible, are the other workarounds I gave above even correct? Any gotchas in them?)

  • 1
    I used the second workaround mentioned above. Seems to operate as expected. – Wildcard Nov 25 '17 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.