SQL SERVER 将XML变量转为JSON文本

编程学习 2021-07-05 13:43www.dzhlxh.cn编程入门
这篇文章主要介绍了SQL SERVER 将XML变量转为JSON文本的相关资料,需要的朋友可以参考下

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

-- 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"}

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板