我有一個由其他人創建的存儲過程。在WHERE
條款,還有的是,我有一個很難理解一個CASE表達式:如何翻譯嵌套的CASE表達式以理解邏輯?
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
所以我們在這裏說的是:
當參數@DateFrom爲null,則使用參數@EffDateFrom , 是對的嗎?
但是,如果其不爲空,然後 1,檢查InvoiceDate大於EFFECTIVEDATE,如果它是 - 然後 2.檢查是否01-01-2016
和InvoiceDate之間的天數大於或等於0 AND
如果該號碼12-31-2016
與InvoiceDate之間的天數小於或等於0,則爲1!什麼是1?這意味着記錄是有效的?記錄將在一張桌子上?正確?
而且ELSE 0
這意味着它不會接的記錄,是否正確?
之後,我很困惑。 更新的理解(如果正確):
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
OOOH !!!非常感謝你們。真棒解釋! – Oleg