2013-04-10 83 views
4

我有一個帶有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 *' 
+0

[在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

回答

2

如果你想選擇Value屬性與[XmlDataColumn].value(...) XPath表達式整個NameValuePair元素代替的價值,這應該工作:

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

你的表達僅檢查NameValuePair是否具有屬性Value

如果沒有使用正確的名稱的多個元素,並要檢查其中是否具有價值"One",您可以使用exist(...)方法:

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

I試過這個,但它仍然沒有工作。有關更多詳細信息,請參閱編輯我的問題。 – 2013-04-10 20:11:24

+0

有多個NameValuePair與你正在尋找的Name?我會更新我的答案。 – 2013-04-10 20:26:30

+0

我不認爲有多個元素具有相同的「名稱」,但我會嘗試替代解決方案,看看會發生什麼。 – 2013-04-10 20:32:26

1

另一種選擇是投XML爲varchar ,然後搜索給定的字符串,就好像XML獲得一個varchar字段一樣。

SELECT * 
FROM Table 
WHERE CAST(Column as nvarchar(max)) LIKE '%Name="Foo" Value="One"%' 

我喜歡這個解決方案,因爲它是乾淨的,容易記憶,很難陷入困境,並且可以作爲一個where子句的一部分。

它不像Leo提供的答案那樣動態和完整,但取決於具體情況,它可能是一種「快速」「骯髒」的方式來獲取所需的數據。