人生从来没有真正的绝境。无论遭受多少艰辛,无论经历多少苦难,只要一个人的心中还怀着一粒信念的种子,那么总有一天,他就能走出困境,让生命重新开花结果。
废话不多说了,直接给大家贴代码了。
-- 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"}
本文SQLSERVER将XML变量转为JSON文本到此结束。好好扮演自我的主角,做自我该做的事。小编再次感谢大家对我们的支持!