我有以下XML,存储在一个表的一列中:
<Selections>
<TextSelection>
<words>
<index> 0 </index>
<text> hi </text>
</words>
</TextSelection>
<TextSelection>
<words>
<index> 1 </index>
<text> hello </text>
</words>
</TextSelection>
<id> 1 </id>
<followtext> yes </followtext>
<text> hi hello </text>
<response> greetings </response>
<TextSelection>
<words>
<index> 2 </index>
<text> dora </text>
</words>
</TextSelection>
<TextSelection>
<words>
<index> 3 </index>
<text> toy</text>
</words>
</TextSelection>
<id> 2 </id>
<followtext> yes </followtext>
<text> dora toy </text>
<response> like dora </response>
</Selections>
我需要从上面的XML中检索文本和响应。
我检索值的查询是:
select xml.value('(/Selections/TextSelection/words/text)[1]', 'varchar(max)') as Selections, xml.value('(/Selections/TextSelection/words/response)[1]', 'varchar(max)') as Response from QResponse where rid = '20';
但它返回Null值。我如何获得这些价值?而且我还需要迭代下一个后续节点才能获得该值?如何做到这一点?
输出将是:
text response
------------------------
hi hello greetings
dora toy like dora
答案 0 :(得分:1)
基于对XML和select语句的简要回顾,我怀疑你的XPath是不正确的 也许试试:
/Selections/TextSelection[1]/words[1]/text[1]
/Selections/response[1]
此外,以下链接可能会有所帮助:
http://blog.sqlauthority.com/2010/06/23/sqlauthority-news-guest-post-select-from-xml-jacob-sebastian/
此致
答案 1 :(得分:0)
你的问题是你想要一个兄弟姐妹.......但基本上“跟随我的项目”。
,这导致:
“XQuery [value()]:不支持XQuery语法'follow-sibling'。”
:其中
这是一次尝试......将显示错误。
declare @MyData XML
select @MyData = '
<Selections>
<id>1</id>
<followtext> yes </followtext>
<text> hi hello </text>
<response> greetings </response>
<id>2</id>
<followtext> yes </followtext>
<text> dora toy </text>
<response> like dora </response>
</Selections>
'
/*
text response
------------------------
hi hello greetings
dora toy like dora
*/
SELECT T.c.value('(.)[1]', 'varchar(100)') AS [text]
, T.c.value('(../response)[1]', 'varchar(100)') AS responseOne
, T.c.value('../following-sibling::response)', 'varchar(100)') AS responseTwo
FROM @MyData.nodes('(/Selections/text)') T(c)