将父子XML数据导入Sql Server表

时间:2011-08-12 10:08:21

标签: sql-server xml sql-server-2008

我有这样的XML:

    <StateTree>
      <State ID="01">
        <Name>State1</Name>
         <CityList>
          <City ID="01" Order="1" CityGroup="1" CityBuild="1" GeoLocation="X">
            <Name>City1</Name>
            <Group>1</Group>
             <AreaList>
              <Area ID="01" GeoLocation="6">
                <Name>Area1</Name>
              </Area>
              <Area ID="02" GeoLocation="6">
                <Name>Area2</Name>
              </Area>
            </AreaList>
          </City>
          <City ID="02" Order="3" CityGroup="2" CityBuild="4" GeoLocation="5">
            <Name>City2</Name>
            <Group>2</Group>
            <AreaList />
          </City>
        </CityList>
      </State>
     </StateTree>

我想把它转换成这样的表:

州:

ID        Name
01        State1
---------------------------------------------------

城市:

ID    Order   CityGroup   CityBuild   GeoLocation   Name       State1
01    1         1           1           X           City1       01
02    3         2           4           5           City2       01
---------------------------------------------------

AreaList:

ID        GeoLocation       Name        CityID
01          6               Area1        01
02          6               Area2        01

我怎么能这样做?

感谢

1 个答案:

答案 0 :(得分:3)

我不会为每个字段和所有插入写入此内容,但以下SQL应指向正确的方向:

declare @xml xml
set @xml = 
'
<StateTree>
      <State ID="01">
        <Name>State1</Name>
         <CityList>
          <City ID="01" Order="1" CityGroup="1" CityBuild="1" GeoLocation="X">
            <Name>City1</Name>
            <Group>1</Group>
             <AreaList>
              <Area ID="01" GeoLocation="6">
                <Name>Area1</Name>
              </Area>
              <Area ID="02" GeoLocation="6">
                <Name>Area2</Name>
              </Area>
            </AreaList>
          </City>
          <City ID="02" Order="3" CityGroup="2" CityBuild="4" GeoLocation="5">
            <Name>City2</Name>
            <Group>2</Group>
            <AreaList />
          </City>
        </CityList>
      </State>
     </StateTree>

'

--Select States
select
    ID = s.value('@ID','varchar(10)'),
    Name = s.value('Name[1]','varchar(100)')
from 
    @xml.nodes('/StateTree/State') x(s)

--Select Cities
select
    ID = c.value('@ID','varchar(10)'),
    Name = c.value('Name[1]','varchar(100)'),
    StateID = c.value('../../@ID','varchar(10)')
from
    @xml.nodes('/StateTree/State/CityList/City') x(c)

--Select Areas
select
    ID = a.value('@ID','varchar(10)'),
    Name = a.value('Name[1]','varchar(100)'),
    CityID = a.value('../../@ID','varchar(10)')
from
    @xml.nodes('/StateTree/State/CityList/City/AreaList/Area') x(a)