--Czy to zadziała? pochodzi z Sortowanie drzewa z inna kolumna w SQL Server 2008
DECLARE @table TABLE (id INT NOT NULL PRIMARY KEY, name NVARCHAR(4000) NOT NULL, path HIERARCHYID)
INSERT
INTO @table
VALUES
(1, 'People', '/'),
(2, 'Girls', '/1/'),
(3, 'Boys', '/2/'),
(4, 'Zoey', '/1/1/'),
(5, 'Kate', '/1/2/'),
(6, 'Monica', '/1/3/'),
(7, 'Mark', '/2/1/'),
(8, 'David', '/2/2/')
;WITH q AS
(
SELECT *, HIERARCHYID::Parse('/') AS newpath
FROM @table
WHERE path = HIERARCHYID::GetRoot()
UNION ALL
SELECT t.*, HIERARCHYID::Parse(q.newpath.ToString() + CAST(ROW_NUMBER() OVER (ORDER BY t.name) AS NVARCHAR(MAX)) + '/')
FROM q
JOIN @table t
ON t.path.IsDescendantOf(q.path) = 1
AND t.path.GetLevel() = q.path.GetLevel() + 1
)
SELECT replicate(convert(nvarchar, '-'), q.path.GetLevel()) + q.name /*+ '(' + q.newpath.ToString() + ')'*/
FROM q
ORDER BY
newpath