Not sure if this is going to work. The embedded SQL implementation uses cursors internally and I am not sure what happens if you also explicitly use cursors in your script.

At the very least you should set:
SET NOCOUNT ON
at the top of you script. (This prevents generation of internal result messages)

Also you should use SQLNextResultSet to make sure you fetch all the results. Sometimes these kind of scripts generate intermediate result sets that confuse the embedded SQL logic.

Maybe it is better to put the logic in a stored procedure and execute that.

Or try to achieve the same without using cursors. You may be able to accomplish the same by executing 2 ESQL queries, where you use the results of the first query to generate the second query.