Looping row-by-row through a selected result set
Available in
PSQL
Syntax
A FOR SELECT
statement
retrieves each row sequentially from the result set and executes the statement or block of statements on the row. In each iteration of the loop, the field values of the current row are copied into pre-declared variables.
Including the
AS CURSOR
clause enables positioned deletes and updates to be performed — see notes belowcan carry named parameters that must be previously declared in the
DECLARE VARIABLE
statement or exist as input or output parameters of the procedurerequires an clause that is located at the end of the
SELECT … FROM …
specification. In each iteration of the loop, the field values in the current row are copied to the list of variables specified in theINTO
clause. The loop repeats until all rows are retrieved, after which it terminatescan be terminated before all rows are retrieved by using a
LEAVE statement
Other points to take into account regarding undeclared cursors:
the cursor name argument associated with an clause must not clash with any names created by
DECLARE VARIABLE
orDECLARE CURSOR
statements at the top of the body code, nor with any other cursors surfaced by anAS CURSOR
clauseThe optional
FOR UPDATE
clause in theSELECT
statement is not required for a positioned update
Examples using FOR SELECT
A simple loop through query results:
Using the
AS CURSOR
clause to surface a cursor for the positioned delete of a record:
See also
DECLARE CURSOR
, , SELECT
, , DELETE