Я считаю, что это то, что вы хотели бы после ...
/* Setup, using table variables for this example */
declare @TableA table (Division varchar(50), [State] varchar(50), County varchar(50), City varchar(50))
declare @TableB table (Division varchar(50), [State] varchar(50), County varchar(50), City varchar(50))
insert into @TableA values ('North','OH','ABCDE','CLE')
,('South','TX','Dallas','Irving')
,('East','NC','EFGH','Charlotte')
insert into @TableB values ('North','OH','ABCDE','Akron')
,('East','NC','PQRST','Duluth')
,('South','LA','GHJKL','Boca')
--review initital tables
select * from @TableA
select * from @TableB
-- Top Level of Hierarchy...
insert into @TableB
select distinct
A.Division
,NULL as [State]
,NULL as [County]
,NULL as [City]
from
@TableA A
left join
@TableB B on A.Division = B.Division
and B.[State] is null
and B.County is null
and B.City is null
where
B.Division is null
-- 2nd Level of Hierarchy...
insert into @TableB
select distinct
A.Division
,A.[State] as [State]
,NULL as [County]
,NULL as [City]
from
@TableA A
left join
@TableB B on A.Division = B.Division
and A.[State] = B.[State]
and B.County is null
and B.City is null
where
B.Division is null
and B.[State] is null
-- 3rd Level of Hierarchy...
insert into @TableB
select distinct
A.Division
,A.[State] as [State]
,A.County as [County]
,NULL as [City]
from
@TableA A
left join
@TableB B on A.Division = B.Division
and A.[State] = B.[State]
and A.County = B.County
and B.City is null
where
B.Division is null
and B.[State] is null
and B.County is null
-- Review results
select
*
from
@TableB
order by
Division
,[State]
,County
,City
Результаты :
Division State County City
---------------------------------------------
East NULL NULL NULL
East NC NULL NULL
East NC EFGH NULL
East NC PQRST Duluth
North NULL NULL NULL
North OH NULL NULL
North OH ABCDE NULL
North OH ABCDE Akron
South NULL NULL NULL
South LA GHJKL Boca
South TX NULL NULL
South TX Dallas NULL