首页 > 解决方案 > 如何通过 SQL Server 从 XML 中的节点获取值

问题描述

我在网上找到了几条关于此的信息,但我无法让它为我的生活工作。

这是我拥有的 XML:

在此处输入图像描述

我需要提取每个节点的 ID 和名称值。有很多。

我试图这样做,但它返回 NULL:

select [xml].value('(/Alter/Object/ObjectDefinition/MeasureGroup/Partitions/Partition/ID)[1]', 'varchar(max)')
from test_xml

我知道上面只会返回 1 条记录。我的问题是,如何返回所有记录?

这是 XML 文本(精简版):

<Alter xmlns="http://schemas.microsoft.com/analysisservices/2003/engine" AllowCreate="true" ObjectExpansion="ExpandFull">
  <ObjectDefinition>
    <MeasureGroup xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <ID>ts_homevideo_sum_20140430_76091ba1-3a51-45bf-a767-f9f3de7eeabe</ID>
      <Name>table_1</Name>
      <StorageMode valuens="ddl200_200">InMemory</StorageMode>
      <ProcessingMode>Regular</ProcessingMode>
      <Partitions>
        <Partition>
          <ID>123</ID>
          <Name>2012</Name>
        </Partition>
        <Partition>
          <ID>456</ID>
          <Name>2013</Name>
        </Partition>
      </Partitions>
    </MeasureGroup>
  </ObjectDefinition>
</Alter>

标签: sqlsql-serverxmlxquery

解决方案


你需要这样的东西:

DECLARE @MyTable TABLE (ID INT NOT NULL, XmlData XML)

INSERT INTO @MyTable (ID, XmlData)
VALUES (1, '<Alter xmlns="http://schemas.microsoft.com/analysisservices/2003/engine" AllowCreate="true" ObjectExpansion="ExpandFull">
  <ObjectDefinition>
    <MeasureGroup xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <ID>ts_homevideo_sum_20140430_76091ba1-3a51-45bf-a767-f9f3de7eeabe</ID>
      <Name>table_1</Name>
      <StorageMode valuens="ddl200_200">InMemory</StorageMode>
      <ProcessingMode>Regular</ProcessingMode>
      <Partitions>
        <Partition>
          <ID>123</ID>
          <Name>2012</Name>
        </Partition>
        <Partition>
          <ID>456</ID>
          <Name>2013</Name>
        </Partition>
      </Partitions>
    </MeasureGroup>
  </ObjectDefinition>
</Alter>')

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/analysisservices/2003/engine')
SELECT 
    tbl.ID,
    MeasureGroupID = xc.value('(ID)[1]', 'varchar(200)'),
    MeasureGroupName = xc.value('(Name)[1]', 'varchar(200)'),
    PartitionID = xp.value('(ID)[1]', 'varchar(200)'),
    PartitionName = xp.value('(Name)[1]', 'varchar(200)')
FROM
    @MyTable tbl
CROSS APPLY
    tbl.XmlData.nodes('/Alter/ObjectDefinition/MeasureGroup') AS XT(XC)
CROSS APPLY
    XC.nodes('Partitions/Partition') AS XT2(XP)
WHERE   
    ID = 1

首先,您必须尊重并包含​​定义在 XML 文档根目录中的默认 XML 名称空间。

接下来,您需要进行嵌套调用以.nodes()获取所有<MeasureGroup>和所有包含的<Partition>节点,以便您可以访问这些 XML 片段并从中提取IDName

这应该会导致类似这样的输出:

在此处输入图像描述


推荐阅读