2017-06-15 62 views
0

我想弄清楚如何在多個條件下執行SQL Server CASE命令。具有多個條件的SQL Server CASE

我試圖使用條件

If column_a = 'test' AND column_b IS NULL OR (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK' 
ELSE 'CHECK' 
END 

那麼打破什麼,我想說的是:

If column_a = 'test' AND column_b IS NULL return 'OK' 
OR If column_a = 'test' AND (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK' 

所以我寫的語句是

CASE WHEN column_a = 'test' AND column_b IS NULL OR (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK' 
ELSE 'CHECK' 
END 

我沒有收到任何錯誤,只是沒有得到預期的結果。這是SQL Server中的多個AND OR語句的正確順序嗎?

感謝您的任何幫助,您可以提供

回答

1

試試這個:

case 
    when column_a = 'test' 
    and (column_b is null 
     or 
     (column_b is not null and column_c = column_d)) 
     or column_e >=480 
     then 'OK' 

或顯示一些示例數據和預期的結果,所以我們可以得到一個更好地瞭解其做

+0

謝謝dbajr - 我試過了,它爲我工作。非常感激。 – spittingfire

1

我會分解它有點不同。我建議是這樣的:

CASE 
    WHEN column_a='test' AND column_b IS NULL 
    THEN 'OK' 
    WHEN column_a = 'test' AND (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 
    THEN 'OK' 
    ELSE 'CHECK' 
END 
+0

感謝聯發你的建議有用非常讚賞 – spittingfire