如何通过SQL Server从XML节点中获取价值

时间:2018-12-07 17:19:33

标签: sql sql-server xml xquery

我已经在网上找到了一些与此有关的信息,但我无法一辈子使用它。

这是我拥有的XML:

enter image description here

我需要提取每个节点的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>

1 个答案:

答案 0 :(得分:2)

您需要这样的东西:

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片段并提取{{ 1}}和ID

这将导致输出类似这样的结果:

enter image description here