Last active
March 1, 2016 15:23
-
-
Save roe3p/aa47e49962df150dba91 to your computer and use it in GitHub Desktop.
T-SQL to return contents of a table as a JSON object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Gets all records in a SQL table and returns it as a single-dimension JSON object. | |
//If the parameter @VarName is passed, the returned output assignes the object to that variable. | |
CREATE PROCEDURE [dbo].[pGetJSONFromTable] @ObjectName VARCHAR(255), @VarName VARCHAR(255) = NULL, @registries_per_request smallint = null | |
AS | |
BEGIN | |
IF OBJECT_ID(@ObjectName) IS NULL | |
BEGIN | |
SELECT Json = ''; | |
RETURN | |
END; | |
DECLARE @Top NVARCHAR(20) = CASE WHEN @registries_per_request IS NOT NULL | |
THEN 'TOP (' + CAST(@registries_per_request AS NVARCHAR) + ') ' | |
ELSE '' | |
END; | |
DECLARE @SQL NVARCHAR(MAX) = N'SELECT ' + @Top + '* INTO ##T ' + | |
'FROM ' + @ObjectName + ''; | |
EXECUTE SP_EXECUTESQL @SQL; | |
DECLARE @X NVARCHAR(max) = N'[' + (SELECT * FROM ##T FOR XML PATH('')) + ']'; | |
SET @X = N'' + REPLACE(@X, CHAR(10), '\n') | |
SET @X = N'' + REPLACE(@X, CHAR(13), '') | |
SET @X = N'' + REPLACE(@X, '"', '"') | |
SET @X = N'' + REPLACE(@X, '''', ''') | |
SELECT @X = REPLACE(@X, '<' + Name + '>', | |
CASE WHEN ROW_NUMBER() OVER(ORDER BY Column_ID) = 1 THEN '{"' | |
ELSE '"' END + Name + '":"'), | |
@X = REPLACE(@X, '</' + Name + '>', '",'), | |
@X = REPLACE(@X, ',{', '}, ' + CHAR(13) + CHAR(10) + '{'), | |
@X = REPLACE(@X, ',]', '}]') | |
FROM sys.columns | |
WHERE [Object_ID] = OBJECT_ID(@ObjectName) | |
ORDER BY Column_ID; | |
DROP TABLE ##T; | |
SELECT Json = ISNULL('var ' + @VarName + ' = ', N'') + @X, | |
len(@x) AS Length; | |
END | |
GO | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment