在WHERE子句中使用case语句或IF

时间:2020-03-04 00:50:27

标签: mysql sql

我有几个存储过程几乎相同,但是在WHERE子句中有一些不同的AND部分。

基于变量deptname,我想向我现有的WHERE子句中添加其他AND / OR条件。有点像IF / CASE WHEN,不同之处。

将其视为字符串连接

query_string = 'WHERE a= XYZ AND B= 123"
if deptname = a:  query_string + "AND additional conditions for dept a"
else if deptname = b:query_string + "AND additional conditions for dept b"

使用变量的合适方法是什么?

这是我要执行的操作的伪代码

SELECT 
personID AS pid,
personcode,
persondeptcode,
more_fields AS fields
FROM
TABLE_XYZ
WHERE
--shared parts
personcode = 'C' 
AND
persondeptcode = 'MAJ'
--- NOW the different part
IF @deptname = "deptA"
AND 
(
PROGRAM_LDESCR IN 
(
    'prog1',
    'prog2',
    'prog3'
)
OR
aprogram IN ('aprogram1') 
OR 
(aprogram IN ('aprogram2') AND PLAN_LDESCR IN ('plan123'))
); 
--- THIS IS A DIFFERENT DEPT SO WE HAVE DIFFERENT AND PART 
ELSE IF @deptname = "deptB"

(
PROGRAM_LDESCR IN 
(
    '1234'
)
OR
aprogram IN ('a1234') 
);

3 个答案:

答案 0 :(得分:1)

您似乎想要类似的东西:

AND
(@deptname = 'dept123' AND (PROGRAM_LDESCR IN ('1234') OR aprogram IN ('a1234')) OR
 @deptname <> 'dept123'
)

答案 1 :(得分:1)

要合并WHERE子句的最后一部分(如果我正确理解了您的注释代码),则可以执行以下操作:

SELECT 
    personID AS pid,
    personcode,
    persondeptcode,
    more_fields AS fields
FROM
    TABLE_XYZ
WHERE
    personcode = 'C' 
    AND persondeptcode = 'MAJ'
    AND (
        (@deptname="deptA" AND (PROGRAM_LDESCR IN ('prog1', 'prog2', 'prog3') OR aprogram IN ('aprogram1') OR (aprogram IN ('aprogram2') AND PLAN_LDESCR IN ('plan123'))))
        OR
        (@deptname="deptB" AND (PROGRAM_LDESCR IN ('1234') OR aprogram IN ('a1234'))
    )

通常,如果您想实际更改WHERE语句中的值,则可以使用CASE子句过滤掉不必要的数据行和SELECT语句(我很少看到{ CASE子句之外的{1}}条语句,除非它正在执行类似复杂排序的操作。

答案 2 :(得分:1)

在这种情况下,您可以使用CASE表达式,重要的是要确保您有一个ELSE子句,以确保如果@deptname不是 带有附加条件的两个值之一:

WHERE personcode = 'C' 
  AND persondeptcode = 'MAJ'
  AND (CASE @deptname 
       WHEN "deptA" THEN PROGRAM_LDESCR IN ('prog1', 'prog2', 'prog3')
                      OR aprogram IN ('aprogram1') 
                      OR aprogram IN ('aprogram2') AND PLAN_LDESCR IN ('plan123')
       WHEN "deptB" THEN PROGRAM_LDESCR IN ('1234')
                      OR aprogram IN ('a1234')
       ELSE 1
       END)

Here是以此方式使用的CASE表达式的简单演示。