Is this better?set nocount ondeclare @menu table (id int, name varchar(12), parentid int)insert @menuselect 1, 'A' ,null union allselect 2, 'AA' ,1 union allselect 3, 'B' ,null union allselect 4, 'AAA' ,2 union allselect 5, 'AA' ,1 union allselect 6, 'AAAA' ,4 union allselect 7, 'AA' ,1 union allselect 8, 'ABCDEF' ,7;with Recursion (id, name, parentid, path, Level)as(select id, Name, ParentID, convert(nvarchar(32), h.id) as path, 0from @Menu hwhere h.ParentID is nullunion allselect h.id, h.Name, h.ParentID, convert(nvarchar(32), r.path + '.' + convert(varchar(10), h.id)) as path, r.Level + 1from @Menu h inner join Recursion as r on h.ParentID = r.id)select id, name, ParentID, path, level from Recursion ORDER BY Pathoutput:id name ParentID path level----------- ------------ ----------- -------------------------------- -----------1 A NULL 1 02 AA 1 1.2 14 AAA 2 1.2.4 26 AAAA 4 1.2.4.6 35 AA 1 1.5 17 AA 1 1.7 18 ABCDEF 7 1.7.8 23 B NULL 3 0
Be One with the OptimizerTG