问题
Why we need
WHERE CURRENT OF
clause inOracle PL/SQL
? We all know thatFETCH
retrieves only one row at a time and henceFETCH
is used inLOOP
to process all the rows of a cursor. Then why do we exclusively need aWHERE CURRENT OF
clause? We can anyhow lock the cursor rows usingFOR UPDATE
orFOR UPDATE OF
.Can rows be unlocked (which are locked by
FOR UPDATE
orFOR UPDATE OF
) once we close the cursor? Or do we need toCOMMIT
orROLLBACK
the transaction to unlock the rows?
回答1:
Have a look at this block:
DECLARE
CURSOR c1 IS
SELECT course_number, ROWID AS RID
FROM courses_tbl
FOR UPDATE;
begin
FOR aCourse IN c1 LOOP
UPDATE courses_tbl SET course_number = aCourse.course_number + 1
WHERE CURRENT OF c1;
UPDATE courses_tbl SET course_number = aCourse.course_number + 1
WHERE ROWID = aCourse.RID
end loop;
end;
The two UPDATE statements are equivalent, WHERE CURRENT OF ...
is just a shortcut for WHERE ROWID = ...
, you can use either of them.
Actually your question should be "Why we need FOR UPDATE ...
?" The reason is, the ROWID may change by other operations, e.g. ALTER TABLE ... SHRINK SPACE
, moving tablespace or big DML's. FOR UPDATE
locks the row, i.e. ensures that ROWID does not change until you finished your transaction.
No, you can release the lock only by finishing the transaction, i.e. ROLLBACK
or COMMIT
回答2:
- May be this will convince you ...
When we want to update or delete the cursor fetched row(s) from the database, we don’t have to form a UPDATE or a DELETE statement with a primary key mapping in its WHERE clause, instead, the WHERE CURRENT OF clause comes in handy.
Source: http://www.dba-oracle.com/t_adv_plsql_for_update_where_current.htm
- You must commit or rollback your transaction to release locks.
来源:https://stackoverflow.com/questions/49110728/where-current-of-in-pl-sql