Oracle:如何限制“select .. for update skip locked”中的行数

use*_*525 5 sql oracle

我有一张桌子:

table foo{
  bar number,
  status varchar2(50)
}
Run Code Online (Sandbox Code Playgroud)

我有多个线程/主机,每个线程/主机都在使用该表。每个线程更新状态,即悲观地锁定行。

在 Oracle 12.2 中。

select ... for update skip locked似乎可以完成这项工作,但我想限制行数。新的FETCH NEXT听起来不错,但我无法正确理解语法:

SELECT * FROM foo ORDER BY bar 
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY 
FOR UPDATE SKIP LOCKED;
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最简单方法是什么,即使用最少代码1 (理想情况下没有 pl/sql 函数)?

我想要这样的东西:

select * from (select * from foo 
               where status<>'baz' order by bar
) where rownum<10 for update skip locked
Run Code Online (Sandbox Code Playgroud)

PS 1. 我们正在考虑离开 oracle。

小智 1

我建议创建pl/sql函数并使用动态sql来控制锁定记录的数量。锁是在读取时获取的。因此,获取 N 条记录会自动锁定它们。请记住,一旦完成事务(提交或回滚),记录就会被解锁。以下是锁定 N 条记录并将其 id 值作为数组返回的示例(假设您已在表中添加了主键 ID 列):

create or replace function get_next_unlocked_records(iLockSize number)
return sys.odcinumberlist
is
  cRefCursor sys_refcursor;
  aIds       sys.odcinumberlist := sys.odcinumberlist();
begin
  -- open cursor. No locks so far
  open cRefCursor for 
    'select id from foo '||
    'for update skip locked';

  -- we fetch and lock at the same time 
  fetch cRefCursor bulk collect into aIds limit iLockSize;

  -- close cursor
  close cRefCursor;

  -- return locked ID values, 
  -- lock is kept until the transaction is finished
  return aIds; 

end;
Run Code Online (Sandbox Code Playgroud)

sys.odcinumberlist是内置的数字数组。

这是在数据库中运行的测试脚本:

declare 
  aRes sys.odcinumberlist;
begin
  aRes := get_next_unlocked_records(10);
  for c in (
    select column_value id
    from   table(aRes)
  ) loop
    dbms_output.put_line(c.id);
  end loop;
end;
Run Code Online (Sandbox Code Playgroud)