2011-07-30 30 views
1

私はテーブルLocations(id, type, code, parentid)を持っています。SQL Server 2008階層的クエリ

タイプは、国/州/地域/地区にすることができます。したがって、この表には階層的地理データが格納されます。 国には多くの州があり、多くの地域と地域に多くの町があります。

特定の親レコードの子孫レコードをリストする必要があります。たとえば、オーストラリア国のすべてのレコードが必要です。この場合の親レコードは

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.

関連する問題