Jes*_*ebb 5 xml sql sql-server xquery
我有一个带有 XML 数据类型列的数据库表。该列包含如下值:
<NameValuePairCollection>
<NameValuePair Name="Foo" Value="One" />
<NameValuePair Name="Bar" Value="Two" />
<NameValuePair Name="Baz" Value="Three" />
</NameValuePairCollection>
Run Code Online (Sandbox Code Playgroud)
我想查询在XML数据类型列的数值为所有行"One"了"Foo"。我在创建适当的 XQuery 来过滤结果时遇到问题。
我发现了几个相关的 SO 问题,它们对我的尝试有所帮助,但我仍然无法让它发挥作用。
如何查询 SQL Server XML 列中的值在
SQL Server XML 数据类型上使用 LIKE 语句
这是我到目前为止的 SQL:
select *
from MyTable
where [XmlDataColumn].value('((/NameValuePairCollection/NameValuePair)[@Name="Foo"])[@Value]', 'varchar(max)') = 'One'
order by ID desc
Run Code Online (Sandbox Code Playgroud)
这是我现在遇到的错误:
XQuery [MyTable.XmlDataColumn.value()]: Cannot atomize/apply data() on expression that contains type 'NameValuePair' within inferred type 'element(NameValuePair,#anonymous) *'
Run Code Online (Sandbox Code Playgroud)
更新(响应@LeoWörteler 的建议)
根据您的回答,我将 SQL 更改为:
select *
from MyTable with(nolock)
where [XmlDataColumn].value('/NameValuePairCollection/NameValuePair[@Name="Subject"]/@Value', 'varchar(max)') = 'One'
order by ID desc
Run Code Online (Sandbox Code Playgroud)
但这仍然不起作用。我收到以下错误:
XQuery [MyTable.XmlDataColumn.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xs:string *'
Run Code Online (Sandbox Code Playgroud)
如果您想选择属性的值Value而不是NameValuePair使用 XPath 表达式中的整个元素[XmlDataColumn].value(...),则这应该可行:
/NameValuePairCollection/NameValuePair[@Name="Foo"]/@Value
Run Code Online (Sandbox Code Playgroud)
您的表达式仅检查 是否NameValuePair具有 attribute Value。
如果有多个具有正确名称的元素,并且您想检查其中是否有任何一个具有 value "One",您可以使用以下exist(...)方法:
where [XmlDataColumn].exist(
'/NameValuePairCollection/NameValuePair[@Name="Subject" and @Value="One"]') = 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7939 次 |
| 最近记录: |