2017-04-08 166 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)