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


轉自:http://blog.csdn.net/gyc1105/article/details/8063624

SQLServer中有三個關鍵字可以修改比較運算符:AllAnySome,其中SomeAny等價。 

他們作用於比較運算符和子查詢之間,作用類似Existsnot existsinnot 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而無法查詢到數據。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM