In another question I asked I had found a solution but the sort order works only if the ID's are growing:
USE TESTE
GO
WITH Niveis AS (
-- Membro âncora
SELECT Id, IdPai, convert(varchar(1000), Nome) as Nome,
0 AS Nivel -- nível 0
FROM TABELA1
WHERE IdPai IS NULL
UNION ALL
-- Filhos
SELECT T1.Id, T1.IdPai, convert(varchar(1000), Niveis.Nome + ' - ' + T1.Nome) as Nome,
Nivel+1
FROM TABELA1 T1
INNER JOIN Niveis ON T1.IdPai = Niveis.Id
)
SELECT Id, IdPai, Nome
FROM Niveis
ORDER BY Id, IdPai
How can I do when the ID's are out of order in the levels?