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
The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause.
Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.
The CASE statement has to be included inside the SELECT Statement. It starts with the CASE keyword followed by the WHEN keyword and then the CONDITION. The condition can be any valid SQL Server expression which returns a boolean value.
Introduction to Oracle CASE expression You can use a CASE expression in any statement or clause that accepts a valid expression. For example, you can use the CASE expression in statements such as SELECT , UPDATE , or DELETE , and in clauses like SELECT , WHERE , HAVING , and ORDDER BY .
You don't need case
in the where
statement, just use parentheses and or
:
Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
(@day = 'Monday' AND Monday = 1)
OR (@day = 'Tuesday' AND Tuesday = 1)
OR Wednesday = 1
)
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 case
statement (which you shouldn't):
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
WHEN @day = 'Tuesday' THEN Tuesday
ELSE Wednesday
END
And just for an extra umph, you can use the between
operator for your date:
where @Date between StartDate and EndDate
Making your final query:
select
*
from
Times
where
@Date between StartDate and EndDate
and (
(@day = 'Monday' and Monday = 1)
or (@day = 'Tuesday' and Tuesday = 1)
or Wednesday = 1
)
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With