相思资源网 Design By www.200059.com

废话不多说了,直接给大家贴代码了。

-- create function
create function [dbo].[fnXmlToJson] (@XmlData xml)
returns nvarchar(max)
as
begin
return
(select stuff( 
(select
*
from 
(select
',{'+ 
stuff(
(select
',"'+
coalesce(b.c.value('local-name(.)', 'NVARCHAR(MAX)'),'')+'":"'+ b.c.value('text()[]','NVARCHAR(MAX)') +'"'
from x.a.nodes('*') b(c) for xml path(''),type).value('(./text())[]','NVARCHAR(MAX)'),,,'')
+'}'
from @XmlData.nodes('/root/*') x(a)) JSON(theLine) 
for xml path(''),type).value('.','NVARCHAR(MAX)' )
,,,''));
end;
go
-- test table and data
create table [dbo].[PivotExample]
(
[Country] [nvarchar]() null
,[Year] [smallint] not null
,[SalesAmount] [money] null
)
on
[PRIMARY];
insert into [dbo].[PivotExample]values('Australia', , .);
insert into [dbo].[PivotExample]values('Germany', , .);
insert into [dbo].[PivotExample]values('United States', , .);
insert into [dbo].[PivotExample]values('France', , .);
declare @xml xml;
set @xml=(select top * from [dbo].[PivotExample] for xml path, root);
select dbo.fnXmlToJson(@xml);
--return string
{"Country":"Australia","Year":"","SalesAmount":"."},
{"Country":"Germany","Year":"","SalesAmount":"."},
{"Country":"United States","Year":"","SalesAmount":"."},
{"Country":"France","Year":"2008","SalesAmount":"922179.0400"}

标签:
sql,将xml转为json

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“SQL SERVER 将XML变量转为JSON文本”

暂无SQL SERVER 将XML变量转为JSON文本的评论...