>>-FOREACH------------------------------------------------------> (1) >----+------------------------------------------+--| SELECT ... INTO Statement |---------> +-WITH HOLD--------------------------------+ +-cursor--+-----------+--FOR---------------+ | '-WITH HOLD-' | '-| Routine Call |--+--------------------+-' | .-,--------. | | V | | '-INTO----data_var-+-' (2) >--| Statement Block |-------END FOREACH--+---+---------------->< '-;-' Routine Call: |--EXECUTE--+-PROCEDURE--+-procedure-+------+-------------------> | +-SPL_var---+ | | '-function--' | | (3) | '--------FUNCTION--+-SPL_var--+-' '-function-' >--(--+-----------------------+--)------------------------------| | .-,-----------------. | | V (4) | | '---| Argument |------+-'
Element | Description | Restrictions | Syntax |
---|---|---|---|
cursor | Identifier that you supply as a name for this FOREACH loop | Each cursor name within a routine must be unique | Identifier |
data_var | SPL variable in the calling routine that receives the returned values | Data type of data_var must be appropriate for returned value | Identifier |
function,
procedure |
SPL function or procedure to execute | Function or procedure must exist | Database Object Name |
SPL_var | SPL variable that contains the name of a routine to execute | Must be a CHAR, VARCHAR, NCHAR, or NVARCHAR type | Identifier |
A FOREACH loop is the procedural equivalent of using a cursor. To execute a FOREACH statement, the database server takes these actions:
Because the statement block can contain additional FOREACH statements, cursors can be nested. No limit exists on the number of nested cursors.
An SPL routine that returns more than one row, collection element, or set of values is called a cursor function. An SPL routine that returns only one row or value is a noncursor function.
This SPL procedure illustrates FOREACH statements with a SELECT ... INTO clause, with an explicitly named cursor, and with a procedure call:
CREATE PROCEDURE foreach_ex() DEFINE i, j INT; FOREACH SELECT c1 INTO i FROM tab ORDER BY 1 INSERT INTO tab2 VALUES (i); END FOREACH FOREACH cur1 FOR SELECT c2, c3 INTO i, j FROM tab IF j > 100 THEN DELETE FROM tab WHERE CURRENT OF cur1; CONTINUE FOREACH; END IF UPDATE tab SET c2 = c2 + 10 WHERE CURRENT OF cur1; END FOREACH FOREACH EXECUTE PROCEDURE bar(10,20) INTO i INSERT INTO tab2 VALUES (i); END FOREACH END PROCEDURE; -- foreach_ex
A select cursor is closed when any of the following situations occur: