2014-04-02 81 views
0

我試圖根據case語句更改where子句的條件。問題是它不喜歡'between'語句。我可以在那裏改變「Where」標準嗎?這裏是什麼導致問題(關鍵字'之間'錯誤的語法。) 我試圖從日期範圍內的PMF_FISCALCALENDAR表中獲取財年。問題是一個日期範圍可能是一個無效的數字,在這種情況下,我需要使用第二個日期。在Where子句中的案例與

關鍵詞'between'之間的語法錯誤。

,(select PERIOD = 
    CASE 
     WHEN PERIOD = '1' THEN 
      'Jan'   
     WHEN Period = '2' THEN 
      'Feb' 
     WHEN PERIOD = '3' THEN 
      'Mar' 
     WHEN Period = '4' THEN 
      'Apr' 
     WHEN PERIOD = '5' THEN 
      'May' 
     WHEN Period = '6' THEN 
      'Jun' 
     WHEN PERIOD = '7' THEN 
      'Jul' 
     WHEN Period = '8' THEN 
      'Aug' 
     WHEN PERIOD = '9' THEN 
      'Sep' 
     WHEN Period = '10' THEN 
      'Oct' 
     WHEN PERIOD = '11' THEN 
      'Nov' 
     WHEN Period = '12' THEN 
      'Dec' 

    END 

FROM PMF_FISCALCALENDAR 
WHERE 
(CASE 
    WHEN YEAR(SALESQUOTATIONLINE.KTI_SENTDATE) = 1900 Then 
      SALESQUOTATIONLINE.KTI_SENTDATE between PMF_FISCALCALENDAR.STARTDATE and PMF_FISCALCALENDAR.ENDDATE 
     ELSE 
      SALESQUOTATIONTABLE.PMF_QUOTESENTDATE between PMF_FISCALCALENDAR.STARTDATE and PMF_FISCALCALENDAR.ENDDATE 
END) 
    ) AS 'Fiscal Month Sent' 

我想使用一個或其他案例結果作爲where子句條件。 我使用的是SQL SERVER 2005

回答

3

更改語句像

WHERE 
    CASE 
     WHEN YEAR(SALESQUOTATIONLINE.KTI_SENTDATE) = 1900 Then 
       SALESQUOTATIONLINE.KTI_SENTDATE 
      ELSE 
       SALESQUOTATIONTABLE.PMF_QUOTESENTDATE 
    END between PMF_FISCALCALENDAR.STARTDATE and PMF_FISCALCALENDAR.ENDDATE 
+0

這仍然充當如果 WHEN YEAR(SALESQUOTATIONLINE。 KTI_SENTDATE)= 1900然後 SALESQUOTATIONLINE.KTI_SENTDATE 如果它的1900返回null – rigamonk

0

試試這個更好的語法和性能:

SELECT PERIOD = convert(char(3), dateadd(m, PERIOD, -1), 0) 
FROM PMF_FISCALCALENDAR 
WHERE 
    SALESQUOTATIONLINE.KTI_SENTDATE < '1901-01-01' AND 
    SALESQUOTATIONLINE.KTI_SENTDATE >= '1900-01-01' AND 
    SALESQUOTATIONLINE.KTI_SENTDATE between PMF_FISCALCALENDAR.STARTDATE and PMF_FISCALCALENDAR.ENDDATE 
or 
    (SALESQUOTATIONLINE.KTI_SENTDATE < '1900-01-01' or 
    SALESQUOTATIONLINE.KTI_SENTDATE >= '1901-01-01' or 
    SALESQUOTATIONLINE.KTI_SENTDATE is null) AND 
    SALESQUOTATIONTABLE.PMF_QUOTESENTDATE between PMF_FISCALCALENDAR.STARTDATE and PMF_FISCALCALENDAR.ENDDATE