简体   繁体   English

根据输入参数添加/删除where子句条件

[英]Add/Remove where clause conditions based on Input Parm

How can I add/remove an "And" condition from Where clause based on Input parameter? 如何基于Input参数从Where子句添加/删除“ And”条件?

If InpParm = "A" then
    Select * from Table1
           Where Field1 = "AAA"
             And Field2 = "BBB"
             And Field3 = "CCC"  

If InpParm = "B" then
    Select * from Table1
           Where Field1 = "AAA"
             And Field3 = "CCC"  

Can this be done by case statement. 可以通过案例陈述来完成。

You can create the same behavior with a series of logical operators: 您可以使用一系列逻辑运算符来创建相同的行为:

SELECT *
FROM   table1
WHERE  (inpparm = 'A' AND field1 = 'AAA' AND field2 = 'BBB' AND field3 = 'CCC') OR
       (inpparm = 'B' AND field1 = 'AAA' AND field3 = 'CCC')

Note that since the conditions on field1 and field3 are identical, they could be extracted outside the or : 请注意,由于field1field3的条件相同,因此可以在or之外提取它们:

SELECT *
FROM   table1
WHERE  field1 = 'AAA' AND
       field3 = 'CCC' AND
       ((inpparm = 'A' AND field2 = 'BBB') OR (inpparm = 'B'))
SELECT *
FROM
    Table1
WHERE
    Field1 = 'AAA'
    AND Field3 = 'CCC'
    AND ((InpParm = 'A' AND Filed2 = 'BBB') or InpParm = 'B')

Mureinik was on the money as far as how your criteria can be combined but there is one fairly big issue with which is the final line of criteria needs to be in parenthesis because AND has a higher level of precedence than OR . 就如何将您的条件进行组合而言,Murienik一直在赚钱,但是有一个相当大的问题是,必须在括号中加上条件的最后一行,因为AND的优先级比OR So without wrapping the last statement in parenthesis the statement would have evaluated the all of the criteria of the ANDs together and then simply said OR InpParm = 'B' which would mean you could get Field1/2/3 results other than what was desired. 因此,如果不将最后一个语句括在圆括号中,则该语句将对AND的所有条件进行评估,然后简单地说OR InpParm = 'B' ,这意味着您可以获得除期望值以外的Field1/2/3结果。

You could also note if InpParam can only have the values of 'A' OR 'B' then you wouldn't actually need the InpParm = 'A' either but for good measure I have added it. 您还可能会注意到,如果InpParam仅具有'A''B'值,那么您实际上也不需要InpParm = 'A' ,但出于很好的考虑,我已经添加了它。

And just because you specifically asked about whether it could be done in a case expression the answer is yes you can do whatever you want in a case expression it just isn't necessary for this particular case . 只是因为您特别问过是否可以在case表达式中完成,答案是是的,您可以在case表达式中做任何您想做的事情,但这对于这种特殊情况来说是不必要的

SELECT *
FROM
    Table1
WHERE
    (CASE
       WHEN InpParm = 'A' AND Field1 = 'AAA' AND Field2 = 'BBB' AND Field3 = 'CCC' THEN 1
       WHEN InpParm = 'B' AND Field1 = 'AAA' AND Field2 = 'CCC' THEN 1
       ELSE 0
    END) = 1

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

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