从sql中的xml获取属性和元素值

时间:2017-02-03 17:30:59

标签: sql xml attributes element

我有以下XML,需要将此数据提取到sql表中以获取属性名称和所有元素值

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

我的SQL是

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)

但结果似乎总是在“主要人员”之下。属性,并没有返回&#39; OtherPerson&#39;在AttributeName列中

AttributeName   NodeName                    NodeValue
MainPerson      OccupationID                347
MainPerson      OccupationDescription   
MainPerson      OccupationOtherDescription  accountant
MainPerson      OccupationID                200
MainPerson      OccupationDescription   
MainPerson      OccupationOtherDescription  engineer

我希望结果看起来像是:

AttributeName   NodeName                    NodeValue
MainPerson      OccupationID                347
MainPerson      OccupationDescription   
MainPerson      OccupationOtherDescription  accountant
OtherPerson     OccupationID                200
OtherPerson     OccupationDescription   
OtherPerson     OccupationOtherDescription  engineer

我对此比较陌生,似乎无法想出这个,请帮忙,因为这可能很简单!

1 个答案:

答案 0 :(得分:0)

这就是你需要的:

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)

结果:

enter image description here