简体   繁体   中英

Importing and shredding XML into SQL Table

Hi i hope someone can help me, i am trying to import XML elements into an SQL Table, in XML format.

To start with i have an XML file called Chassis.xml that looks like this.

<Chassis>
  <Chassis Id="1" Chassis="blah blah" Suitability="1" Structured="1" />
  <Chassis Id="2" Chassis="blah blah" Suitability="1" Structured="1" />
  <Chassis Id="3" Chassis="Blah Blah" Suitability="1" Structured="1" />
  <Chassis Id="4" Chassis="Blah Blah" Suitability="1" Structured="1" />
</Chassis>

And i am trying to im trying to write an SQL procedure that imports the elements into a table here is the table layout that i wanted.

test.hardwareComponents

Id          TypeId         XmlData
----------------------------------
1            0001         <Chassis Id="1" Chassis="blah blah" Suitability="1" Structured="1" />
2            0001         <Chassis Id="2" Chassis="blah blah" Suitability="1" Structured="1" />

The TypeId will be a foreign key that will define what that Type is in another table later, so TypeId 0001 is a Chassis ComponentType.

Every thing i try keeps on failing i've spent hours and hours trying to do this and i am stumped can anyone help me.

Have you tried something like

DECLARE @xml XML

SET @xml = 
'<Chassis> 
  <Chassis Id="1" Chassis="blah blah" Suitability="1" Structured="1" /> 
  <Chassis Id="2" Chassis="blah blah" Suitability="1" Structured="1" /> 
  <Chassis Id="3" Chassis="Blah Blah" Suitability="1" Structured="1" /> 
  <Chassis Id="4" Chassis="Blah Blah" Suitability="1" Structured="1" /> 
</Chassis>'


SELECT  T2.Loc.value('@Id', 'INT') ID,
        T2.Loc.query('.')
FROM    @xml.nodes('/Chassis/Chassis') as T2(Loc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM