简体   繁体   English

许多条件取决于 WHERE 子句中的 IF 子句

[英]Many conditions depends on IF clause within WHERE clause

How can I implement a WHERE clause that depends on one @value condition, like that pseudocode below:如何实现依赖于一个@value条件的WHERE子句,如下面的伪代码:

Select * from table
WHERE
IF(@value is not null) 
    Id > 10 and Name = 'example' and Address is not null and ... etc
ELSE 
    Email is not null

As you've seen you can't use an if like that, but you can create the desired behavior using the and and or logical operators:如您所见,您不能像这样使用if ,但您可以使用andor逻辑运算符创建所需的行为:

SELECT *
FROM   table
WHERE  (@value IS NOT NULL AND 
        id > 10 AND 
        name = 'example' AND 
        address IS NOT NULL AND -- etc...) OR
       (@value IS NULL AND email IS NOT NULL)

You want return records with email is not null only when @value is null .仅当@valuenull时,您才希望返回email不是 null 的记录。
You need to specify "precondition" for both "branches" of "if.. else" in your example.您需要在示例中为“if.. else”的两个“分支”指定“前提条件”。

SELECT *
FROM Table
WHERE (@value IS NOT NULL AND Id > 10 AND ....)
    OR (@value IS NULL AND Email IS NOT NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM