I have a stored procedure that was created by someone else. In the WHERE
clause, there is a CASE expression that I am having a hard time to understand:
DECLARE
@DateFrom datetime = '01-01-2016',
@DateTo datetime = '12-31-2016'
@EffDateFrom datetime = NULL,
@EffDateTo datetime = NULL,
/* SOME SELECT statement here */
WHERE
CASE WHEN @EffDateFrom IS NULL THEN 1
ELSE CASE WHEN dateDiff(d, '01-01-2016', dbo.tblQuotes.EffectiveDate) >= 0
AND dateDiff(d, EOMONTH (GETDATE()), dbo.tblQuotes.EffectiveDate) <= 0 Then 1
else 0
end
END = 1
--------------/* This is where I am confused */--------------------------------
AND CASE WHEN @DateFrom IS NULL THEN 1 ELSE
CASE WHEN INV.InvoiceDate > INV.EffectiveDate THEN
CASE WHEN dateDiff(d, '01-01-2016', INV.InvoiceDate) >= 0
AND dateDiff(d, '12-31-2016', INV.InvoiceDate) <= 0 Then 1 else 0 end
ELSE
CASE WHEN dateDiff(d, '01-01-2016', INV.EffectiveDate) >= 0
AND dateDiff(d, '12-31-2016', INV.EffectiveDate) <= 0 Then 1 else 0 end
END
END = 1
So what we saying here is:
When Parameter @DateFrom is null, then use parameter @EffDateFrom, is that right?
But if its not null, then
1.check if InvoiceDate greater than EffectiveDate, and if it is - then
2.check if the number of days between 01-01-2016
and InvoiceDate is greater or equal to 0 AND
if the number of days between 12-31-2016
and InvoiceDate less or equal to 0 then 1!! what is 1? meaning the record is valid? The record will be in a table? Correct?
And ELSE 0
meaning it will NOT pick the record, correct?
After that I am confused. Updated the understanding ( if its correct):
CASE WHEN @DateFrom IS NULL THEN 1 ELSE
CASE WHEN INV.InvoiceDate > INV.EffectiveDate THEN
-----------------------------/*then check the below conditions and if its 1 then display the record if its 0 then do NOT */
CASE WHEN dateDiff(d, '01-01-2016', INV.InvoiceDate) >= 0
AND dateDiff(d, '12-31-2016', INV.InvoiceDate) <= 0 THEN 1 ELSE 0
END
----------------------------/* and this statement will only be working if parameter @EffDateFrom is not null. Correct? */
ELSE
CASE WHEN dateDiff(d, '01-01-2016', INV.EffectiveDate) >= 0
AND dateDiff(d, '12-31-2016', INV.EffectiveDate) <= 0 Then 1 else 0 end
END
END = 1
This is the logic (of the part you asked):
The whole statement: