您现在的位置是:网站首页> 编程资料编程资料
SQL SERVER 将XML变量转为JSON文本_MsSql_
2023-05-26
324人已围观
简介 SQL SERVER 将XML变量转为JSON文本_MsSql_
废话不多说了,直接给大家贴代码了。
-- 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"}您可能感兴趣的文章:
相关内容
- 通过Windows批处理命令执行SQL Server数据库备份_MsSql_
- 详解SQL中Group By的用法_MsSql_
- SQL中 decode()函数简介_MsSql_
- sql 数据库出现“只读”提示 解决方法 (sql 错误 5120)_MsSql_
- sql存储过程几个简单例子_MsSql_
- SQL Server 跨库同步数据_MsSql_
- 实例理解SQL中truncate和delete的区别_MsSql_
- SQL Server中NULL的正确使用与空间占用_MsSql_
- SQLSERVER分页查询关于使用Top方式和row_number()解析函数的不同_MsSql_
- SQL中print、sp_helptext的限制与扩展_MsSql_
