Версия с целочисленным столбцом идентификаторов в качестве первичного ключа.
declare @Country table
(
CountryID int identity primary key,
Name varchar(50)
)
declare @State table
(
StateID int identity primary key,
CountryID int,
Name varchar(50)
)
insert into @Country (Name)
select C.C.value('@name', 'varchar(50)')
from @xml.nodes('/countries/country') as C(C)
insert into @State (CountryID, Name)
select Country.CountryID, S.S.value('.', 'varchar(50)')
from @xml.nodes('/countries/country') as C(C)
cross apply C.C.nodes('state') as S(S)
inner join @Country as Country
on Country.Name = C.C.value('@name', 'varchar(50)')
Рабочий образец для данных SE
И версия, в которой имена используются в качестве основногоключ.
declare @Country table
(
CountryName varchar(50) primary key
)
declare @State table
(
StateName varchar(50) primary key,
CountryName varchar(50)
)
insert into @Country (CountryName)
select distinct C.C.value('@name', 'varchar(50)')
from @xml.nodes('/countries/country') as C(C)
insert into @State (StateName, CountryName)
select S.S.value('.', 'varchar(50)'),
C.C.value('@name', 'varchar(50)')
from @xml.nodes('/countries/country') as C(C)
cross apply C.C.nodes('state') as S(S)