oracle中记录存在性的判断
来源:互联网 发布:山东数据共享交换平台 编辑:程序博客网 时间:2024/05/02 12:19
原文:http://hi.baidu.com/xingchengjie/blog/item/fd49e854ed8a88173b293557.html
oracle关于存在性的判断
很多人喜欢用这样的方法来判断是否存在记录:select count(*) into t_count from t where condition;
if t_count> 0 then ....
这种方法的问题在于:我们需要的仅仅是是否存在,而不是得到总记录数。查询记录总数付出了不必要的性能代价。
两种情况:1. 如果判断是否存在记录后, 要查询记录中的某些列的信息,或者是决定要对表进行insert/update操作,典型的操作为:
a.
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;
b.
select count(*) into t_count from t where condition;
if t_count> 0 then
update ...;
else
insert ...;
end;
这两种操作,都可以采用直接操作,然后进行例外处理的方式,根本就不进行这个存在性判断!改写后的a.
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;
改写后的b.
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 ....
使用改写后的语句,多数情形下应该会有比原来的语句更好的性能。(当然, 如果你要查询的表本身是一个单行或只有几行记录的表, 直接查询应该会更好)
以下是PL/SQL语句示范:
declare t_count number(10);
begin
select count(*) into t_count from dual where exists
(select 1 from dzk.t_branch_asset where rownum<2);
if (t_count>0) then
dbms_output.put_line('t_count='||t_count);
end if;
end;
- oracle中记录存在性的判断
- oracle中记录存在性的判断
- oracle关于存在性的判断
- oracle关于存在性的判断
- 判断表中是否存在记录的SQL语句
- SQL 判断表中是否存在记录的高效率方法
- 判断表中是否存在该记录
- oracle中获取字段值存在重复的记录
- Oracle: DELETE前不需SELECT判断记录是否存在,INSERT前不需SELECT判断是否有若干字段值重复的记录。
- 判断某个条件的记录是否存在
- Oracle中判断表是否存在!
- Oracle中判断表是否存在
- Oracle中判断表是否存在!
- oracle 判断值中是否存在汉字
- sql中存储过程中判断记录是否存在时
- Oracle判断表是否存在的函数
- mysql中判断记录是否存在方法比较
- java sql ResultSet 如何判断ResultSet中存在记录
- android点滴
- Dalvik指令格式
- mapreduce
- Additional Include Directories 与 Include Directories的区别
- Android:Fresco体验(一):Android Studio导入Fresco
- oracle中记录存在性的判断
- Spring JdbcTemplate 查询方法中的RowMapper实现汇总
- AlarmManager
- 数据结构绪论
- 小问题
- 在JSP里使用CKEditor和CKFinder
- Nginx 配置 location 总结及 rewrite 规则写法
- CGRect_获取控件的高,宽,x,y等简便方法
- Android 5.0 屏蔽Home键