Posts

Showing posts from March, 2016

Converting SQL query result into JSON string

Image
SQL doesn't provide native support to translate query result into JSON format. But we can achive this with a little twisting with SQL :). Assume we have a "Computer" table in database with the following data: Now, we can get this data into JSON format using the query below: Here, I've used UNPIVOT operation to de-normalized the data and then constructed the JSON string. Notice that: the ProductCode has been used as the primary key of the objects in this query. You can also achive the same thing without using UNPIVOT; but in that case you have to construct the JSON string for every column you need by yourself. And if you are looking for more generic one to convert each row from a data set regardless of any primary key or without knowing the exact columns to be converted, following stored procedure could be helpful: I hope this will be helpful to someone looking for generating JSON feed directly from SQL. Cheers!