gpt4 book ai didi

sql - SQL Server XML 数据类型中的 LIKE 比较

转载 作者:数据小太阳 更新时间:2023-10-29 02:06:37 24 4
gpt4 key购买 nike

我有一个带有 XML 数据类型列的数据库表。该列包含如下值:

<NameValuePairCollection>
<NameValuePair Name="Foo" Value="One" />
<NameValuePair Name="Bar" Value="Two" />
<NameValuePair Name="Baz" Value="Three" />
</NameValuePairCollection>

我正在尝试查询 XML 数据类型列的 "One" 值为 "Foo" 的所有行。我在创建适当的 XQuery 来过滤结果时遇到问题。

我发现了几个相关的 SO 问题,它们对我的尝试有所帮助,但我仍然无法让它工作。

How can I query a value in SQL Server XML column
Use a LIKE statment on SQL Server XML Datatype

这是我到目前为止的 SQL:

select * 
from MyTable
where [XmlDataColumn].value('((/NameValuePairCollection/NameValuePair)[@Name="Foo"])[@Value]', 'varchar(max)') = 'One'
order by ID desc

这是我现在遇到的错误:

XQuery [MyTable.XmlDataColumn.value()]: Cannot atomize/apply data() on expression that contains type 'NameValuePair' within inferred type 'element(NameValuePair,#anonymous) *'

更新(回应@LeoWörteler 的建议)

根据您的回答,我将 SQL 更改为:

select * 
from MyTable with(nolock)
where [XmlDataColumn].value('/NameValuePairCollection/NameValuePair[@Name="Subject"]/@Value', 'varchar(max)') = 'One'
order by ID desc

虽然这仍然不起作用。我收到以下错误:

XQuery [MyTable.XmlDataColumn.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xs:string *'

最佳答案

如果你想选择 Value 属性的值而不是整个 NameValuePair 元素,在 [XmlDataColumn].value(.. .),这应该有效:

/NameValuePairCollection/NameValuePair[@Name="Foo"]/@Value

您的表达式仅检查 NameValuePair 是否具有属性 Value

如果有多个具有正确名称的元素,并且您想检查其中是否有值 "One",您可以使用 exist(...)方法:

where [XmlDataColumn].exist(
'/NameValuePairCollection/NameValuePair[@Name="Subject" and @Value="One"]') = 1

关于sql - SQL Server XML 数据类型中的 LIKE 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15934320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com