1
In another question I asked i had found a solution but ordering only works 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 could I do when ID’s are out of ascending order on levels?