1. 程式人生 > 實用技巧 >SQLServer 中All、Any和Some用法與區別

SQLServer 中All、Any和Some用法與區別

SQLServer中有三個關鍵字可以修改比較運算子:All、Any和Some,其中Some和Any等價。

他們作用於比較運算子和子查詢之間,作用類似Exists、not exists、in、not in以及其他邏輯意義,這些語法同樣被SQLServer2000支援但是很少看到有人用它們。

官方參考文:http://technet.microsoft.com/zh-cn/library/ms187074%28SQL.90%29.aspx(建議閱讀)

set nocount on
  
use tempdb
go
  
if (object_id ('t1') is not null)drop table t1
create table t1 (n int) insert into t1 select 2 unionselect 3 if (object_id ('t2') is not null)drop table t2 create table t2 (n int) insert into t2 select 1 unionselect 2 union select 3 union select 4 -- t1表資料 2,3 -- t2表資料 1,2,3,4 -- '>all' 表示:t2表中列n的資料大於t1表中列n的資料的數,結果只有4. select * from t2 where
n > all(select n from t1 ) --4 select * from t2 where n > any(select n from t1 ) --3,4 select * from t2 where n > some(selectn from t1) --3,4 select * from t2 where n = all(select n from t1 ) --無資料 select * from t2 where n = any(select n from t1 ) --2,3 select * from t2 where
n = some(selectn from t1) --2,3 select * from t2 where n < all(select n from t1 ) --1 select * from t2 where n < any(select n from t1 ) --1,2 select * from t2 where n < some(selectn from t1) --1,2 select * from t2 where n <>all (select n from t1 ) --1,4 select * from t2 where n <>any (select n from t1 ) --1,2,3,4 select * from t2 where n <>some(select n from t1) --1,2,3,4 set nocount off

注意:

1. =any 與in 等效.
2. 如果t1中包含null資料,那麼所有All相關的比較運算將不會返回任何結果。因為t1和t2表的null的存在他們和notexists之類的比較符會有一些區別。
比如下面兩句

select * from t2 a where not exists(select1 from t1 where n>=a.n) 

select * from t2 where  n > all(select n from t1) 

他們邏輯上意義很像但是對於null的處理卻是恰恰相反,第一句會忽略子查詢的null而把t2的null同時查出來,第二句卻是忽略了t2的null同時會因為t1中的null而無法查詢到資料。