欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL SERVER 将XML变量转为JSON文本

程序员文章站 2022-04-14 11:35:26
废话不多说了,直接给大家贴代码了。 -- create function create function [dbo].[fnxmltojson] (@xmlda...

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

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