Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 层次表和最大级别_Sql Server 2008_C# 4.0_Common Table Expression_Hierarchical - Fatal编程技术网

Sql server 2008 层次表和最大级别

Sql server 2008 层次表和最大级别,sql-server-2008,c#-4.0,common-table-expression,hierarchical,Sql Server 2008,C# 4.0,Common Table Expression,Hierarchical,我在sql中使用以下函数来获取节点的级别,但目前我的节点已超过20000个,因此运行此函数需要50秒,如何优化它 WITH cteLevels AS ( SELECT TopicId ,ParentId ,1 AS [Level] FROM Accounting.Topics WHERE parentId = 0 UNION ALL SELECT Accounting.Topics.topicId ,Accounting.Topics.Par

我在sql中使用以下函数来获取节点的级别,但目前我的节点已超过20000个,因此运行此函数需要50秒,如何优化它

   WITH cteLevels
AS
(
SELECT
  TopicId
  ,ParentId

  ,1        AS [Level]
FROM   Accounting.Topics
WHERE parentId = 0 


UNION ALL

SELECT
  Accounting.Topics.topicId
  ,Accounting.Topics.Parentid
   ,[Level] + 1 AS [Level]
 FROM   Accounting.Topics

       INNER JOIN cteLevels
         ON ( Accounting.Topics.ParentId = cteLevels.TopicID ) 

)

-- Viewing Data
SELECT
  *
FROM   cteLevels

对于此类查询,节点/行的数量不太重要。在我看来,对于递归查询来说,最重要的是级别数。在您的案例中,最大级别数是多少?为什么您使用
SELECT*FROM cteLevels
而您没有过滤器
SELECT*FROM cteLevels,其中Topic=@param
(例如)?我知道获取最大级别应该更改为:SELECT max(level)FROM cteLevels,但问题是该算法的性能太慢了!!需要50秒。我会添加一个过滤器(
WHERE
子句)。对于
,请从cteLevels中选择*,其中…
。您应该将在
Accounting.Topics
上创建的索引添加到此问题。实际执行计划是什么?注意:一个算法不能是呆板的,可以是最优的,次优的,等等。