带有插入stmt的oracle游标并发

oracle cursor concurrency with insert stmt

游标的结果是在打开时确定的?但是下面的演示揭示了一个区别:

drop table Highschooler;
drop table w;
create table Highschooler( grade int );
create table w( grade int );

insert into Highschooler(grade) values (13);
insert into Highschooler(grade) values(14);
insert into Highschooler(grade) values (15);
insert into w values (16);

select * from Highschooler;
select * from w;

create or replace create function ff(a int) return int is 
   total int := 0;
begin
  select  count(grade) into total from w where grade > a ;
  return total;
end;

DECLARE
   my_var int :=0;
   my_var2 int := 0;
   my_var3 int := 0;
   CURSOR CC IS select ff(grade) from Highschooler for update;
BEGIN
   open CC;
   fetch CC into my_var;
   insert into w values (16);
   fetch CC into my_var2;
   fetch CC into my_var3;
   dbms_output.put_line(my_var || '  - '  || my_var2 || ' - ' || my_var3);
   close CC;
end;

输出:

GRADE
13
14
15
Download CSV
3 rows selected.

Result Set 4
GRADE
16
Statement processed. ------- the insert stmt in 'insert into w values (16);' affect the cursor's output here
1  - 2 - 2

您的函数包含另一个仅在执行时打开的游标。这就是为什么你通常不应该使用函数来做 SQL - 你最终会得到逻辑上损坏的数据,因为每次执行都将使用不同的 SCN 点。

定义游标不使用函数,例如

CURSOR CC IS 
select  (select  count(grade) from w where grade > h.grade) as ff 
from Highschooler h;

这将导致预期的结果

1  - 1 - 1

另请注意,避免使用函数会带来更好的性能,因为您省略了 上下文切换