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

DECLARE @selection integer ;
DECLARE @items integer ;
DECLARE @washTypes integer ;

SET @selection = {Root Container.Selection Group.Selection Checkbox.controlValue} ;
SET @items = {Root Container.Items Group.Items Checkbox.controlValue} ;
SET @washTypes = {Root Container.Types of Wash Group.Wash Types Checkbox.controlValue} ;

SELECT

RAW_CIP_records_ndx as 'Index', 
start as 'Start', 
stop as 'End', 
total_duration as 'Total Duration', 
item as 'Item', 
wash_type as 'Type of Wash', 
operator as 'CIP Operator', 
program_complete as 'Program Fully Completed?'

FROM RAW_CIP_records

WHERE
start = (case when @selection = 1 then (BETWEEN '{Root Container.Start Date.formattedDate}' and '{Root Container.End Date.formattedDate}') else start end)
and 
item = (case when @items = 0 then 'Receiving Bay 1' when @items = 1 then 'Receiving Bay 2' when @items = 2 then 'Receiving Bay 3' else item end)
and
wash_type = (case when @washTypes = 0 then 'Regular' when @washTypes = 1 then 'Sanitize' when @washTypes = 2 then 'Acid' else wash_type end)

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

WHERE (
     @selection = 1 AND (start BETWEEN @startDate and @endDate)
  OR @selection <> 1
)

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

IF @selection = 1
    SELECT ...
ELSE
    SELECT ...
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement