废话不多说了,直接给大家贴代码了。--createfunctioncreatefunction[dbo].[fnXmlToJson](@XmlDataxml)returnsnvarchar(max)asbeginreturn(selectstuff((select*from(select',{'+stuff((select',"'+coalesce(b.c.value('local-name(.)','NVARCHAR(MAX)'),'')+'":"'+b.c.value('text()[]','NVARCHAR(MAX)')+'"'fromx.a.nodes('*')b(c)forxmlpath(''),type).value('(./text())[]','NVARCHAR(MAX)'),,,'')+'}'[email protected]('/root/*')x(a))JSON(theLine)forxmlpath(''),type).value('.','NVARCHAR(MAX)'),,,''));end;go--testtableanddatacreatetable[db
废话不多说了,直接给大家贴代码了。
-- 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"}
标签: SQLSERVER XML 变量 转为 JSON 文本
声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!