我不会使用显式游标来执行此操作。 Steve F. 不再建议人们在可以使用隐式游标时使用显式游标。
该方法与count(*)
是不安全的。如果另一个会话删除了包含以下内容的行之后满足条件的行count(*)
,并在该行之前select ... into
,代码将抛出一个无法处理的异常。
原始帖子的第二个版本没有这个问题,并且通常是首选。
也就是说,使用异常会产生较小的开销,如果您 100% 确定数据不会更改,则可以使用count(*)
,但我建议不要这样做。
我运行了这些基准测试甲骨文10.2.0.1 on 32位Windows。我只看经过的时间。还有其他测试工具可以提供更多详细信息(例如锁存器计数和使用的内存)。
SQL>create table t (NEEDED_FIELD number, COND number);
表已创建。
SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);
已创建 1 行。
declare
otherVar number;
cnt number;
begin
for i in 1 .. 50000 loop
select count(*) into cnt from t where cond = 1;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 1;
else
otherVar := 0;
end if;
end loop;
end;
/
PL/SQL 过程成功完成。
过去:00:00:02.70
declare
otherVar number;
begin
for i in 1 .. 50000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 1;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
PL/SQL 过程成功完成。
过去:00:00:03.06