Ho una stored procedure che fa qualcosa di simile:Sostituisce la logica condizionale con le istruzioni CASE efficienti in Transact-SQL?
IF @Param = '1'
SELECT HT.HeaderKey, HT.Description,
(SELECT SUM(E1) -- E1 is actually a complex expression
FROM DetailTable DT INNER JOIN ...
INNER JOIN ...
INNER JOIN ...
WHERE DT.HeaderKey = HT.HeaderKey)
FROM HeaderTable HT
ELSE IF @Param = '2'
SELECT HT.HeaderKey, HT.Description,
(SELECT SUM(E2) -- E2 is yet another complex expression
FROM DetailTable DT INNER JOIN ... -- Here, DetailTable is not
INNER JOIN ... -- joined to the same tables
INNER JOIN ... -- as in the first case
WHERE DT.HeaderKey = HT.HeaderKey)
FROM HeaderTable HT
-- Etc. There are five cases.
mi piacerebbe per ridurre la query al seguente:
SELECT HT.HeaderKey, HT.Description,
CASE @Param
WHEN '1'
(SELECT SUM(E1)
FROM DetailTable DT INNER JOIN ...
INNER JOIN ...
INNER JOIN ...
WHERE DT.HeaderKey = HT.HeaderKey)
WHEN '2'
(SELECT SUM(E2)
FROM DetailTable DT INNER JOIN ...
INNER JOIN ...
INNER JOIN ...
WHERE DT.HeaderKey = HT.HeaderKey)
-- Etc.
ELSE 0
END
FROM HeaderTable HT
Tuttavia, se SQL Server valuta tutti i casi , indipendentemente da quale verrà effettivamente restituito, la query modificata sarebbe gravemente inefficiente.
Così, mi piacerebbe sapere, non SQL Server valutare tutti i casi in una dichiarazione CASE
, oppure solo il primo che soddisfa la condizione s' il CASE
?
+1 per la bella domanda –
Grazie, Stephanie. – pyon