where子句中的case語句 - SQL Server

[英]case statement in where clause - SQL Server


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:

我正在嘗試在我的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 个解决方案

#1


47  

You don't need case in the where statement, just use parentheses and or:

你在where語句中不需要case,只需使用括號和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):

此外,您的語法錯誤的情況。它不會向字符串附加內容 - 它返回單個值。如果你真的要使用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 

And just for an extra umph, you can use the between operator for your date:

只需要額外的umph,您可以使用Between運算符作為您的日期:

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
    )

#2


5  

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))

#3


1  

A CASE statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/01/04/3def01ff2b052e8d7396cd18fb443b36.html



 
  © 2014-2022 ITdaan.com 联系我们: