Loki, I had the similar query but it didn't sort by name as I wanted but by the code - it was Friday and I was overloaded.
Anyway, running your query gave me an error, it's necessary to cast; I had to change it following way:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name, CAST(ofs.name as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name, CAST(tree.code+'/'+ofs.name as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
The problem is that it's necessary to cast to a varchar despite of the fact that name is varchar. It's quite possible that varchar(255) isn't enough with large trees.
So I made a version where the above mention problem isn't so big:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name,
CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name,
CAST(tree.code +'/' + CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255)) as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
But I don't like such solution where is necessary to cast. Is there any better solution?