2016-05-24 15 views
0
where子句中陳述

我想在where子句中檢驗一個條件Acheive如果在SQL

Select * from [Sale Master] where 
IF (@IsTime='1') 
BEGIN 
convert(char(19),Sale_Date,20) between'2016-05-18 10:45:00' and '2016-05-18 10:55:00' 
END 
ELSE 
BEGIN 
convert(char(10),Sale_Date,20) between'2016-05-18' and '2016-05-18' 
END 

什麼我其實想做的是我想基礎上,@IsTime位variable.If搜索記錄確實它應該考慮日期和時間,否則它只考慮日期。我知道IF條件不應該用在Where子句中,但我沒有關於使用CASE的任何想法。

+0

你並不真的需要大約'bit'值引號。 – Tanner

回答

0

試試這個:

Select * 
from [Sale Master] 
where 
(
    (@IsTime=1) 
    and 
    convert(char(19),Sale_Date,20) between '2016-05-18 10:45:00' and '2016-05-18 10:55:00' 
) 
or   
(
    (@IsTime=0) 
    and 
    convert(char(10),Sale_Date,20) between '2016-05-18' and '2016-05-18' 
) 
2

你並不需要一個if() - 也不是case。但更重要的是,沒有理由將日期轉換爲字符串進行比較。所以:

Select * 
from [Sale Master] 
where (@IsTime = '1' and sale_date between '2016-05-18 10:45:00' and '2016-05-18 10:55:00') or 
     (@IsTime <> '1' and Sale_Date between '2016-05-18' and '2016-05-18'); 

注:如果IsTime是一個數字,然後做了比較,沒有用引號。另外,如果值可以是NULL,那麼第二次比較需要考慮到這一點。

實際上,使用日期/時間使用between可能會很危險。我更喜歡直接的比較:

Select * 
from [Sale Master] 
where (@IsTime = '1' and sale_date >= '2016-05-18 10:45:00' and sale_date < '2016-05-18 10:55:00') or 
     (@IsTime <> '1' and Sale_Date >= '2016-05-18' and Sale_Date < '2016-05-19'); 

阿龍貝特朗具有使用between日期/次good blog post解釋的問題。

0

嘗試這樣,這有點類似於戈登Linoff後,但我刪除了一個條件。

SELECT * 
FROM [Sale Master] 
WHERE (
     @IsTime = '1' 
     AND sale_date BETWEEN '2016-05-18 10:45:00' 
      AND '2016-05-18 10:55:00' 
     ) 
    OR (
     Sale_Date BETWEEN '2016-05-18' 
      AND '2016-05-18' 
     ); 
+0

不認爲這會起作用 – Tanner

+0

@坦納:解釋一下爲什麼我能理解 – StackUser

+0

首先,無論「@ IsTime」的值如何,第二個子句都會被評估。其次,與日期檢查的條款具有相同的值,所以沒有之間。也許測試它,看看你的代碼對付虛擬數據。 – Tanner

0
IF (@IsTime='1') 
BEGIN 
    Select * from [Sale Master] 
    where convert(char(19),Sale_Date,20) between'2016-05-18 10:45:00' and '2016-05-18 10:55:00' 
END 
ELSE 
BEGIN 
    Select * from [Sale Master] 
    where convert(char(10),Sale_Date,20) between'2016-05-18' and '2016-05-18' 
END