SQL Server 2008 Hierarchical queries
I have a table 开发者_运维问答Locations(id, type, code, parentid)
.
The type can be COUNTRY/STATE/REGION/TOWN. So this table holds hierarchical geographic data. Country will have many states, state many regions and regions many towns.
I need to list out descendent records for a given parent record. For example I need all records under Country Australia. The parent record in this case will be
10, COUNTRY, AU, null)
I understand a recursive CTE is the way to go but not sure how to.
thanks
Here's an example of a CTE approach:
declare @t table (id int, type varchar(10), name varchar(50), parentid int)
insert @t
select 1, 'COUNTRY', 'AU', null
union all select 2, 'STATE', 'Guiness State', 1
union all select 3, 'STATE', 'Pilsner State', 1
union all select 4, 'REGION', 'Heineken Region', 2
union all select 5, 'REGION', 'Bud Light Region', 3
union all select 6, 'TOWN', 'Hoegaarden Town', 2
union all select 7, 'TOWN', 'Corona Town', 2
union all select 8, 'TOWN', 'Leffe Town', 3
; with recursed as
(
select *
from @t as root
where root.name = 'Guiness State'
union all
select child.*
from recursed as parent
join @t as child
on parent.id = child.parentid
)
select *
from recursed
Code sample at SE Data.
精彩评论