敬业的IT人 >> 数据库 >> Oracle >> 在不同情况下判断是否存在记录的实用方法

在不同情况下判断是否存在记录的实用方法

敬业的IT人 互联网 佚名 2008-1-7 17:06:00

很多网友在判断是否存在记录时经常使用下面的方法:

select count(*) into t_count from t where condition;if t_count> 0 then ....

但上面的方法的不足之处主要在于:某些情况下我们需要的仅仅是是否存在,而不是得到总记录数。查询记录总数付出了不必要的性能代价。

下面我们具体来看两种情况:

1. 假如判断是否存在记录后, 要查询记录中的某些列的信息,或者是决定要对表进行insert/update操作,具体操作:

(1)

select count(*) into t_count from t where condition;if t_count> 0 then select cols into t_cols from t where condition;else otherstatement;end;

(2)

select count(*) into t_count from t where condition;if t_count> 0 then update ...;else insert ...;end;

注释:以上两种操作,都可以采用直接操作,然后进行例外处理的方式,根本就不进行这个存在性判断。

改写后的(1)

begin select cols into t_cols from t where condition;exception when no_data_found then begin statement-block2; end; when others then begin raise error... end;end;

改写后的(2)

update t set ... where condition;IF SQL%NOTFOUND THEN insert into t ...END IF;

或者:

begin insert into t ...exception when DUP_VAL_ON_INDEX then begin update t set ... end;end;

2. 假如判断是否存在记录来决定是否进行其它操作, 如下例

select count(*) into t_count from t where condition;if t_count> 0 then ....

则可以改成这样的语句:

select count(*) into t_count from dual where exists(select 1 from t where condition);if t_count> 0 then ....

如果我们使用改写后的语句,绝大多数情况下应该会有比原来的语句又更好的性能。

粤ICP备06119539号
Copyright CiscoSky.Org,Some Rights Reserved.
Email:me1228#tom.com