2017-04-08 3 views
0

아래 코드에서 변수의 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 
+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 

예컨대

이 값은 변수가 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) 
관련 문제