The FOR statement executes a statement for each row of a table.
>>-+--------+--FOR--+-------------------+--AS-------------------> '-label:-' '-SQL-variable-name-' >----cursor-name--CURSOR--+-----------+--FOR--------------------> '-WITH HOLD-' .-----------------------------. V | >--select-statement--DO----SQL-procedure-statement-- ;-+--------> >--END FOR--+-------+------------------------------------------>< '-label-'
Either the SQL-variable-name or label can be used to qualify other SQL variable names in the statement.
If SQL-variable-name is specified, then it should be used to qualify any other SQL variable names in the statement when debugging the SQL function, SQL procedure, or SQL trigger.
Each expression in the select list must have a name. If an expression is not a simple column name, the AS clause must be used to name the expression. If the AS clause is specified, that name is used for the variable and must be unique.
FOR statement rules: The FOR statement executes one or multiple statements for each row in a table. The cursor is defined by specifying a select list that describes the columns and rows selected. The statements within the FOR statement are executed for each row selected.
The select list must consist of unique column names and the table specified in the select list must exist when the function, procedure, or trigger is created.
The cursor specified in a FOR statement cannot be referenced outside the FOR statement and cannot be specified on an OPEN, FETCH, or CLOSE statement.
Handler warning: Handlers may be used to handle errors that might occur on the open of the cursor or fetch of a row using the cursor in the FOR statement. Handlers defined to handle these open or fetch conditions should not be CONTINUE handlers as they may cause the FOR statement to loop indefinitely.
In this example, the FOR statement is used to specify a cursor that selects 3 columns from the employee table. For every row selected, SQL variable fullname is set to the last name followed by a comma, the first name, a blank, and the middle initial. Each value for fullname is inserted into table TNAMES.
BEGIN DECLARE fullname CHAR(40); FOR vl AS c1 CURSOR FOR SELECT firstnme, midinit, lastname FROM employee DO SET fullname = lastname || ', ' || firstnme ||' ' || midinit; INSERT INTO TNAMES VALUE ( fullname ); END FOR; END;