sql - SQL replace cte by actual table to improve performance?
问题描述
Table #temp
has an index on (NrBL, LgnBL)
. But in SQL Server 2016, common table expressions cannot be indexed. Could it be faster to use another temporary table instead of the CTE, and index it on (NrBL, LgnBL)
?
WITH cte (NrBL, LgnBL, clientNr) AS
(
SELECT NrBL, LgnBL, clientNr
FROM #temp
WHERE Niveau=0
)
UPDATE a
SET a.ClientNr = cte.ClientNr
FROM #temp AS a
JOIN cte ON a.NrBL=cte.NrBL AND a.LgnBL = cte.LgnBL;
解决方案
我认为带有窗口函数的可更新 CTE 是最好的方法:
WITH cte (NrBL, LgnBL, clientNr) AS (
SELECT t.*,
MAX(CASE WHEN Niveau = 0 THEN clientNr END) OVER (PARTITION BY NrBL, LgnBL) as new_clientNr
FROM #temp t
)
UPDATE cte
SET ClientNr = new_ClientNr
WHERE new_clientNR IS NOT NULL;
您可以在(NrBL, LgnBL, Niveau, clientNr)
.
推荐阅读
- javascript - 使用 gulp-tap 将延迟函数结果返回到下一个 Gulp 管道
- python - 如何为短语创建 word2vec 然后计算余弦相似度
- c# - 如何使用按钮调用另一个窗口?
- java - 使用 Java Stream 多次处理结果
- thymeleaf - th:field 忽略占位符值并设置为 0
- javascript - “TypeError:无法读取 null 的属性‘内容’”在 Jest 中运行
- python - 控制轴的标题标签颜色
- python - 如何使用 Cython 将 python 脚本转换为 Linux 独立可执行文件/二进制文件?
- java - 如何仅在线程未执行或之前未启动时启动线程,或者只应创建一个线程实例
- solr - Solr8.0.0 并非所有记录都被索引