2012-07-17 41 views
0

任何人都可以使用正確的TSQL來解析以下xml。假設我想爲名稱元素找到值爲「y」的項目,但我想要獲取「value」元素的值,在下面的示例中爲「2」。TSQL - 解析XML幫助,搜索特定值

Declare @XML xml 

set @XML =' 
<Test> 
<items> 
<item> 
<name>x</name> 
<value>1</value> 
</item> 
<item> 
<name>y</name> 
<value>2</value> 
</item> 
</items> 
</Test>' 

--i am stuck here 
selecct @XML.value('Test/items/....") 

通過搜索「y」,結果將爲「2」。

這可能嗎?

有人可以幫忙的語法?謝謝!

回答

0

試試這個

select @xml.value('((test/items/item)[2]/value)[1]', 'nvarchar(max)') 

擊穿:

(test/items/item)[2] -- find the second instance of an item tag under a test tag 

((test/items/item)[2]/value)[1] -- then find the first instance of a value tag under that 

值函數不能給予其甚至可以在理論上返回多於一個值的任意表達式。如果有疑問,請將括號括起來,如(some-expression-here)[1]

要找到對應於給定的名稱值:

select @xml.value('((test/items/item)[name="y"][1]/value)[1]', 'nvarchar(max)') 
+0

喜奔,非常感謝。這將工作,如果我知道我在找什麼是在標籤的第二個實例。但是如果我沒有?所以我想在名稱標籤中搜索值「y」並返回值標籤的值。可能應該有更好的命名標籤。 – user1096865 2012-07-17 21:48:28

+0

喜奔,烏爾編輯看起來像什麼我要找的,但是當我運行它,我得到一個空返回 '聲明@XML XML 集@XML =」 X ý ' 選擇@ xml.value('((試驗/項目)[名稱= 「Y」] [1] /值)[1]」, '爲nvarchar(最大)') ' – user1096865 2012-07-17 22:00:35

+0

@ user1096865,糾正。 – Ben 2012-07-17 22:16:28