Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL 2008: returning data rows as JSON?

I think this question is like clay pidgeon shooting.. "pull... bang!" .. shot down.. but nevertheless, it's worth asking I believe.

Lots of JS frameworks etc use JSON these days, and for good reason I know. The classic question is "where to transform the data to JSON".

I understand that at some point in the pipeline, you have to convert the data to JSON, be it in the data access layer (I am looking at JSON.NET) or I believe in .NET 4.x there are methods to output/serialize as JSON.

So the question is: Is it really a bad idea to contemplate a SQL function to output as JSON?

Qualifier: I understand trying to output 1000's of rows like that isn't a good idea - in fact not really a good idea for web apps either way unless you really have to. For my requirement, I need possibly 100 rows at a time...

like image 272
Dav.id Avatar asked Aug 07 '10 23:08

Dav.id


People also ask

How do I get SQL output in JSON format?

Format query results as JSON, or export data from SQL Server as JSON, by adding the FOR JSON clause to a SELECT statement. Use the FOR JSON clause to simplify client applications by delegating the formatting of JSON output from the app to SQL Server.

Is JSON compatible with SQL Server 2008?

Simple answer is: no.

Does SQL return JSON?

Use FOR JSON output in SQL Server user-defined functionsYou can create user-defined functions that format result sets as JSON and return this JSON output.


2 Answers

The answer really is: it depends.

If your application is a small one that doesn't receive much use, then by all means do it in the database. The thing to bear in mind though is, what happens when your application is being used by 10x as many users in 12 months time?

If it makes it quick, simple and easy to implement JSON encoding in your stored procedures, rather than in your web code and allows you to get your app out and in use, then that's clearly the way to go. That said, it really doesn't take that much work to do it "properly" with solutions that have been suggested in other answers.

The long and short of it is, take the solution that best fits your current needs, whilst thinking about the impact it'll have if you need to change it in the future.

like image 124
Rob Avatar answered Oct 10 '22 21:10

Rob


This is why [WebMethod] (WebMethodAttribute) exists.

like image 33
Hut8 Avatar answered Oct 10 '22 19:10

Hut8