如何让光标选取表数据发生变化?

问题描述 投票:0回答:3

我在程序中有以下光标:

procedure Run is
    Cur Cursor is select * from table where condition;
    R Cur%rowtype;

    Open Cur;
    loop
        fetch Cur into R;
        exit when Cur%notfound;

        -- Run some time consuming operations here
        something...
    end loop;
    Close Cur;
end;

此游标正在运行计划作业。

假设运行此游标时有 100 行满足 where 条件。

如果在程序运行时,我在表中插入了满足相同条件的新行,有什么方法可以让光标也选择这些新行?

oracle plsql
3个回答
3
投票

没有。

游标将返回的行集在游标打开时确定。此时,Oracle 知道当前的 SCN(系统更改编号)并将返回该时间点存在的数据。

根据问题的性质,您可以编写一个循环,不断询问满足条件的单行(假设您的耗时操作更新了一些数据,以便您知道需要处理什么)。类似的东西

loop
  begin
    select some_id
      into l_some_id
      from your_table
     where needs_processing = 'Y'
     order by some_id
     fetch first row only;
  exception
    when no_data_found
    then
      l_some_id := null;
  end;
  
  exit when l_some_id is null;
      
  some_slow_operation( l_some_id );
end loop;

假设

some_slow_operation
needs_processing
标志更改为 N。并假设您正在使用默认的已提交读事务隔离级别。


1
投票

不,光标不能做到这一点。事务是一致的,您的光标是您提取的数据的快照。 如果您想要一致的结果,您可以:

  1. 锁定表格,以免发生任何更改,
  2. 使用其他机制,例如将逻辑移至触发器,该触发器将在满足您的条件的每条新数据上执行(并且会带来开销,因此非常具体)

0
投票

您可以在循环内进行提交,以便选择查询在每次迭代中从表中获取最新记录。

© www.soinside.com 2019 - 2024. All rights reserved.