What is the purpose and usage of “FOR UPDATE OF” clause in a COBOL-DB2 program

DB2DatabaseBig Data Analytics

Problem: What is the purpose of the "FOR UPDATE OF" clause in a cursor? What will happen if we fire an UPDATE statement without using this clause in a COBOL-DB2 program?

Solution

The “FOR UPDATE OF” clause is given in the cursor declaration and it is used when we want to update the table. All the columns which need to be updated should be given in the cursor declaration.

The “FOR UPDATE OF” clause will place the exclusive lock on all the qualifying rows once the cursor is open. We can also update the table without using “FOR UPDATE CLAUSE” but in that case the exclusive lock will be placed on the row only when the UPDATE query will be executed. For example - If we want to update the ORDERS table for all the entries having ORDER_DATE as 15th Sep 2020, then we will write an update cursor as below.

Example

EXEC SQL
DECLARE ORDER_CUR CURSOR WITH HOLD FOR
   SELECT * FROM ORDERS WHERE ORDER_DATE = ‘2020-09-15’
      FOR UPDATE OF ORDER_TOTAL, ORDER_STATUS
END-EXEC

This query will place an exclusive lock on all the rows of the ORDERS table having ORDER_DATE as 15th Sep 2020. However, If we want to update all the columns of this table then we do not have to give any column name in the “FOR UPDATE OF” clause.

It is also possible to declare a SELECT cursor and use an UPDATE query for one row at a time. But in this case the exclusive lock will be placed only on one row at a time, once the UPDATE query is executed.

raja
Published on 01-Dec-2020 05:05:09
Advertisements