开发者

Import parent-child XML data to Sql Server Tables

I have a XML like this:

    <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>

and I want to convert it to tables like this:

State:

ID        Name
01        State1
---------------------------------------------------
开发者_如何学Python

City:

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

How I can do this ?

thanks


I'm not going to write this for every field and all the inserts, but the following SQL should point you in the right direction:

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) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜