我有一個帶有XML數據類型列的數據庫表。列包含的值是這樣的:SQL Server XML數據類型LIKE比較
<NameValuePairCollection>
<NameValuePair Name="Foo" Value="One" />
<NameValuePair Name="Bar" Value="Two" />
<NameValuePair Name="Baz" Value="Three" />
</NameValuePairCollection>
我想查詢在XML數據類型列有一個"Foo"
的"One"
值的所有行。我無法創建合適的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) *'
UPDATE(以迴應@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 *'
[在SQL Server XML數據類型上使用LIKE語句](https://stackoverflow.com/questions/1832987/use-a-like-statement-on-sql-server-xml-datatype) – Squazz 2017-09-06 11:43:04