Create table #Hirarchy( ID int ,Type varchar(20) ,Name varchar(100) ,ParentID int );
insert into #Hirarchy values(1,'COUNTRY','USA',NULL) insert into #Hirarchy values(2,'STATE','GA',1) insert into #Hirarchy values(3,'STATE','NC',1) insert into #Hirarchy values(4,'CITY','Charlotte',3) insert into #Hirarchy values(5,'STATION','Pine-1',4) insert into #Hirarchy values(6,'STATION','Pine-2',4) insert into #Hirarchy values(7,'STATION','SouthBlv-1',4) insert into #Hirarchy values(8,'CITY','Marietta',2) insert into #Hirarchy values(9,'STATION','IndPark-1',8) insert into #Hirarchy values(10,'STATION','IndPark-2',8) ; WITH CTE_Hirarchy(ID,Type,Name,ParentID,State, HPath) AS ( Select ID,Type,Name,ParentID,Name As State,CAST(Name as varchar(100)) as HPath from #Hirarchy where Type='STATE' UNION ALL SELECT a.ID,a.Type,a.Name,a.ParentID,b.State,CAST(b.HPath + '->' + a.Name as varchar(100)) as HPath from #Hirarchy a JOIN CTE_Hirarchy b on a.ParentID=b.ID ) Select * from CTE_Hirarchy Where Type='STATION' go
Drop table #Hirarchy
|