Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Heirarchical data required using T SQL

Author  Topic 

geeshna
Starting Member

1 Post

Posted - 2011-09-05 : 06:02:00
Hi,
I have a DB on SQL Server 2005 Express edition.
One among couple of tables is a 'Location' table with structure as below :
LocationID - PK
Name
ParentID - FK

The ParentID is self Referncing key to the LocationID of the same table.

The referencing could go upto 3 levels as demonstrated in the example below
LocationID Name ParentID
1 Asia Null
2 Europe Null
3 China 1
4 Beijing 3

My requirement is to get the data in Hierarchy :
Continent Country City
Asia Null Null
Asia China Beijing
Europe Null Null

Could someone help me get this structure using SQL Query.

Cheers,
Geeshna


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-05 : 06:21:06
see below for an example

create table Hier
(
LocationID int,
Name varchar(100),
ParentID int
)

insert into Hier
select 1, 'Asia', Null union all
select 2 ,'Europe', Null union all
select 3 ,'China', 1 union all
select 4 ,'Beijing', 3 union all
select 5 ,'Azerbaijan', 2 union all
select 6 ,'Germany', 2 union all
select 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 Hier
where ParentID is null
union all
select t.LocationID,t.Name,t.ParentID,c.value,cast(c.[path] + '/' + t.Name as varchar(max)),c.Level + 1
from CTE c
join Hier t
ON t.ParentID = c.id
)

select [1] as Continent,[2] As country, [3] as city
from(
select left(path + '/',charindex('/',path+'/')-1) as path, level,value
from CTE
)t
pivot (max(value) for [level] in ([1],[2],[3]))p


output
----------------------------------------
Continent country city
-----------------------------------------
Asia China Beijing
Europe Germany Munich



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -