您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

XML to SQL-选择多个具有相同名称的节点

XML to SQL-选择多个具有相同名称的节点

取决于您要执行的操作…如果您知道要抓取2个“ Address_Components”,则可以按如下方式修改查询

;WITH XMLNAMESPACES(DEFAULT 'urn:com.workday.report/Countries_and_Their_Address_Components_Summary')
    select 
        xmldata.[ISO], xmldata.[Component 1], xmldata.[Component 2], xmldata.[required]
    from @inputxml
    cross apply (
        select 
            [ISO] = xmldata.value('(Country/ID)[3]', 'VARCHAR(MAX)'),
            [Component 1] = xmldata.value('(Address_Components/Address_Component/ID)[2]', 'VARCHAR(MAX)'),
            [Component 2] = xmldata.value('(Address_Components[2]/Address_Component/ID)[2]', 'VARCHAR(MAX)'),
            [required] = xmldata.value('(Address_Components/required)[1]', 'INT')
        from x.nodes('/Report_Data/Report_Entry') Z1(xmldata)
    ) xmldata

结果看起来像这样:

ISO   Component 1               Component 2               required
----- ------------------------- ------------------------- -----------
AFG   ADDRESS_LINE_1_LOCAL      ADDRESS_LINE_2_LOCAL      0

但是,如果可以有任意数量的“ Address_Components”,并且想要将它们捕获到单独的记录中,则可以像下面这样重写查询

;WITH XMLNAMESPACES(DEFAULT 'urn:com.workday.report/Countries_and_Their_Address_Components_Summary')
    select 
        [ISO] = Report_Entry.x.value('(Country/ID)[3]', 'VARCHAR(MAX)')
        , [Component] = Address_Components.x.value('(Address_Component/ID)[2]', 'VARCHAR(MAX)')
        , [required] = Address_Components.x.value('(required)[1]', 'INT')
    from @inputxml
    cross apply x.nodes('/Report_Data/Report_Entry') Report_Entry(x)
    cross apply Report_Entry.x.nodes('./Address_Components') Address_Components (x)

结果看起来像这样:

ISO   Component                 required
----- ------------------------- -----------
AFG   ADDRESS_LINE_1_LOCAL      0
AFG   ADDRESS_LINE_2_LOCAL      0
SQLServer 2022/1/1 18:29:19 有349人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶