2012-10-18 36 views
2

所以我有以下查詢奇SQL結果

Select id, [First], [Last] , [Business] as contactbusiness, (Case When ([Business] != '' or [Business] is not null) 
     Then [Business] Else 'No Phone Number' END) from contacts 

結果看起來像

id First Last contactbusiness (No column name) 
2 John Smith  
3 Sarah Jane 0411 111 222 0411 111 222 
6 John Smith 0411 111 111 0411 111 111 
8     NULL   No Phone Number 
11 Ryan B  08 9999 9999 08 9999 9999 
14 David F  NULL   No Phone Number 

我期望記錄2也顯示沒有電話號碼

如果我改變「[業務]不爲空」to [商業]!= null然後我得到正確的結果

id First Last contactbusiness (No column name) 
2 John Smith     No Phone Number 
3 Sarah Jane 0411 111 222 0411 111 222 
6 John Smith 0411 111 111 0411 111 111 
8     NULL   No Phone Number 
11 Ryan B  08 9999 9999 08 9999 9999 
14 David F  NULL   No Phone Number 

通常情況下,您需要使用非空而不是!= null。這裏發生了什麼?

+0

只是爲了讓你知道,我更新我的回答解釋爲什麼'[商家]!= null'工作 – Manatherin

+0

我的回答可能是第一,但@Manatherin比我更詳細地解釋瞭如何解決問題(以比我更優雅的方式),而且還解釋了你在第二種情況下得到的奇怪結果。所以我建議將接受轉換爲他的答案。另外,我需要學會避免反對我自己的興趣:)。 –

+0

感謝您的詳細信息。我只記得我可以使用isnull([Business],'')!=''。不知道哪種方式更好地執行 –

回答

2

你的邏輯,如前所述,是關閉的。你可以使用

SELECT id, [First], [Last] , [Business] AS contactbusiness, 
    COALESCE(NULLIF([Business], ''), 'No Phone Number') 
FROM contacts 

SQL這是一個有點更簡潔

原因爲何If i change the "[Business] is not null" to [Business] != null then i get the correct results作品是[Business] != null永遠是假的。

如上所述,SQL使用is運算符檢查空值,並且空值的相等比較總是失敗(使用select 'hi' where (null = null)select 'hi' where (null != null)進行實驗)。使用您的OR statment和短路的意思是:

  1. 當電話號碼是存在的首要條件[Business] != ''是真實的。所以OR表述爲真,並且使用電話號碼
  2. 當第一個條件失敗時,第二個條件[Business] != null也是錯誤的。所以OR陳述是錯誤的和「沒有電話號碼」顯示
+0

+1,我真的很喜歡'COALESCE(NULLIF(...),...)'組合。十分優雅。 –

+0

@BenLee Cheers,雖然我不得不承認,但是我不久前就偷走了另一個SO問題。 – Manatherin

3

你需要在有條件使用AND,不OR:因爲你使用的底片

[Business] != '' and [Business] is not null 

這是令人困惑的。我只是翻轉了整個情況和使用陽性(在這種情況下,你可以使用OR):

(Case When ([Business] == '' or [Business] is null) 
    Then 'No Phone Number' Else [Business] END) 
+0

正確的,我想變量不是sql –

2

你的邏輯是錯誤的。您需要使用一個檢查兩個否定時:

Case When ([Business] != '' AND [Business] is not null