您的位置:首页 > 数据库

SQL SERVER 将XML变量转为JSON文本

2016-03-06 00:00 573 查看
废话不多说了,直接给大家贴代码了。

-- 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 Server中将数据导出为XML和Json方法分享
在SQL Server中将数据导出为XML和Json的方法
php 备份数据库代码(生成word,excel,json,xml,sql)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: