Locations
行政区画の階層を作る自己結合のテーブルがあります。のようState
にCounty
、Town
など
LocationId
はPK
これtable
であり、のように使用さForeign key
れjoining table
ます。結合テーブルにはとがProjectId
あり、プロジェクトは任意のレベルの場所にある可能性があるため、結合テーブルには郡、町などを含めることができます。FKとして使用される場所LocationsId
を見つけたいと思います。root-parent(State)
サンプルとして以下sql
を使用してください。(管理スタジオでコピー/貼り付け)
DECLARE @Locations TABLE (LocationId INT, LocationName VARCHAR(30), ParentId INT, LocLevel INT)
INSERT INTO @Locations
Values(1, 'State1', NULL, 1),
(2, 'State1-County1', 1, 2),
(3, 'State1-County1-Town1', 2, 3),
(4, 'State1-County1-Town1-Muncip-1', 3, 4),
(5, 'State1-County2', 1, 2),
(6, 'State1-County2-Town1', 5, 3),
(7, 'State1-County2-Town1-Muncip-1', 6, 4),
(8, 'State2', NULL, 1),
(9, 'State2-County1', 8, 2),
(10, 'State2-County1-Town1', 9, 3),
(11, 'State2-County1-Town1-Muncip-1', 10, 4)
DECLARE @ProjectLocations TABLE (ProjectLocationId INT, ProjectId INT, LocationId INT)
INSERT INTO @ProjectLocations
VALUES(1, 1, 2),
(2, 1, 3),
(3, 1, 4),
(4, 1, 11),
(5, 2, 3),
(6, 2, 11),
(7, 3, 10),
(8, 4, 11),
(9, 5, 9)
SELECT * FROM @Locations
SELECT * FROM @ProjectLocations
これは出すべきです
DECLARE @FirstOutput TABLE (ProjectLocationId INT, ProjectId INT, LocationId INT, RootParentId INT)
SELECT * FROM @FirstOutput