此論壇問題是要利用 HierarchyId 來找出字串路徑,HierarchyId 可以透過 CAST(HierarchyId AS ncarchar(4000)) 直接轉成字串路徑(EX:\1\2\3),而此問題是要找出以[名稱]為主的字串路徑(EX:公司\課級\組級),在沒有現成函數可以使用的前提下,還是只能跑 CTE 來取得。
USE TempDB
GO
IF OBJECT_ID('Demo') IS NOT NULL
DROP TABLE Demo
CREATE TABLE Demo
(
NO int NOT NULL PRIMARY KEY NONCLUSTERED ,
NOName nvarchar(500) ,
HID hierarchyid ,
HLevel AS HID.GetLevel()
)
GO
DECLARE @Parent AS HIERARCHYID
DECLARE @Child AS HIERARCHYID
-- 公司資料
SELECT @Parent = hierarchyid::GetRoot()
INSERT INTO Demo (NO,NOName,HID) VALUES(1,N'公司',@Parent)
-- 課級資料
SELECT @Parent = HID FROM Demo WHERE NO = 1
SELECT @Child = @parent.GetDescendant(NULL, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(2,N'課級1',@Child)
SELECT @Child = @parent.GetDescendant(@Child, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(3,N'課級2',@Child)
-- 組級資料
SELECT @Parent = HID FROM Demo WHERE NO = 2
SELECT @Child = @parent.GetDescendant(NULL, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(4,'組級1',@Child)
SELECT @Child = @parent.GetDescendant(@Child, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(5,'組級2',@Child)
SELECT @Parent = HID FROM Demo WHERE NO = 3
SELECT @Child = @parent.GetDescendant(NULL, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(6,'組級3',@Child)
SELECT @Child = @parent.GetDescendant(@Child, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(7,'組級4',@Child)
SELECT @Child = @parent.GetDescendant(@Child, NULL)
INSERT INTO Demo (NO,NOName,HID) VALUES(8,'組級5',@Child)