SQL Server 2008中WHERE子句中的日期比较的CASE语句

时间:2016-01-20 10:50:33

标签: sql sql-server-2008 case

我正在使用一个查询,其中包含WHERE子句中的CASE语句,我必须将日期列与2个变量fromDate和toDate(如果它不为空)进行比较。但SQL Server 2008在执行时会出现一些错误,例如“语法不正确'>'”。任何人都可以帮我正确的查询?这是查询:

declare 
@fromDate varchar(32)= '2015-08-04',
@toDate varchar(32) = '2016-01-04'

SELECT 
DC_MASTER.DC_NO,
PSR_LOAD_DATE_TIME,
CUS_NAME  
FROM DC_ITEM
INNER JOIN DC_MASTER ON DC_MASTER.DC_NO=DC_ITEM.DC_NO  
INNER JOIN ITEM_MASTER ON item_master.ITEM_CODE  = DC_ITEM.ITEM_CODE  
INNER JOIN  CUSTOMER_MASTER ON customer_master.CUS_CODE = DC_MASTER.CUS_CODE 
INNER JOIN LOCATION_MASTER ON location_master.LOC_CODE  = DC_ITEM.LOC_CODE 
WHERE DC_ITEM.ITEM_CODE=item_master.ITEM_CODE 
AND CASE 
WHEN @fromDate IS NOT NULL AND @toDate IS NOT NULL THEN DC_MASTER.PSR_LOAD_DATE_TIME >= @fromDate and PSR_LOAD_DATE_TIME <= @toDate
END 

3 个答案:

答案 0 :(得分:2)

您可以将逻辑重写为:

WHERE DC_ITEM.ITEM_CODE=item_master.ITEM_CODE 
AND (@fromDate IS NULL OR @toDate IS NULL
     OR (DC_MASTER.PSR_LOAD_DATE_TIME >= @fromDate 
         and PSR_LOAD_DATE_TIME <= @toDate)
    )

答案 1 :(得分:2)

您可以轻松将其转换为正常情况,而不是案例:

declare 
@fromDate varchar(32)= '2015-08-04',
@toDate varchar(32) = '2016-01-04'

SELECT 
DC_MASTER.DC_NO,
PSR_LOAD_DATE_TIME,
CUS_NAME  
FROM DC_ITEM
INNER JOIN DC_MASTER ON DC_MASTER.DC_NO=DC_ITEM.DC_NO  
INNER JOIN ITEM_MASTER ON item_master.ITEM_CODE  = DC_ITEM.ITEM_CODE  
INNER JOIN  CUSTOMER_MASTER ON customer_master.CUS_CODE = DC_MASTER.CUS_CODE 
INNER JOIN LOCATION_MASTER ON location_master.LOC_CODE  = DC_ITEM.LOC_CODE 
WHERE DC_ITEM.ITEM_CODE=item_master.ITEM_CODE 
AND ((@fromDate IS NOT NULL AND @toDate IS NOT NULL and DC_MASTER.PSR_LOAD_DATE_TIME >= @fromDate
and PSR_LOAD_DATE_TIME <= @toDate) or @fromDate IS NULL or @toDate IS NULL)

答案 2 :(得分:2)

不需要案例表达式

注意,如果参数为null,则日期范围将不起作用,因此我的假设是,如果其中任何一个为NULL,那么您需要所有行。

SELECT
      DC_MASTER.DC_NO
    , PSR_LOAD_DATE_TIME
    , CUS_NAME
FROM DC_ITEM
      INNER JOIN DC_MASTER ON DC_MASTER.DC_NO = DC_ITEM.DC_NO
      INNER JOIN ITEM_MASTER ON item_master.ITEM_CODE = DC_ITEM.ITEM_CODE
      INNER JOIN CUSTOMER_MASTER ON customer_master.CUS_CODE = DC_MASTER.CUS_CODE
      INNER JOIN LOCATION_MASTER ON location_master.LOC_CODE = DC_ITEM.LOC_CODE
WHERE (DC_MASTER.PSR_LOAD_DATE_TIME >= @fromDate
      AND PSR_LOAD_DATE_TIME <= @toDate
      )
      OR (@fromDate IS NULL OR @toDate IS NULL)

[编辑] 顺便说一句,日期范围的最佳实践是使用&gt; =然后&lt;

当您使用&gt; =然后&lt; =时, 导致的问题完全相同。