Use SQL to return a JSON string

Viewed 16147

This is a "best practice" question. We are having internal discussions on this topic and want to get input from a wider audience.

I need to store my data in a traditional MS SQL Server table with normal columns and rows. I sometimes need to return a DataTable to my web application, and other times I need to return a JSON string.

Currently, I return the table to the middle layer and parse it into a JSON string. This seems to work well for the most part, but does occasionally take a while on large datasets (parsing the data, not returning the table).

I am considering revising the stored procedures to selectively return a DataTable or a JSON string. I would simply add a @isJson bit parameter to the SP.

If the user wanted the string instead of the table the SP would execute a query like this:

DECLARE @result varchar(MAX)
SELECT @result = COALESCE(@results ',', '') + '{id:"' + colId + '",name:"' + colName + '"}'
    FROM MyTable
SELECT @result

This produces something like the following:

{id:"1342",name:"row1"},{id:"3424",name:"row2"}

Of course, the user can also get the table by passing false to the @isJson parameter.

I want to be clear that the data storage isn't affected, nor are any of the existing views and other processes. This is a change to ONLY the results of some stored procedures.

My questions are:

  1. Has anyone tried this in a large application? If so, what was the result?
  2. What issues have you seen/would you expect with this approach?
  3. Is there a better faster way to go from table to JSON in SQL Server other than modifying the stored procedure in this way or parsing the string in the middle tier?
2 Answers
Related