2012-09-22 76 views
1

我需要在where子句中實現。在SQL Server 2008的where子句中使用if-else

我試着在case聲明,但之間不能case語句中使用

where 
    if start_mth < end_mth 
     mth_no between start_mth and end_mth 
    else start_mth > end_mth 
     mth_no between start_mth and 12 
         or 
     mth_no between 1 and end_mth 
+1

看起來像你的條件是不正確的,因爲它使用相同的start_mth AnandPhadke

+0

無論如何,您無法使用其他條件爲「else start_mth> end_mth」的條件。 – Geethanga

+0

如果你確實需要一個「if-else」,那麼你應該使用start_mth> = end_mth。因爲如果你沒有使用它,那麼=就會丟失,如果值相等,查詢就會中斷。如果你不需要它,那麼你需要一個「if-else if」而不是「if-else」 –

回答

1
where 
((start_mth<end_mth) and (mth_no between start_mth and end_mth)) or 
((start_mth>end_mth) and ((mth_no between start_mth and 12) or (mth_no between 1 and end_mth))) 
1
WHERE 
(start_mth < end_mth AND mth_no BETWEEN start_mth and end_mth) 
OR 
(start_mth >= end_mth AND 
    (mth_no BETWEEN start_mth AND 12 
     OR mth_no BETWEEN 1 AND end_mth))