You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL XML节点查询问题:无法获取Section节点的ID与Caption

问题

现有SQL查询可正常返回XML中的Tab节点数据,但修改查询条件获取Section节点的ID和Caption时无结果。附上相关XML片段及SQL脚本寻求帮助:

XML片段

</Tab>
<Tab Caption="Works" ID="7f789fee-1aa4-4341-801a-f31d1daf1bcc" 
  <Tabs>
    <Tab Caption="Works" ID="24e52dcf-fb35-4a29-8890-9eec6bde28c2" 
      <Sections>
        <Section ID="631e1555-89fa-4306-801f-6a1d7b23a435" Caption="ThisOne" 
        </Section>
      </Sections>
    </Tab>

原查询脚本(无结果)

with xmlnamespaces ('Page' as tns, 'commontypes' as common)

select 
    page.section.value('@ID', 'uniqueidentifier') as ID_GUID,
    page.section.value('@Caption', 'nvarchar(max)') as Section
from dbo.PAGELIBRARY as P
  cross apply P.PAGELIBRARYXML.nodes('tns:Page/tns:Sections/tns:Section') as page(section) 
where  P.ID = '88159265-2b7e-4c7b-82a2-119d01ecd40f' 

可正常获取Tab信息的脚本片段

cross apply P.PAGELIBRARYXML.nodes('tns:Page/tns:Tabs/tns:Tab') as page(tab)
解决方案

问题根源是XPath路径错误:从XML结构来看,Section节点的层级是Page -> Tabs -> Tab -> Sections -> Section,而原查询直接从Page节点下找Sections,路径不匹配。

修改nodes()方法中的XPath路径,匹配正确的嵌套层级即可:

with xmlnamespaces ('Page' as tns, 'commontypes' as common)

select 
    page.section.value('@ID', 'uniqueidentifier') as ID_GUID,
    page.section.value('@Caption', 'nvarchar(max)') as Section
from dbo.PAGELIBRARY as P
  cross apply P.PAGELIBRARYXML.nodes('tns:Page/tns:Tabs/tns:Tab/tns:Sections/tns:Section') as page(section) 
where  P.ID = '88159265-2b7e-4c7b-82a2-119d01ecd40f' 

注:你提供的XML片段存在标签未闭合的语法问题,需确保数据库中存储的XML格式是正确的,否则可能影响查询结果。

内容的提问来源于stack exchange,提问作者davie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:03:14