2017-04-08 22 views
0

以下のコードでは、where句に2つの日付比較があり、変数のNULL値を許容するCASE文に変更する必要があります。 @StartDate変数がNULLの場合、StartDate値に関係なくすべての行を選択する必要があります。 @StartDateがnullでない場合は、StartDate> = @StartDateのすべての行を選択する必要があります。where文節でSQLのcase文を使用すると助けが必要です

その他の問題は、Where句のLotCodeにあります。ステートメントはそのまま正常に動作しますが、@LotCodeがnullの場合、LotCodeのNULL値は返されません。

ご協力いただければ幸いです。 @EndDateに同じ

... >= (Case when @StartDate is null then h.createtime else @StartDate end) 

:あなたはまだあなたがそれを修正する必要があるケースを使用する場合は

and coalesce(h.createtime, @StartDate) >= @StartDate 
and coalesce(h.createtime, @EndDate) <= @EndDate 

:あなたはCOALESCE functionの代わりに、このようなCASEを使用することができます

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

+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) 
関連する問題