where子句中的case语句 - SQL Server

时间:2012-01-04 17:11:31

标签: sql sql-server

我正在尝试在我的SQL查询的where子句中添加case或if语句 我有一个旅程时间表,其中包含开始和结束日期,以及每天的布尔字段,表示当天旅程发生的位置。这是我到目前为止所做的,但我得到的语法错误不正确:

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 

3 个答案:

答案 0 :(得分:47)

case语句中不需要where,只需使用括号和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
)

此外,您的语法错误。它不会向字符串附加内容 - 它返回单个值。如果你真的要使用case语句(你不应该这样做),你会想要这样的东西:

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 

只是为了额外的umph,您可以使用between运算符作为您的日期:

where @Date between StartDate and EndDate

进行最终查询:

select
    * 
from 
    Times
where
    @Date between StartDate and EndDate
    and (
        (@day = 'Monday' and Monday = 1)
        or (@day = 'Tuesday' and Tuesday = 1)
        or Wednesday = 1
    )

答案 1 :(得分:5)

只需执行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))

答案 2 :(得分:1)

CASE语句是一个表达式,就像布尔比较一样。这意味着'AND'需要在'CASE'语句之前,而不是在其中。:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)

AND -- Added the "AND" here

CASE WHEN @day = 'Monday' THEN (Monday = 1)   -- Removed "AND" 
    WHEN @day = 'Tuesday' THEN (Tuesday = 1)  -- Removed "AND" 
    ELSE AND (Wednesday = 1) 
END