The
WHERE CURRENT OF clause is used in some UPDATE and DELETE statements.
The most recent row fetched from the table should be updated or deleted.
To use this clause we must declare the cursor with the
FOR UPDATE clause.
Oracle provides the
FOR UPDATE clause in SQL to allow the developer to lock a set of Oracle rows for the duration of a transaction. In Other sessions can only query the rows but they can not update or delete.
Current of clause is useful when a table doesn't have unique values or the table contains duplicate record or updating a column based on some condition . Otherwise if a table contains unique values or table doesn't contain duplicate records or updating columns without any conditions then no need of the where current clause.
Check the below example:
I have one table "EMP_DETAILS"with below data and in this table have duplicate data .
Ename | Sal |
Smith | 52000 |
Jones | 50000 |
Smith | 70000 |
King | 60000 |
Now we are updating SAL with 1000 for each employee using below PL/SQL code.
DECLARE
CURSOR EMPLOY_CUR IS SELECT * FROM EMP_DETAILS;
BEGIN
FOR INDEX1 IN EMPLOY_CUR
LOOP
UPDATE EMP_DETAILS
SET SAL=SAL+1000
WHERE ENAME=INDEX1.ENAME;
END LOOP;
COMMIT;
END;
/
But in this code have some problem with duplicate record . Now try to understand the problem in update.Cursor in 1st record and Ename="Smith" and it will satisfy two record now SAL became
SAL=52000+1000 =53000
SAL=70000+1000 =71000
Cursor in 2nd record Ename="Jones"
SAL=52000+1000 =53000
Cursor in 3rd record Ename="Smith" again it will satisfy two record now SAL became
SAL=53000+1000=54000
SAL=71000+1000=72000
Now my cursor in 4th record Ename="King"
SAL=60000+1000=61000
Check the out put which is not correct :
Ename | Sal |
Smith | 54000 |
Jones | 51000 |
Smith | 72000 |
King | 61000 |
Now we will write a code by using WHERE CURRENT OF clause
DECLARE
CURSOR EMPLOY_CUR IS SELECT * FROM EMP_DETAILS FOR UPDATE OF SAL NOWAIT;
BEGIN
FOR INDEX1 IN EMPLOY_CUR
LOOP
UPDATE EMP_DETAILS
SET SAL=SAL+1000
WHERE CURRENT OF EMPLOY_CUR;
END LOOP;
COMMIT;
END;
Check the out put which is correct :
Ename | Sal |
Smith | 53000 |
Jones | 51000 |
Smith | 71000 |
King | 61000 |