2016-12-15 30 views
2

私はこのテーブル地域テーブルの親地域レベル名を知るには?

CREATE TABLE Region 
(
    RegionID INT PRIMARY KEY , 
    ParentRegionID INT FOREIGN KEY REFERENCES dbo.Region, 
    RegionName NVARCHAR(30) 
); 

を作成し、私はこのようないくつかの値を挿入します。

INSERT INTO dbo.Region 
     (RegionID, ParentRegionID, RegionName) 
VALUES (1, NULL, N'USA'), 
     (2, 1, N'California'), 
     (3, 2, N'Los Angeles'), 
     (4, 2, N'California City'), 
     (5, 2, N'San Diego'), 
     (6, 2, N'Bakersfield'), 
     (7, 1, N'Alaska'), 
     (8, 7, N'Wrangell'), 
     (9, 7, N'Anchorage'), 
     (10, 7, N'Juneau'); 

私は私のクエリは

ParentRegionID RegionID RegionName RegionLevelNameに


NULL   1   USA   Country 
1    2   California  State 
1    7   Alaska   State 
7    8   Wrangell  City 
7    9   Anchorage  City 
7    10   Juneau   City 
2    3   Los Angeles City 
2    4   CaliforniaCity City 
2    5   San Diego  City 
2    6   Bakersfield City 
を返したいです

答えて

2

このコードを試す

WITH RegionTree (ParentRegionID, RegionID, RegionName, RegionLevel) 
     AS (
      SELECT ParentRegionID , 
        RegionID , 
        RegionName , 
        0 AS RegionLevel 
      FROM  Region 
      WHERE ParentRegionID IS NULL 
      UNION ALL 
      SELECT c.ParentRegionID , 
        c.RegionID , 
        c.RegionName , 
        p.RegionLevel + 1 
      FROM  Region c 
        INNER JOIN RegionTree p ON c.ParentRegionID = p.RegionID 
     ) 
SELECT ParentRegionID , 
     RegionID , 
     RegionName , 
     CASE WHEN RegionLevel = 0 THEN 'Country' 
      WHEN RegionLevel = 1 THEN 'State' 
      WHEN RegionLevel = 2 THEN 'City' 
     END AS RegionLevelName 
FROM RegionTree;