在下面的代碼中,我在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
如果您的SQL查詢是動態的,那麼你可能想使用[存儲過程/ SQL命令(https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in -sql-server /) –