Her er en, der gør tricket for mig:
@ParentID er kun et udgangspunkt i hierarkiet, men du kan sende ind 0 (men jeg tror, du bruger null som basis-id, så du får ideen)
Nøglen til bestilt sortering er med den sorteringsnøgle, der er bygget op.
WITH RoleHierarchy (RoleID, [Role], [Description], ParentID, Editable, HierarchyLevel, SortKey) AS
(
-- Base
SELECT
RoleID,
[Role],
[Description],
ParentID,
Editable,
0 as HierarchyLevel,
CAST(RoleID AS VARBINARY(300))
FROM
dbo.Roles
WHERE
RoleID = @ParentID
UNION ALL
-- Recursive
SELECT
e.RoleID,
e.[Role],
e.[Description],
e.ParentID,
e.Editable,
th.HierarchyLevel + 1 AS HierarchyLevel,
CAST (th.SortKey + CAST (e.[Role] AS VARBINARY(100)) + CAST (e.[RoleID] AS VARBINARY(100)) AS VARBINARY(300))
FROM
Roles e
INNER JOIN RoleHierarchy th ON e.ParentID = th.RoleID
WHERE
e.RoleID != 0
)
SELECT
RoleID,
ParentID,
[Role],
[Description],
Editable,
HierarchyLevel
FROM
RoleHierarchy
WHERE
RoleID != @ParentID
ORDER BY
SortKey