尝试这种情况:
declare @x xml = '<?xml version="1.0" encoding="utf-8"?>
<countries author="Michael John Grove" title="Country, State-Province selections"
date="2008-Feb-05">
<country name="Afghanistan">
<state>Badakhshan</state>
<state>Badghis</state>
<state>Baghlan</state>
</country>
<country name="Albania">
<state>Berat</state>
<state>Bulqize</state>
<state>Delvine</state>
</country>
</countries>'
declare @StateTable table(StateId int, [State] nvarchar(100))
declare @CountryTable table(CountryId int, [Country] nvarchar(100))
declare @CountryState table(CountryId int, StateId int)
declare @tempTable table(StateId int, [State] nvarchar(100), CountryId int, [Country] nvarchar(100))
insert @tempTable
select ROW_NUMBER() over(order by ta.[state], ta.country) [stateId]
, ta.state
, DENSE_RANK() over(order by ta.country) [countryId]
, ta.country
from
(
select t.s.value('.', 'nvarchar(100)') [state]
, t.s.value('../@name', 'nvarchar(100)') [country]
from @x.nodes('countries/country/state') t(s)
)ta
insert @StateTable
select c.stateId, c.state
from @tempTable c
insert @CountryTable
select distinct c.countryId, c.country
from @tempTable c
insert @CountryState
select c.countryId, c.stateId
from @tempTable c
select * from @StateTable
select * from @CountryTable
select * from @CountryState
输出:
StateId State
----------- -----------
1 Badakhshan
2 Badghis
3 Baghlan
4 Berat
5 Bulqize
6 Delvine
CountryId Country
----------- -----------
1 Afghanistan
2 Albania
CountryId StateId
----------- -----------
1 1
1 2
1 3
2 4
2 5
2 6