I’m trying to add a case or if statement in the where clause of my SQL query.
I have a table of journey times with a start and end date, and a boolean field for each day to signify where the journey happens on that day. Here is what I have so far, but I’m getting incorrect syntax errors:
declare @date datetime
set @Date = '05/04/2012'
declare @day nvarchar(50)
set @day = 'Monday'
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
CASE WHEN @day = 'Monday' THEN
AND (Monday = 1)
WHEN @day = 'Tuesday' THEN
AND (Tuesday = 1)
ELSE
AND (Wednesday = 1)
END
You don’t need
casein thewherestatement, just use parentheses andor:Additionally, your syntax is wrong for a case. It doesn’t append things to the string–it returns a single value. You’d want something like this, if you were actually going to use a
casestatement (which you shouldn’t):And just for an extra umph, you can use the
betweenoperator for your date:Making your final query: