傳統遞歸 CTE 查詢組織架構、物料清單(BOM)等階層資料雖可行,但效能與寫法複雜度隨層級增長而惡化。hierarchyId(CLR 使用者定義型別)提供原生路徑編碼、索引支援與豐富方法,大幅簡化階層操作。
/ 開頭結尾的路徑字串表示節點位置,如 /1/2/3/CREATE TABLE Employees (
Org_Id HIERARCHYID NOT NULL,
EmployeeId INT NOT NULL,
EmployeeName VARCHAR(50) NOT NULL,
Title VARCHAR(50) NOT NULL
)
GO
INSERT INTO dbo.Employees VALUES ('/', 10000, '陳希章', 'CEO');
INSERT INTO dbo.Employees VALUES ('/1/', 10001, '張三', 'CTO');
INSERT INTO dbo.Employees VALUES ('/2/', 10002, '李四', 'CFO');
INSERT INTO dbo.Employees VALUES ('/1/1/', 10003, '王五', 'IT Manager');
INSERT INTO dbo.Employees VALUES ('/1/2/', 10004, '趙六', 'Manager');
INSERT INTO dbo.Employees VALUES ('/1/1/1/', 10005, '洪七', 'Employee');

圖 1:組織架構視覺化
-- 所有員工及層級
SELECT *, Org_Id.GetLevel() AS Level FROM Employees
-- 查詢 CEO (10000) 所有下屬
DECLARE @Boss HIERARCHYID = (SELECT Org_Id FROM Employees WHERE EmployeeId = 10000)
SELECT *, Org_Id.GetLevel() AS Level
FROM Employees
WHERE Org_Id.IsDescendantOf(@Boss) = 1
-- 查詢趙六 (10004) 及其所有上級
DECLARE @Emp HIERARCHYID = (SELECT Org_Id FROM Employees WHERE EmployeeId = 10004)
SELECT *, Org_Id.GetLevel() AS Level
FROM Employees
WHERE @Emp.IsDescendantOf(Org_Id) = 1



| 方法 | 用途 | 範例 |
|---|---|---|
| GetAncestor(n) | 取得第 n 層祖先 | @h.GetAncestor(1) 取父節點 |
| GetDescendant(child1, child2) | 在兩同級節點間產生新子節點 | @parent.GetDescendant(@lastChild, NULL) 附加至末尾 |
| GetLevel() | 取得節點深度(根為 0) | @h.GetLevel() |
| GetRoot() | 取得根節點 | HIERARCHYID::GetRoot() |
| IsDescendantOf(parent) | 判斷是否為指定節點的子孫 | @child.IsDescendantOf(@parent) |
| Parse('string') | 字串轉 hierarchyId | HIERARCHYID::Parse('/1/2/') |
| GetReparentedValue(oldRoot, newRoot) | 移動子樹(變更根路徑) | @h.GetReparentedValue(@oldRoot, @newRoot) |
| ToString() | 轉回路徑字串 | @h.ToString() |
CREATE INDEX IX_Breadth ON Employees(Org_Id) — 適合「取得所有直屬下級」查詢CREATE INDEX IX_Depth ON Employees(Org_Id) WITH (DATA_COMPRESSION = PAGE) — 適合「取得整棵子樹」查詢現有 ParentId 遞歸結構可透過遞歸 CTE 一次性轉換為 hierarchyId,後續維護改用 GetDescendant / GetReparentedValue,效能與開發效率雙贏。