hierarchyid** 系統 CLR 類型,將層次結構提升為**頭等資料類型**hierarchyid:儲存 **絕對路徑位置** (如 /, /1/, /1/1/),二進制緊湊編碼0x (根)、0x58 (/1/)、0x5AC0 (/1/1/)| 方法 | 用途 | 範例 |
|---|---|---|
GetAncestor(n) | 取得第 n 層祖先 | @h.GetAncestor(1) → 父節點 |
GetDescendant(child1, child2) | 取得兩子節點間的**插入位置** | 見下文詳解 |
IsDescendantOf(@h) | 判斷是否為某節點後代 | WHERE h.IsDescendantOf(@root) = 1 |
GetLevel() | 取得節點層級 (根=0) | @h.GetLevel() |
ToString() | 二進制 → 可讀路徑字串 | /1/2/3/ |
Parse('/1/2/') | 字串 → 二進制 (靜態方法) | hierarchyid::Parse('/1/2/') |
GetReparentedValue(old, new) | 整棵子樹移動:舊路徑前綴替換為新路徑 | 移動部門至新父部門 |
| 二進制讀寫 | Read/Write(BinaryReader/Writer) | 支援 .NET 序列化 |
-- 在父節點 @parent 下新增子節點
DECLARE @lastChild hierarchyid = (
SELECT MAX(Node) FROM Org WHERE Node.GetAncestor(1) = @parent
);
DECLARE @newNode hierarchyid = @parent.GetDescendant(@lastChild, NULL);
-- @lastChild 為現有最後一個子節點,NULL 表示無下一個兄弟
-- 回傳緊隨 @lastChild 之後的空隙位置
GetReparentedValue 批量更新)目前缺乏標準 SQL 集合式操作範例 (如「取得某節點所有葉子孫節點」)。相關操作更像**程序式命令**而非宣告式查詢,需配合 CTE/遞迴函數完成。
hierarchyid 欄,編寫遞迴 CTE 回填路徑NodePath AS Node.ToString() PERSISTED 便於除錯IsDescendantOf 替代遞迴 CTE,效能提升數量級