我们通常被要求在报告中包含某些层次结构的级别,我正在寻找一种使用 hierarchyid 提高查询性能的方法。我做了一些测试,并且我有一些有效的查询,但我认为性能可能会更好。下面是一个为给定条目提取级别 2 到 4 的示例。我想出了一种方法来使用 GetAncestor() 函数结合hierarchyid的级别。第一个查询看起来很快,但它被硬编码为只返回某个级别的行,以避免用负值破坏 GetAncestor 查询。第二个示例解决了该问题,但速度要慢得多。理想情况下,第二个选项是我想要使用的,但它不够快。
--drop table #hier
CREATE TABLE #hier
(
rec_ID int NOT NULL,
rec_NAME varchar(6),
nodeID hierarchyid NULL,
lvl AS [nodeid].[GetLevel]() PERSISTED
) ON [PRIMARY]
GO
ALTER TABLE #hier ADD CONSTRAINT
rec_ID PRIMARY KEY CLUSTERED
(
rec_ID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX IX_hier_nodeID ON #hier
(
nodeID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE #hier SET (LOCK_ESCALATION = TABLE)
GO
insert into #hier (rec_ID, rec_NAME, nodeID)
SELECT 1, 'CEO', cast('/' as hierarchyid)
union
SELECT 2, 'VP1', cast('/1/' as hierarchyid)
union
SELECT 3, 'VP2', cast('/2/' as hierarchyid)
union
SELECT 4, 'VP3', cast('/3/' as hierarchyid)
union
SELECT 5, 'Mgr1', cast('/1/1/' as hierarchyid)
union
SELECT 6, 'Mgr2', cast('/1/2/' as hierarchyid)
union
SELECT 7, 'Super1', cast('/1/2/1/' as hierarchyid)
union
SELECT 8, 'Ldr1', cast('/1/2/1/1/' as hierarchyid)
union
SELECT 9, 'Work1', cast('/1/2/1/1/1/' as hierarchyid)
union
SELECT 10, 'Work2', cast('/1/2/1/1/2/' as hierarchyid)
union
SELECT 11, 'Work3', cast('/1/2/1/1/3/' as hierarchyid)
GO
-- this runs fast but is hard coded to a level
declare @recname varchar(6)
set @recname = 'Work3'
select
x.rec_name
,x.lvl
,(select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 2) ) as l2
,(select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 3) ) as l3
,(select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 4) ) as l4
from #hier x
where x.rec_name = @recname
and x.lvl >= 4
-- this works for all levels but runs too slow
set @recname = 'Mgr2'
select
x.rec_name
,x.lvl
,case
when x.lvl >=2 then (select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 2) )
else '*N/A' end as l2
,case
when x.lvl >=3 then (select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 3) )
else '*N/A' end as l2
,case
when x.lvl >=4 then (select rec_name from #hier where nodeid = x.nodeid.GetAncestor(x.lvl - 4) )
else '*N/A' end as l2
from #hier x
where x.rec_name = @recname