程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle數據庫基礎 >> oracle判斷表中某記錄是否存在的方法

oracle判斷表中某記錄是否存在的方法

編輯: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 ....使用改寫後的語句,多數情形下應該會有比原來的語句更好的性能。(當然, 如果你要查詢的表本身是一個單行或只有幾行記錄的表, 直接查詢應該會更好)

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved