简体   繁体   English

WHERE子句中的CASE语句,带有!= condition

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

I'm trying to figure out how to use a case statement in a where clause (with !=), here is an idea of what I am trying to do: 我试图弄清楚如何在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

I've seen a few examples of a case statement in a where clause, but not one with a != condition. 我在where子句中看到了一些case语句的例子,但没有一个带有!=条件的例子。 Any ideas? 有任何想法吗?

A simple AND / OR combination will do: 一个简单的AND / OR组合将:

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

If I understood your question, you want to evaluate other boolean expression besides equality. 如果我理解你的问题,你想要评估除了相等之外的其他布尔表达式。 The CASE statement has two forms, the one that you're trying (always look for equality) and this other form: CASE语句有两种形式,一种是你正在尝试的(总是寻找相等)和另一种形式:

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

just use ELSE for everything else 只需将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

OR you can use the parameter inside the case, like this 或者您可以使用案例中的参数,就像这样

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