也许有更好的方法,但这个接缝可以完成这项工作。
declare @T table
(
ID int,
Name varchar(10),
HID HierarchyID
)
insert into @T values
(1, 'Craig', '/'),
(2, 'Steve', '/1/'),
(3, 'John', '/1/1/'),
(4, 'Sam', '/2/'),
(5, 'Matt', '/2/1/'),
(6, 'Chris', '/2/1/1/')
select *
from @T
where HID.GetDescendant(null, null) not in (select HID
from @T)
结果:
ID Name HID
----------- ---------- ---------------------
3 John 0x5AC0
6 Chris 0x6AD6
2012-05-22 更新
如果节点编号不是完整的序列,上述查询将失败。这是另一个应该解决这个问题的版本。
declare @T table
(
ID int,
Name varchar(10),
HID HierarchyID
)
insert into @T values
(1, 'Craig', '/'),
(2, 'Steve', '/1/'),
(3, 'John', '/1/1/'),
(4, 'Sam', '/2/'),
(5, 'Matt', '/2/1/'),
(6, 'Chris', '/2/1/2/') -- HID for this row is changed compared to above query
select *
from @T
where HID not in (select HID.GetAncestor(1)
from @T
where HID.GetAncestor(1) is not null)