我需要帮助在where子句中使用SQL case语句

时间:2017-04-08 23:47:01

标签: sql-server

在下面的代码中,我在where子句中有2个日期比较,我需要将其更改为允许变量为NULL值的CASE语句。当@StartDate变量为null时,无论StartDate值如何,都应选择所有行。如果@StartDate不为null,则应选择StartDate> = @StartDate的所有行。

另一个问题是Where子句中的LotCode。该语句可以正常工作,但是当@LotCode为null时,它不会返回LotCode的NULL值。

非常感谢任何帮助。

declare @StartDate datetime
declare @EndDate datetime
declare @ItemNumber varchar(50)
declare @LotCode varchar(50)

set @StartDate = '12-25-2016'
set @Enddate = '03-08-2017'
set @ItemNumber = NULL
set @LotCode = NULL


SELECT h.[CreateTime] 
      ,h.[SubmitTime]
      ,h.[CreateUserName]
      ,h.[TransactionCode]
      ,h.[TransferOrderCode]
      ,u.[ItemCode]
      ,u.[LotCode]
      ,u.[FromSiteCode]
      ,u.[ToSiteCode]
      ,u.[ToBinCode]
      ,u.[TransferQuantity]


  FROM GP7_TrxSiteTransfer h
  left join GP7_TrxSiteTransferUnit u
       on h.oid = u.TrxSiteTransferOid

where transactionstatus = '4'

and h.createtime >= @StartDate
-- I would like to replace the above statement with a comparison that allows for the variable to be null and select all values of EndDate.... tried the below line but it doesn't work
--and h.createtime >= (Case @StartDate when null then @StartDate else h.createtime end)  

and h.createtime <= @EndDate
-- I would like to replace the above statement with a comparison that allows for the variable to be null and select all values of EndDate.... tried the below line but it doesn't work
--and h.createtime <= (Case @EndDate when null then @EndDate else h.createtime end) 

and u.ItemCode = (Case @ItemNumber when null then @ItemNumber else ItemCode End)

and u.LotCode = (Case @LotCode when null then @LotCode else LotCode End)     -- I need to change this statement to select all values of LotCode including NULL.  Right now it includes all non-null values

order by h.createtime

3 个答案:

答案 0 :(得分:0)

您可以使用COALESCE function代替CASE,如下所示:

and coalesce(h.createtime, @StartDate) >= @StartDate
and coalesce(h.createtime, @EndDate) <= @EndDate

如果您仍想使用此案例,则只需修复它:

 ... >= (Case when @StartDate is null then h.createtime else @StartDate end)

@EndDate

的情况相同

答案 1 :(得分:0)

您的所有case陈述都与您想要的相反 而不是

Case @<var> when null then @<var> else <col> End

使用

Case @<var> when null then <col> else @<var> End

e.g。

Case @LotCode when null then LotCode else @LotCode End

这将在变量为NULL时与变量进行比较,或在变量为NULL时与列进行比较。这与使用coalesce(@LotCode, LotCode)相同。

以相同的方式更改日期比较也会纠正它们。

答案 2 :(得分:0)

This worked:

where transactionstatus = '4'

and (h.createtime >= @StartDate OR @StartDate IS NULL)
and (h.createtime <= @EndDate OR @EndDate IS NULL)
and (u.ItemCode = @ItemNumber or @ItemNumber IS NULL)
and (u.LotCode = @LotCode or @LotCode IS NULL)