微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL Server中将查询结果转换为Json格式脚本分享

脚本源码:

代码如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE[dbo].[SerializeJSON](
@Parametersql AS VARCHAR(MAX)
)
AS
BEGIN

DECLARE @sql NVARCHAR(MAX)
DECLARE @XMLString VARCHAR(MAX)
DECLARE @XML XML
DECLARE @Paramlist NVARCHAR(1000)
SET @Paramlist = XML OUTPUT'
SET @SQL = 'WITH PrepareTable (XMLString)'
SET @SQL = @SQL + 'AS('
SET @SQL = @SQL + @ParameterSQL+ 'FOR XML RAW,TYPE,ELEMENTS'
SET @SQL = @SQL + ')'
SET @SQL = @SQL + 'SELECT @XML=[XMLString]FROM[PrepareTable]'
EXEC sp_executesql @SQL,@Paramlist,@XML=@XML OUTPUT
SET @XMLString=CAST(@XML AS VARCHAR(MAX))

DECLARE @JSON VARCHAR(MAX)
DECLARE @Row VARCHAR(MAX)
DECLARE @RowStart INT
DECLARE @RowEnd INT
DECLARE @FieldStart INT
DECLARE @FieldEnd INT
DECLARE @KEY VARCHAR(MAX)
DECLARE @Value VARCHAR(MAX)

DECLARE @StartRoot VARCHAR(100);SET @StartRoot=''
DECLARE @EndRoot VARCHAR(100);SET @EndRoot='
'
DECLARE @StartField VARCHAR(100);SET @StartField='<'
DECLARE @EndField VARCHAR(100);SET @EndField='>'

SET @RowStart=CharIndex(@StartRoot,@XMLString,0)
SET @JSON=''
WHILE @RowStart>0
BEGIN
SET @RowStart=@RowStart+Len(@StartRoot)
SET @RowEnd=CharIndex(@EndRoot,@RowStart)
SET @Row=SubString(@XMLString,@RowStart,@RowEnd-@RowStart)
SET @JSON=@JSON+'{'

-- for each row
SET @FieldStart=CharIndex(@StartField,@Row,0)
WHILE @FieldStart>0
BEGIN
-- parse node key
SET @FieldStart=@FieldStart+Len(@StartField)
SET @FieldEnd=CharIndex(@EndField,@FieldStart)
SET @KEY=SubString(@Row,@FieldStart,@FieldEnd-@FieldStart)
SET @JSON=@JSON+'"

-- parse node value
SET @FieldStart=@FieldEnd+1
SET @FieldEnd=CharIndex(' SET @Value=SubString(@Row,@FieldEnd-@FieldStart)
SET @JSON=@JSON+'"


SET @FieldStart=@FieldStart+Len(@StartField)
SET @FieldEnd=CharIndex(@EndField,@FieldStart)
SET @FieldStart=CharIndex(@StartField,@FieldEnd)
END
IF LEN(@JSON)>0SET @JSON=SubString(@JSON,LEN(@JSON))
SET @JSON=@JSON+'},'
--/ for each row

SET @RowStart=CharIndex(@StartRoot,@RowEnd)
END
IF LEN(@JSON)>0SET @JSON=SubString(@JSON,LEN(@JSON))
SET @JSON='['+@JSON+']'
SELECT @JSON

END
GO

使用方法:

代码如下:
EXEC[SerializeJSON]'SELECT*FROM[Employee_TBL]'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐