Skip to content
Advertisement

Using case statement or IF inside a WHERE clause

I have several stored procedures that are almost identical but have some different AND parts inside a WHERE clause.

Based on a variable deptname, I want to add additional AND/OR conditions to my already existing WHERE clause. So kind of like IF/CASE WHEN on the part that is different.

Think about it as string concatenation

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"

What is the appropriate way to use a variable?

here is some pseudo code of what I am trying to do

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') 
);

Advertisement

Answer

You can use a CASE expression in this case, the important thing is to make sure you have an ELSE clause to ensure the expression remains true if @deptname is not one of the two values with extra conditions:

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 is a simple demo of a CASE expression used in this fashion.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement