Iterate through the records of a query
By using a special type of FOR loop, you can iterate through the
results of a query and manipulate that data. The FOR IN loop syntax
is as follows:
[<<label>>]
FOR record | row IN select_clause LOOP
statements
END LOOP;
The record or row is assigned all the rows that result from the
select clause and the loop body runs for each. An example follows:
DECLARE
mviews RECORD;
-- Instead, if you did:
-- mviews cs_materialized_views%ROWTYPE;
-- this record is ONLY usable for the cs_materialized_views table
BEGIN
CALL cs_log('Refreshing materialized views...');
FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
-- Now "mviews" has one record from cs_materialized_views
RAISE EXCEPTION, 'Can't execute SQL while processing SQL for %',
mview.my_name;
END LOOP;
CALL cs_log('Done refreshing materialized views.');
return 1;
end;
If the loop is terminated with an EXIT statement, the last assigned row is still accessible after the loop.
The FOR-IN EXECUTE statement is another way to iterate over records:
[<<label>>]
FOR record | row IN EXECUTE text_expression LOOP
statements
END LOOP;
This form is similar to the previous form, except that the source SELECT statement is specified as a string expression. The main difference between the two is the syntax and use of variables to build the SQL to run. The first form is faster to evaluate.