2012-01-04 282 views
18

我想在我的SQL查詢的where子句中添加一個case或if語句。
我有一張開始和結束日期的旅程時間表,以及每天的布爾型字段來表示旅程在當天發生的地點。這裏是我到目前爲止,但我發現了不正確的語法錯誤:where語句中的case語句 - SQL Server

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 
+2

在我看來,如果你有表的一個設計問題,有沒有辦法,你應該永遠有列星期一,星期二,星期三等。您應該記住daya專欄,並填寫您想要的日期或數字值,以查找您想要的日期。如果超過一天適用,則使用相關表格。 – HLGEM 2012-01-04 17:17:49

回答

47

你並不需要在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 
) 

此外,你的語法對於一個案例是錯誤的。它不會將東西附加到字符串 - 它會返回單個值。你會想是這樣的,如果你確實要使用一個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 
    ) 
+0

謝謝埃裏克 - 這是完美的:) – 2012-01-05 09:37:26

+0

@Eric這會減慢查詢 – 2013-09-30 11:37:34

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

對我來說,這將是愚蠢的downvote你,但你可以在'where'子句中使用'case'。你不能像OP所要做的那樣使用它。 – Eric 2012-01-04 17:20:21

+1

在Microsoft SQL Server中,確實可以在'WHERE'子句中使用'CASE'。試試這個 - 解析並執行得很好(在SQL 2008 R2上):「select * from sys.tables t where case when t.schema_id = 1 then 1 else 0 end = 1」 – jklemmack 2012-01-04 17:22:17

+0

@Eric謝謝:)然後修復: P – 2012-01-04 17:22:41

1

A CASE語句是一個表達式,就像一個布爾比較。這意味着「與」需要「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 
+0

Thx用於編輯Dylan。今天早上我一定是在引導VB。 – jklemmack 2012-01-04 18:15:39

+2

嗨jklemmack,我最初嘗試過,並得到了一個「不正確的語法附近'='」的錯誤在案件陳述的第一行。當我執行這個查詢時仍然會這樣 – 2012-01-05 09:42:21