Skip to content
Advertisement

Dynamic Case Expression Based on Dates

I have a SQL query that has multiple conditions that will change the WHERE clause. I have three case expressions that dynamically update this WHERE clause. The last two case expressions are working well. However, the first one is more dynamic than the last two and I am having issues with it.

Here is the portion of the table that is applicable to this exercise (Image of Table)

I need it to work as follows: When my variable @selection = 1, I need it to sort my return based on two dates being passed in. When my variable @selection = {any other int}, I need it to return all dates.

Query with Description

WHERE
{Start Date} = (case when @selection = 1 then {return all values where Start Date is between two dates that are passed in} else {return all Start Dates})

Entire Query

I can get a simple WHERE clause to work with these two dates and the BETWEEN function. However, I can’t figure out how to pass all of this into a CASE expression.

Advertisement

Answer

You could do it a WHERE condition in one query

But I would suggest you are better off with two separate queries as it will be more likely to use an index.

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