lets assume you have this table:
CREATE TABLE Hierarchy
(
CompanyNode hierarchyid NOT NULL,
CompanyId int NOT NULL,
NodeLevel AS CompanyNode.GetLevel()
CONSTRAINT PK_Hierarchy PRIMARY KEY NONCLUSTERED (CompanyNode)
)
and you populate it so it hold this data:
CompanyNode CompanyId NodeLevel
0x 1 0
0x58 2 1
0x5AC0 3 2
0x68 100 1
0x6AC0 101 2
0x6AD6 1000 3
0x6AD6B0 10000 4
0x78 20 1
0x7AC0 200 2
0x7AD6 2000 3
0x7AD6B0 20000 4
0x7AD6B580 200000 5
0x7AD6D0 20001 4
0x7ADA 2001 3
0x7ADE 2002 3
0x7B40 201 2
0x7BC0 202 2
and now you want to get all the parents of CompanyId 20001, this is how I did it:
DECLARE @currentLevel smallint
SELECT @currentLevel = NodeLevel
FROM Hierarchy
WHERE CompanyId = 20001;
with tree([Path], [PathName], CompanyId, [Level])
AS
(
SELECT h.CompanyNode AS [Path],
h.CompanyNode.ToString() AS [PathName],
h.CompanyId,
@currentLevel AS [Level]
FROM Hierarchy h
WHERE h.CompanyId = 20001
UNION ALL
SELECT h.CompanyNode AS [Path],
h.CompanyNode.ToString() AS [PathName],
h.CompanyId,
CAST((t.[Level] - 1) AS smallint) AS [Level]
FROM Hierarchy h
INNER JOIN tree t ON
t.[Path].GetAncestor(1) = h.CompanyNode
WHERE h.[NodeLevel] > 0
)
SELECT * FROM TREE
order by [Path]
you can change the recursive part of the CTE and not filter the top most node of the tree.
hope this helps,
Oded