SQL SERVER 將XML變量轉為JSON文本。本站提示廣大學習愛好者:(SQL SERVER 將XML變量轉為JSON文本)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL SERVER 將XML變量轉為JSON文本正文
空話不多說了,直接給年夜家貼代碼了。
-- 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"}