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

What is the appropriate way to use a variable?

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

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:

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