2011-07-30 38 views
1

我有一個表Locations(id, type, code, parentid)SQL Server 2008分層查詢

該類型可以是COUNTRY/STATE/REGION/TOWN。所以這張表擁有層次地理數據。 國家會有很多州,州很多地區和地區很多城鎮。

我需要列出給定父記錄的後代記錄。例如,我需要澳大利亞國家下的所有記錄。在這種情況下,母公司的記錄將是

10, COUNTRY, AU, null) 

我明白一個遞歸CTE是走的路,但不知道如何。

感謝

回答

2

這裏的CTE方法的一個例子:

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.