从XML数据中选择查询

时间:2013-07-20 20:31:10

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我正在尝试从XML数据中获取结果,但只获取第一个节点的值。

create table #temp(xmlString nvarchar(max))
insert into #temp (xmlString) values 
('<?xml version="1.0" ?><response status = "ERROR">
<error>Error1</error>
<error>Error2</error>
</response>')

我想要一个结果:

Error1, Error2

请帮忙。 感谢

2 个答案:

答案 0 :(得分:3)

select
    x.c.value('.', 'nvarchar(128)') as value
from (select cast(xmlString as xml) as data from temp) as t
    outer apply t.data.nodes('/response/error') as x(c)

SQL FIDDLE EXAMPLE

答案 1 :(得分:0)

正确答案

select STUFF((select ',' +  x.c.value('.', 'nvarchar(max)') 
from (select cast(xmlString as xml) as data from #temp)
as t outer apply t.data.nodes('/response/error')
as x(c)for xml path('')), 1, 1, '') as Errors