How can I retrieve next n unlocked rows from Oracle?

自古美人都是妖i 提交于 2021-02-07 20:19:02

问题


Suppose I have Oracle table books store n books info with columns id and title. Some of the tuples are locked by SELECT ... FOR UPDATE clause.

Suppose these rows whose id in (1, 2, 4, 5, 6, 9) are get locked.

Now I want to write a SQL to achieve that when execute it, return the next 2 records which are unlocked. And the SQL may be called by multiple process at same time.

That is to say, the first call will return id = 3 and id = 7 records; the second call will return id = 8 and id = 10 records.

I think SELECT ... FOR UPDATE SKIP LOCKED would help, it auto skips rows which are locked and solved the multiple process call at same time problem. But how to achieve get next 2 records? I don't think rownum works, because I do not know which rows are locked.

Could anybody share your ideas? Thanks a lot!


回答1:


In 12c you can use the row_limiting_clause, documented here: http://docs.oracle.com/database/121/SQLRF/statements_10002.htm#SQLRF01702

The general syntax is:

[ OFFSET offset { ROW | ROWS } ]
[ FETCH { FIRST | NEXT } [ { rowcount | percent PERCENT } ]
    { ROW | ROWS } { ONLY | WITH TIES } ]

Alternatively, use the Oracle Streams Advanced Queuing API documented here: http://docs.oracle.com/database/121/ADQUE/aq_opers.htm#ADQUE2835




回答2:


I'm no oracle expert (or user even ;)) but might this work? (as suggested in this answer):

SELECT * FROM  MYTABLE FOR UPDATE SKIP LOCKED        
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY


来源:https://stackoverflow.com/questions/30993756/how-can-i-retrieve-next-n-unlocked-rows-from-oracle

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