see below for an examplecreate table Hier(LocationID int, Name varchar(100), ParentID int )insert into Hierselect 1, 'Asia', Null union allselect 2 ,'Europe', Null union allselect 3 ,'China', 1 union allselect 4 ,'Beijing', 3 union allselect 5 ,'Azerbaijan', 2 union allselect 6 ,'Germany', 2 union allselect 7 ,'Munich', 6;with cte(id, value,parentid,parentvalue,[path],[level]) as(select LocationID,Name,cast(null as int),cast(NULL as varchar(100)),cast(Name as varchar(max)),cast(1 as int)FROM Hierwhere ParentID is nullunion allselect t.LocationID,t.Name,t.ParentID,c.value,cast(c.[path] + '/' + t.Name as varchar(max)),c.Level + 1from CTE cjoin Hier tON t.ParentID = c.id)select [1] as Continent,[2] As country, [3] as cityfrom(select left(path + '/',charindex('/',path+'/')-1) as path, level,valuefrom CTE)tpivot (max(value) for [level] in ([1],[2],[3]))poutput----------------------------------------Continent country city-----------------------------------------Asia China BeijingEurope Germany Munich
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/