Using Select Cursors with FOREACH

When using the FOREACH statement, if the result set from a query is to be modified, do not use this result set as an exit criterion for the FOREACH loop. For example, if the FOREACH statement declares a Select cursor that is expected to return 30 rows, but DELETE, INSERT, or UPDATE operations within the FOREACH loop modify the result set of the query, this might cause unexpected behavior. To ensure that a FOREACH loop works as intended, make sure that any Select cursor in the FOREACH statement completes its execution before you begin modifying its result set.

One way to avoid unexpected results from a FOREACH loop that performs DML operations on the rows returned by a query is to use an ORDER BY clause in the SELECT statement to materialize the result set.