如何为XML类型编写此SQL查询?

时间:2018-04-23 23:41:49

标签: xml tsql xpath sql-server-2012 xquery

我正在使用SQL Server 2012,其中我有一个表[abc],其中有[Information]类型的[XML]列。

此列的值类似于

<Information>
  <Groups>
    <Group Name="Monitor">
      <Items>
        <Item>
          <Name>Cid</Name>
          <Value>2323232323</Value>
        </Item>
        <Item>
          <Name>Tid</Name>
          <Value>6656565656</Value>
        </Item>
      </Items>
    </Group>
  </Groups>
</Information>

如何编写可查询此列的SQL查询 - [Information]并从名称/值中进一步提取[Tid]的值?

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

DECLARE @abc TABLE(ID INT IDENTITY, Information XML);
INSERT INTO @abc VALUES
(N'<Information>
  <Groups>
    <Group Name="Monitor">
      <Items>
        <Item>
          <Name>Cid</Name>
          <Value>2323232323</Value>
        </Item>
        <Item>
          <Name>Tid</Name>
          <Value>6656565656</Value>
        </Item>
      </Items>
    </Group>
  </Groups>
</Information>');

- 此查询使用<Value>谓词

获取唯一的值(<Name>,其中XQuery为“Tid”)
SELECT ID
      ,Information
      ,Information.value(N'(/Information/Groups/Group/Items/Item[Name/text()="Tid"]/Value/text())[1]',N'bigint') AS ValueInTid
FROM @abc AS abc;

--Result=6656565656

- 此查询使用.nodes()获取所有(重复的)<Group>个节点,而不是再次.nodes()返回(重复)<Item>个节点。结果是一个完整的表格:

SELECT gr.value(N'@Name',N'nvarchar(max)') AS GroupName
      ,itm.value(N'(Name/text())[1]',N'nvarchar(max)') AS ItemName
      ,itm.value(N'(Value/text())[1]',N'nvarchar(max)') AS ItemValue
FROM @abc AS abc
OUTER APPLY abc.Information.nodes(N'/Information/Groups/Group') AS A(gr)
OUTER APPLY A.gr.nodes(N'Items/Item') AS B(itm);

结果

GroupName   ItemName    ItemValue
Monitor     Cid         2323232323
Monitor     Tid         6656565656