0

任何人都可以帮助我使用正确的 TSQL 来解析以下 xml。假设我想为 name 元素找到值为“y”的项目,但我想获取“value”元素的值,在下面的示例中为“2”。

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”。

这可能吗?

有人可以帮助语法吗?谢谢!

4

2 回答 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)')
于 2012-07-17T21:41:15.790 回答
0

为此,您可能需要使用 XQuery(设计用于查询 XML 数据)。TSQL 支持它的一个子集:

http://msdn.microsoft.com/en-us/library/ms189075%28SQL.90%29.aspx

于 2012-07-17T22:39:19.393 回答