2017-04-08 117 views
0

在下面的代码中,我在where子句中有2个日期比较,我需要将其更改为允许变量为NULL值的CASE语句。当@StartDate变量为空时,应该选择所有行,而不管StartDate的值如何。如果@StartDate不为空,那么应该选择StartDate> = @StartDate的所有行。我需要帮助在where子句中使用SQL case语句

另一个问题与Where子句中的LotCode有关。该语句按原样正常工作,但@LotCode为空时,它不返回LotCode的空值。

任何帮助将不胜感激。

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 
+0

如果您的SQL查询是动态的,那么你可能想使用[存储过程/ SQL命令(https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in -sql-server /) –

回答

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

+0

非常感谢!我能够得到它的工作。 –

0

您所有的case声明这与你想要的相反。
代替

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

使用

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

例如

Case @LotCode when null then LotCode else @LotCode End 

当变量不是NULL时,或者当变量为NULL时,它将与变量进行比较。这与使用coalesce(@LotCode, LotCode)相同。

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

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)