首页 > 数据库 > SQL Server > 正文

SQL SERVER 将XML变量转为JSON文本

2020-07-25 12:47:18
字体:
来源:转载
供稿:网友

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

-- create functioncreate function [dbo].[fnXmlToJson] (@XmlData xml)returns nvarchar(max)asbeginreturn(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 datacreate 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"}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表