掌握 SQL Server 2008 新增的 HierarchyID 系統資料類型,以高效方式建模、查詢與操作樹狀結構資料(組織架構、目錄分類、BOM 物料清單等)。
GetAncestor()、GetDescendant()、IsDescendantOf()、GetLevel()、ToString()、Parse() 等。Node hierarchyid PRIMARY KEY。@parent.GetDescendant(@lastChild, NULL) 自動計算新節點編碼。WHERE Node.IsDescendantOf(@root) = 1。CREATE TABLE OrgChart
(
Node hierarchyid PRIMARY KEY,
EmployeeID int UNIQUE,
Name nvarchar(50),
Title nvarchar(50)
);
-- 建立深度優先索引
CREATE INDEX IX_OrgChart_DepthFirst ON OrgChart (Node);
-- 插入根節點
INSERT INTO OrgChart (Node, EmployeeID, Name, Title)
VALUES (hierarchyid::GetRoot(), 1, 'CEO', 'Chief Executive Officer');
-- 插入子節點
DECLARE @parent hierarchyid = (SELECT Node FROM OrgChart WHERE EmployeeID = 1);
DECLARE @lastChild hierarchyid = (SELECT MAX(Node) FROM OrgChart WHERE Node.GetAncestor(1) = @parent);
INSERT INTO OrgChart (Node, EmployeeID, Name, Title)
VALUES (@parent.GetDescendant(@lastChild, NULL), 2, 'CTO', 'Chief Technology Officer');
HierarchyID 以 O(log n) 複雜度完成祖先/子樹查詢,儲存空間隨樹深線性增長,是 SQL Server 內建處理階層資料的最佳選擇。