I have a stored procedure that does something like:
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.
I would like to reduce the query to the following:
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
However, if SQL Server evaluates all the cases, regardless of which one will be actually returned, the modified query would be grossly inefficient.
Thus, I'd like to know, does SQL Server evaluate all the cases in a CASE statement, or only the first one that satisfies the CASE's condition?
CASE statements are preferred because: SQL: They are ANSI standard, making it portable to other databases without need for alteration. they support "short circuiting"
Collation Affects the Results of SQL REPLACEIt is a case-insensitive collation.
Question: What is Alternative to CASE Statement in SQL Server? Answer: IIF Function.
CASE will not always short circuit evaluates its conditions sequentially and stops with the first condition whose condition is satisfied.
SQL Server's CASE statement, as mentioned in this article, does take advantage of short-circuiting so in the example shown it will not evaluate the results of every possible CASE outcome for every row.
However, you will still get a less efficient query than your current format as you'll then be forcing all outcomes to share the same execution plan, which may not be optimal. Depending on the differences between the CASE subqueries the effect could be quite significant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With