Those guys gave you all the info you need, but I like doing these things so...use pubsset nocount ongocreate table junk (CategoryID int ,ParentCategoryID int ,Category varchar(30))goinsert junkselect 65, NULL, 'Economic Development' union allselect 66, 65, 'A Wealth of Opportunity' union allselect 67, NULL, 'Top Category' union allselect 69, 67, 'test 3' union allselect 73, NULL, 'A new category' union allselect 74, 73, 'test' union allselect 75, 73, 'a test' union allselect 80, 75, 'a 3rd level test' union allselect 81, 80, 'a 4th level test'godeclare @tb table (CategoryID int ,hierarchy varchar(7900) ,category varchar(30) ,lev int)declare @level intset @level = 0insert @tb (CategoryID, hierarchy, category, lev)select categoryid ,category ,category ,@levelfrom junkwhere parentCategoryid is null--loop through an entire nesting level at oncewhile @@rowcount > 0begin set @level = @level + 1 insert @tb (CategoryID, hierarchy, category, lev) select a.categoryid ,b.hierarchy + '.' + a.category ,a.category ,@level from junk a join @tb b on b.CategoryID = a.parentCategoryid --prevent circular references left join @tb ex on ex.CategoryID = a.Categoryid where ex.CategoryID is null and b.lev+1 = @levelend--return results in hierarchal, alpabetical orderselect category ,space(lev*3) + category [visual hierarchy]from @tb order by hierarchygodrop table junk
Be One with the OptimizerTG