WHERE CURRENT OF in PL/SQL

亡梦爱人 提交于 2020-02-23 04:19:06

问题


  1. Why we need WHERE CURRENT OF clause in Oracle PL/SQL? We all know that FETCH retrieves only one row at a time and hence FETCH is used in LOOP to process all the rows of a cursor. Then why do we exclusively need a WHERE CURRENT OF clause? We can anyhow lock the cursor rows using FOR UPDATE or FOR UPDATE OF.

  2. Can rows be unlocked (which are locked by FOR UPDATE or FOR UPDATE OF) once we close the cursor? Or do we need to COMMIT or ROLLBACK 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:


  1. 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

  1. You must commit or rollback your transaction to release locks.


来源:https://stackoverflow.com/questions/49110728/where-current-of-in-pl-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!