CTE层次结构查询性能&索引

时间:2017-09-04 10:49:03

标签: sql-server indexing hierarchy common-table-expression sql-server-2016

我正在构建一个生成层次结构表的视图,其代码如下

with EmpTree

as
(
  select e.DWH_Dim_TFS_File_DWH_File_Guid, cast(cast(e.DWH_Dim_TFS_File_DWH_File_Guid as binary(4)) as varbinary(max)) as EmpHier,
  1 as EmployeeLevel

  from DM.Dim_TFS_File as e
  where e.DWH_Dim_TFS_File_DWH_FileParent_Guid is null
  union all
  select c.DWH_Dim_TFS_File_DWH_File_Guid, cast(p.EmpHier + cast(c.DWH_Dim_TFS_File_DWH_File_Guid as binary(4)) as varbinary(max)),
  EmployeeLevel +1 as EmployeeLevel
  from EmpTree as p
  join DM.Dim_TFS_File as c
    on c.DWH_Dim_TFS_File_DWH_FileParent_Guid = p.DWH_Dim_TFS_File_DWH_File_Guid
)

select DWH_Dim_TFS_File_DWH_File_Guid
     ,EmployeeLevel
     ,(SELECT 'File Name' from DM.Dim_TFS_File as pu where nullif(cast(substring(EmpHier, 1, 4) as int), 0) = pu.DWH_Dim_TFS_File_DWH_File_Guid) level1
     ,(SELECT 'File Name'from DM.Dim_TFS_File as pu where nullif(cast(substring(EmpHier, 5, 4) as int), 0) = pu.DWH_Dim_TFS_File_DWH_File_Guid) level2

(直到第27级)

问题是这个运行的视图有200M行,所以这个查询需要永远。

这是运行的视图,没有索引,我不能创建一个索引,因为视图不是schemabond,我无法创建它因为我没有权限这样做。

如果我在父和子列中有索引,查询性能会提高很多吗?

其次,我读到如果我在CTE的连接条款中添加TOP 100%和一个订单,性能会提高,但我不知道究竟要把它放在哪里以及应该排序的是什么。

我希望自己清楚明白,我仍然是T-SQL的新秀。

谢谢!

0 个答案:

没有答案