pyo*_*yon 6 sql-server query-optimization
我有一个存储过程,可以执行以下操作:
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.
Run Code Online (Sandbox Code Playgroud)
我想将查询减少到以下内容:
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
Run Code Online (Sandbox Code Playgroud)
但是,如果SQL Server评估所有情况,无论实际返回哪一个,修改后的查询都将非常低效.
因此,我想知道,SQL Server是在评估语句中的所有案例CASE,还是只评估满足CASE条件的第一个案例?
| 归档时间: |
|
| 查看次数: |
2548 次 |
| 最近记录: |