我需要找到 SQL Server HierarchyId
列中包含的特定值。该值可以出现在任何级别。下面是一个示例代码来说明这个问题:
CREATE TABLE mytable
(
Id INT NOT NULL PRIMARY KEY,
TeamName VARCHAR(20) NOT NULL,
MyHierarchyId HIERARCHYID NOT NULL
);
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (1, 'Corporate','/1/');
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (2, 'Group A','/1/2/');
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (3, 'Team X','/1/2/3/');
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (4, 'Group B','/1/4/');
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (5, 'Team Y','/1/4/5/');
INSERT INTO mytable(Id, TeamName, MyHierarchyId)
VALUES (6, 'Team Z','/1/4/6/');
现在我想找到所有与 Id = 4 相关联的记录。这意味着记录 4、5 和 6。我可以使用这样的蛮力方法:
SELECT [M].[Id],
[M].[TeamName],
[M].[MyHierarchyId],
[M].[MyHierarchyId].ToString() AS Lineage
FROM [dbo].[mytable] AS [M]
WHERE [M].[MyHierarchyId].ToString() LIKE '%4%'
但我怀疑这会非常低效。再次,问题是我要搜索的节点的级别是事先不知道的。
感谢您的任何建议。
答案 0 :(得分:3)
您可以使用IsDescendantOf()
Select *
from mytable
Where MyHierarchyID.IsDescendantOf( (select MyHierarchyID from mytable where id=4) ) = 1
结果
Id TeamName MyHierarchyId
4 Group B 0x5C20
5 Team Y 0x5C3180
6 Team Z 0x5C3280