I have the following XML and need to pull this data into a sql table to get the attribute name and all of the element values
declare @GetQuoteXML xml
set @GetQuoteXML = '<QuoteRequest>
<QuoteRisk>
<ChildControls parent = "MainPerson">
<OccupationID>347</OccupationID>
<OccupationDescription />
<OccupationOtherDescription>accountant</OccupationOtherDescription>
</ChildControls>
<ChildControls parent = "OtherPerson">
<OccupationID>200</OccupationID>
<OccupationDescription />
<OccupationOtherDescription>engineer</OccupationOtherDescription>
</ChildControls>
</QuoteRisk>
</QuoteRequest>'
My SQL is
SELECT
AttributeName = ChildControls.value('(//ChildControls/@parent)[1]','varchar(50)'),
NodeName = ChildControls.value('local-name(.)', 'varchar(50)'),
NodeValue = ChildControls.value('(.)[1]', 'varchar(50)')
FROM @GetQuoteXML.nodes('//ChildControls/*') AS ChildControlTable(ChildControls)
but the results always seem to be under the 'Mainperson' attribute, and doesnt return the 'OtherPerson' in the AttributeName column
AttributeName NodeName NodeValue
MainPerson OccupationID 347
MainPerson OccupationDescription
MainPerson OccupationOtherDescription accountant
MainPerson OccupationID 200
MainPerson OccupationDescription
MainPerson OccupationOtherDescription engineer
What I want the results to look like is:
AttributeName NodeName NodeValue
MainPerson OccupationID 347
MainPerson OccupationDescription
MainPerson OccupationOtherDescription accountant
OtherPerson OccupationID 200
OtherPerson OccupationDescription
OtherPerson OccupationOtherDescription engineer
I'm relatively new to this and can't seem to figure this one out, please help as this probably so simple to do!
This is what you need:
SELECT
AttributeName = ChildControls.value('../@parent','varchar(50)'),
NodeName = ChildControls.value('local-name(.)', 'varchar(50)'),
NodeValue = ChildControls.value('(.)[1]', 'varchar(50)')
FROM @GetQuoteXML.nodes('//ChildControls/*') AS ChildControlTable(ChildControls)
RESULT:
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.