1

在 SQL Server 中,就性能而言,使用它IF EXISTS (select * ...)比使用IF (select count(1)...) > 0...

但是,看起来 Oracle 不允许EXISTS在语句内部,因为 using在性能方面效率非常低IF,有什么替代方法可以做到这一点?IF select count(1) into...

代码示例:

IF (select count(1) from _TABLE where FIELD IS NULL) > 0 THEN
UPDATE TABLE _TABLE
SET FIELD = VAR    
WHERE FIELD IS NULL;
END IF;
4

2 回答 2

6

编写代码片段的最佳方法是

UPDATE TABLE _TABLE
SET FIELD = VAR    
WHERE FIELD IS NULL;

即只做更新。它要么处理行,要么不处理。如果您需要检查它是否确实处理了行然后添加

if (sql%rowcount > 0)
then
...

通常在您有类似逻辑的情况下

declare
  v_cnt number;
begin
select count(*) 
  into v_cnt 
  from TABLE 
 where ...;

if (v_cnt > 0) then..

最好使用 ROWNUM = 1,因为你不关心是否有 4000 万行......只需在找到 1 行后让 Oracle 停止。

declare
  v_cnt number;
begin
select count(*) 
  into v_cnt 
  from TABLE 
 where rownum = 1
   and ...;

if (v_cnt > 0) then..

或者

select count(*) 
  into v_cnt 
  from dual
 where exists (select null 
                 from TABLE
                where ...);

无论您喜欢哪种语法。

于 2013-02-21T15:22:40.540 回答
2

根据:http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID: 3069487275935

你可以试试:

  for x in ( select count(*) cnt
               from dual 
              where exists ( select NULL from foo where bar ) )
  loop
        if ( x.cnt = 1 ) 
        then
          found do something
        else 
          not found
        end if;
  end loop;

是一种方式(非常快,只在“需要”时运行子查询,其中存在在到达第一行后停止子查询)

该循环始终至少执行一次且最多执行一次,因为没有 group by 子句的表上的 count(*) 总是返回至少一行和最多一行(即使表本身也是空的!)

于 2013-02-21T15:25:05.740 回答