簡體   English   中英

WHERE子句中的CASE語句,帶有!= condition

[英]CASE statement in WHERE clause with != condition

我試圖弄清楚如何在where子句中使用case語句(使用!=),這里是我想要做的事情的想法:

SELECT *
FROM Table1 JOIN Table2 JOIN Table3
WHERE 
  CASE @fruit
    WHEN 'Apples' THEN (What would go here to return only data related to apples in Table1?)
    WHEN 'Citrus' THEN (What would go here to return data related to either oranges or lemons in Table2?)
    WHEN 'Other' THEN (return all data not related to apples, oranges, or lemons from all 3 tables) (!=)
  END

我在where子句中看到了一些case語句的例子,但沒有一個帶有!=條件的例子。 有任何想法嗎?

一個簡單的AND / OR組合將:

SELECT *
FROM Table
WHERE 
    (@fruit != 'Other' AND Fruit = @fruit) OR
    (@fruit = 'Other' AND Fruit NOT IN('Apples', 'Oranges')

如果我理解你的問題,你想要評估除了相等之外的其他布爾表達式。 CASE語句有兩種形式,一種是你正在嘗試的(總是尋找相等)和另一種形式:

CASE
  WHEN <boolean expression> THEN <result expression>
  WHEN <boolean expression> THEN <result expression>
  ELSE <else expression>
END

只需將ELSE用於其他一切

SELECT *
FROM Table
WHERE 
  CASE @fruit
    WHEN 'Apples' THEN (What would go here to return only data related to apples?)
    WHEN 'Oranges' THEN (What would go here to return only data related to oranges?)
    ELSE (return all data not related to apples or oranges) (!=)
  END

或者您可以使用案例中的參數,就像這樣

SELECT *
FROM Table
WHERE 
  CASE 
    WHEN @fruit = 'Apples' THEN (What would go here to return only data related to apples?)
    WHEN @fruit = 'Oranges' THEN (What would go here to return only data related to oranges?)
    WHEN @fruit <> 'Apples'  AND @fruit <> 'Oranges'  THEN (return all data not related to apples or oranges) (!=)
  END

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM