如何从元素中选择/查询xml数据并在SQL中选择同级值

问题描述 投票:0回答:1

例如,我有一个名为t的SQL Server表,它具有2列和很多行

  • ID(PK,int,not null)
  • 数据(XML(。),不为null)

在数据字段中,我有此XML(无法更改其格式)

<ArrayOfDataAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DataAttribute>
    <Name>field1</Name>
    <Value>default-value-example</Value>
</DataAttribute>
<DataAttribute>
    <Name>field2</Name>
</DataAttribute>
<DataAttribute>
    <Name>field5</Name>
    <Value>False</Value>
</DataAttribute>
<DataAttribute>
    <Name>field4</Name>
    <Value>example value</Value>
</DataAttribute>
<DataAttribute>
    <Name>field5</Name>
    <Value>another value</Value>
</DataAttribute>
</ArrayOfDataAttribute>

我需要返回同级xml项名称的ID和内容,其中它等于field4;如果该行不存在,则返回null / empty字符串。

所以如果只有一行,我将以这个结尾

ID | field4

1 |示例值

从在线阅读看来,使用'nodes'似乎是一种方法,但是我却一无所获,我在网上发现的例子似乎是人们在寻找特定价值的地方。这是我最接近的:

SELECT  T2.Loc.value('.', 'varchar(max)') 
FROM   t  
CROSS APPLY t.Data.nodes('/*:ArrayOfDataAttribute/*:DataAttribute/Name') as T2(Loc)  

非常感谢您的帮助

非常感谢理查德

sql-server xml tsql xquery
1个回答
1
投票

您正在寻找的是XQuery谓词,以及如何将值填充到XQuery中。第一个需要使用方括号([]),第二个需要使用功能sql:variable()

尝试这样:

DECLARE @YourTable TABLE(ID INT IDENTITY,[Data] XML);
INSERT INTO @YourTable VALUES
(N'<ArrayOfDataAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DataAttribute>
    <Name>field1</Name>
    <Value>default-value-example</Value>
</DataAttribute>
<DataAttribute>
    <Name>field2</Name>
</DataAttribute>
<DataAttribute>
    <Name>field5</Name>
    <Value>False</Value>
</DataAttribute>
<DataAttribute>
    <Name>field4</Name>
    <Value>example value</Value>
</DataAttribute>
<DataAttribute>
    <Name>field5</Name>
    <Value>another value</Value>
</DataAttribute>
</ArrayOfDataAttribute>');

-搜索字符串的参数

DECLARE @searchFor NVARCHAR(MAX)=N'field4'

-查询

SELECT t.ID
      ,t.[Data].value(N'(/ArrayOfDataAttribute
                         /DataAttribute[(Name/text())[1]=sql:variable("@searchFor")]
                         /Value
                         /text())[1]',N'nvarchar(max)') AS field4
FROM @YourTable t;

XPath可以读取为:

深入研究属性数组,然后查找具有给定值<DataAttribute><Name>。那里我们需要text()内的Value

提示:尽管有名称空间,但给定的示例未使用任何名称空间。在这种情况下,我们可以省略声明...

© www.soinside.com 2019 - 2024. All rights reserved.