Skip to content
Advertisement

CASE Statement in WHERE Clause SQL Server

I’m having trouble sorting this out. I want to see the fiscal quarters for Date_Received. When the @ReviewPeriodQuarter = 1 then I want the Date_Received months 10,11,12. If @ReviewPeriodQuarter = 2 then I want the Date_Received months 1,2,3 etc. SQL Server doesn’t like the BETWEEN part of this. Thanks

DECLARE @ReviewPeriodQuarter Int

SELECT * FROM Table
WHERE
        MONTH(Date_Received) =
        CASE 
            WHEN @ReviewPeriodQuarter = 1 THEN BETWEEN 10 AND 12 
            WHEN @ReviewPeriodQuarter = 2 THEN BETWEEN 1 AND 3 
            WHEN @ReviewPeriodQuarter = 3 THEN BETWEEN 4 AND 6 
            WHEN @ReviewPeriodQuarter = 4 THEN BETWEEN 7 AND 9 
        END 

Advertisement

Answer

You can either do it with more parameters like Larnu or you can use your original method but tweaked

DECLARE @ReviewPeriodQuarter INT

SELECT *
FROM Table
WHERE MONTH(Date_Received) BETWEEN 
CASE 
    WHEN @ReviewPeriodQuarter = 1 THEN 10
    WHEN @ReviewPeriodQuarter = 2 THEN 1
    WHEN @ReviewPeriodQuarter = 3 THEN 4
    WHEN @ReviewPeriodQuarter = 4 THEN 7
END 
AND 
CASE 
    WHEN @ReviewPeriodQuarter = 1 THEN 12
    WHEN @ReviewPeriodQuarter = 2 THEN 3
    WHEN @ReviewPeriodQuarter = 3 THEN 6
    WHEN @ReviewPeriodQuarter = 4 THEN 9
END 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement