我需要连接下面xml中的一些属性:
set @data = N'<properties>
<property>
<name>first</name>
</property>
<property>
<name>second</name>
</property>
<property>
<name>third</name>
</property>
</properties>'
如果我要提取的结果是:第一,第二,第三,可以使用这样一个简单的语句:
declare @result nvarchar(max)
select @result = coalesce(@result + ',', '') + x.value(N'(name)[1]', N'nvarchar(50)')
from @data.nodes(N'/properties/property') as xtbl(x)
如果我要提取的结果是: first =#。first,second =#。second,third =#.third ,我的解决方案如下所示:
declare mycursor cursor fast_forward
for select
x.value(N'(name)[1]', N'nvarchar(50)')
from
@data.nodes(N'/properties/property') AS xtbl(x)
declare @name nvarchar(50), @result nvarchar(max) = N'$name$=#.$name2$'
open mycursor
fetch next from mycursor into @name
while @@fetch_status = 0
begin
set @result= replace(@result, N'$name$', @name)
set @result = replace(@result, N'$name2$', @name + N',$name$=#.$name2$')
fetch next from mycursor into @name
end
close mycursor;
deallocate mycursor;
set @result = replace(@result, N',$name$=#.$name2$', '')
如何在不使用任何循环的情况下执行此操作?
答案 0 :(得分:1)
您可以使用:
declare @result nvarchar(max)=''
select @result = @result + x.value(N'(name)[1]', N'nvarchar(50)')
+ '=#.'
+ x.value(N'(name)[1]', N'nvarchar(50)')
+ ','
from @data.nodes(N'/properties/property') as xtbl(X)
select @result = left(@result, LEN(@result)-1)
print @result