2012-09-22 81 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))