在下面的代码中,我在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 /) –