아래 코드에서 변수의 NULL 값을 허용하는 CASE 문으로 변경해야하는 where 절에서 2 개의 날짜 비교가 있습니다. @StartDate 변수가 null이면 StartDate 값에 관계없이 모든 행을 선택해야합니다. @StartDate가 null가 아닌 경우, StartDate> = @StartDate 인 모든 행을 선택해야합니다.where 절에 SQL case 문을 사용하는 데 도움이 필요합니다.
다른 문제는 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
당신의 SQL 쿼리가 다음 동적 경우에는 [저장 프로 시저/SQL 명령 (https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in을 사용할 수 있습니다 -sql-server /) –