The CURSOR is used when we have to fetch multiple rows from a table. There are 4 steps involved in order to use a cursor in a COBOL-DB2 program.
DECLARE cursor− In this step we will define the layout of the cursor. We will give the query we want to use. For example−
EXEC SQL DECLARE ORDER_CUR CURSOR FOR SELECT ORDER_ID FROM ORDERS WHERE ORDER_DATE = ‘2020-07-28’ END-EXEC
OPEN cursor− Next we will open our cursor. This statement readies the cursor for data retrieval. For example−
EXEC SQL OPEN ORDER_CUR END-EXEC
FETCH cursor− In this statement, we start fetching the data from DB2 and the row data is stored in host variables. The syntax is like below.
EXEC SQL FETCH ORDER_CUR INTO :ORDER-ID END-EXEC
CLOSE cursor− In this last step we close the cursor which will release all the resources held by the cursor.
EXEC SQL CLOSE ORDER_CUR END-EXEC