繁体   English   中英

从SQL中的XML获取属性和元素值

[英]Get attribute and element values from xml in sql

我有以下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)

但结果似乎总是在“ Mainperson”属性下,并且在AttributeName列中不返回“ OtherPerson”

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

我对此还比较陌生,似乎无法弄清楚,请帮忙,因为这可能很简单!

这是您需要的:

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)

结果:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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