[英]SQL If-Else in the WHERE clause with conditions based on column values
How would you rewrite the WHERE clause in this pseudo-SQL? 您将如何在此伪SQL中重写WHERE子句?
SELECT *
FROM MyTable
WHERE IF ( Col1 <> '' ) Col1 = @Val1
ELSEIF ( Col2 <> '' ) Col2 = @Val2
The correct equivalent for your pseudo code is: 伪代码的正确等效项是:
WHERE (Col1 <> '' AND Col1 = @Val1) OR
(Col1 = '' AND Col2 <> '' AND Col2 = @Val2)
This matches in priority order, first on Col1
and then on Col2
. 这按优先级顺序匹配,首先在Col1
,然后在Col2
。 It only moves on to Col2
when Col1
is an empty string. 仅当Col1
为空字符串时,它才继续移动到Col2
。
Note: This version assumes that Col1
is not NULL
. 注意:此版本假定Col1
不是NULL
。 That can easily be incorporated into the logic, if you need to support NULL
values -- especially with a little guidance on how they should be handled. 如果您需要支持NULL
值,那么可以很容易地将其合并到逻辑中-尤其是在有关如何处理它们的一些指导方面。
Well, it is possible to do something like this using the CASE function: 好吧,可以使用CASE函数执行以下操作:
SELECT *
FROM MyTable
WHERE 1 = CASE WHEN Col1 <> '' THEN CASE WHEN Col1 = @Val1 THEN 1 END
WHEN Col2 <> '' THEN CASE WHEN Col2 = @Val2 THEN 1 END
END
A case function returns a value. 案例函数返回一个值。 So, when 1 = 1, the condition is met. 因此,当1 = 1时,满足条件。 Since the ELSE parts of the case are left out, NULL is returned by the case when the condition is not met. 由于情况的ELSE部分被忽略,因此不满足条件的情况将返回NULL。 Since 1 = null can never be true, the WHERE condition will not be met. 由于1 = null永远不可能为真,因此将不满足WHERE条件。
Sometimes the extra complexity added by code like this is not warranted - it would be up to your exact situation after checking for performance etc. 有时,这样的代码所增加的额外复杂性是不必要的-在检查性能等之后,这将取决于您的实际情况。
EDIT: added ELSE parts. 编辑:添加了其他部分。 These are not needed, but might make it clearer for some. 这些不是必需的,但对于某些人来说可能更清楚。
SELECT *
FROM MyTable
WHERE 1 = (CASE WHEN Col1 <> '' THEN (CASE WHEN Col1 = @Val1 THEN 1 ELSE 0 END)
WHEN Col2 <> '' THEN (CASE WHEN Col2 = @Val2 THEN 1 ELSE 0 END)
ELSE 0
END)
Assuming that I understood your logic correctly. 假设我正确理解了您的逻辑。 You want to match on either col1 = @val1 or col1 is a blank string OR col2 = @val2 or col2 is a blank string. 您要在col1 = @ val1或col1是空白字符串或col2 = @ val2或col2是空白字符串上进行匹配。
SELECT *
FROM MyTable
WHERE (Col1 = @Val1 OR Col1 = '' )
OR (Col2 = @Val2 OR Col2 = '')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.