提高 20k 行执行时间的性能

Improve Performance of execution time on 20k rows

我在 20k 行上使用以下代码,需要 3 分钟, 我该如何改进它?

;WITH  abcd
        AS (
              -- anchor
            SELECT  topicid, [Description], ParentID,topicgroupfk, topicgroupfk AS "GROUPFK",
                    CAST(([Description]) AS VARCHAR(1000)) AS "Path"
            FROM    accounting.topics
            WHERE   ParentId='0' and FinancialPeriodFK=1
            UNION ALL
              --recursive member
            SELECT  t.topicid, t.[Description], t.ParentID,t.topicgroupfk,a.GROUPFK AS "GROUPFK",
                    CAST((a.path + '/' + t.Description) AS VARCHAR(1000)) AS "Path"
            FROM    accounting.topics AS t
                             JOIN abcd AS a
                      ON t.ParentId = a.topicid
                         where t.FinancialPeriodFK=1
           )
SELECT *  FROM abcd where parentid>=0
  • [ParentId] 的数据类型是什么?

我敢打赌(希望)它是一个 int 或 bigint。因此,您可以在此处删除引号和隐式转换:

WHERE   ParentId='0'
  • [描述]的数据类型是什么?

如果它已经是 varchar(1000),您可以删除 2 cast as varchar(1000)。如果它更小,您可以考虑将其更改为 varchar(1000),然后删除 2 个强制转换。

  • 您是否有 [ParentId] 的覆盖索引(包括 [FinancialPeriodFK])以及 [FinancialPeriodFK] = 1 的 where 子句?

  • 其中不需要parentid>=0

  • [topicgroupfk] 是整数吗?

  • 您也可以尝试减小递归 CTE 的大小和范围,稍后再获取它们

    您可能只需要 CTE 中的 topicid、parentid 和路径,稍后尝试通过在主 select

  • 中对 topicid 进行额外连接来获取其他列