很久之前用到的,現在整理在這,裡面一些代碼來源於網上,不過有些bug已被我修改了。
1.查詢結果轉XML
DECLARE @ParameterSQL NVARCHAR(MAX)='SELECT * FROM table'; DECLARE @SQL NVARCHAR(MAX) DECLARE @XMLString VARCHAR(MAX) DECLARE @XML XML DECLARE @Paramlist NVARCHAR(1000) SET @Paramlist = N'@XML 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)) SELECT @XML; SELECT @XMLString;
其中@ParameterSQL為要查詢的語句,@XMLXML格式數據,@XMLStringXML轉成字符串
2.查詢結果轉JSON
查詢結果轉換成json需要經過兩個步驟,首先將查詢結果轉成XML數據,然後通過XML數據轉成json
XML轉JSON的存儲過程如下:
CREATE PROCEDURE [dbo].[SerializeJSON] ( @XML XML, @json_xml NVARCHAR(MAX) OUTPUT ) AS BEGIN DECLARE @XMLString NVARCHAR(MAX); SET @XMLString = CAST(@XML AS NVARCHAR(MAX)); BEGIN TRY--//開始捕捉異常 DECLARE @JSON NVARCHAR(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 = '<row>'; DECLARE @EndRoot VARCHAR(100); SET @EndRoot = '</row>'; 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, @XMLString, @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, @Row, @FieldStart); DECLARE @end INT = CHARINDEX('/>', @Row, @FieldStart); IF @end<1 OR @end>@FieldEnd BEGIN SET @KEY = SUBSTRING(@Row, @FieldStart, @FieldEnd - @FieldStart); SET @JSON = @JSON + '"' + @KEY + '":'; --//parse node value SET @FieldStart = @FieldEnd + 1; SET @FieldEnd = CHARINDEX('</', @Row, @FieldStart); SET @Value = SUBSTRING(@Row, @FieldStart, @FieldEnd - @FieldStart); SET @JSON = @JSON + '"' + @Value + '",'; END; SET @FieldStart = @FieldStart + LEN(@StartField); SET @FieldEnd = CHARINDEX(@EndField, @Row, @FieldStart); SET @FieldStart = CHARINDEX(@StartField, @Row, @FieldEnd); END; IF LEN(@JSON)>0 SET @JSON = SUBSTRING(@JSON, 0, LEN(@JSON)); SET @JSON = @JSON + '},'; --// for each row SET @RowStart = CHARINDEX(@StartRoot, @XMLString, @RowEnd); END; IF LEN(@JSON)>0 SET @JSON = SUBSTRING(@JSON, 0, LEN(@JSON)); --//SET @JSON = '[' + @JSON + ']'; SET @json_xml = @JSON; END TRY--//結束捕捉異常 BEGIN CATCH--//有異常被捕獲 SET @json_xml = @XMLString; END CATCH;--//結束異常處理 END;
以上所述是小編給大家介紹的SqlServer將查詢結果轉換為XML和JSON,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對 網站的支持!