After repeatedly searching and assembling very good methods for converting result sets using the FOR XML and .nodes () commands that are on the Internet, I was able to create this single query (rather than a stored procedure) that does a pretty good job of transforming any arbitrary SQL -query to the JSON array.
The request will encode each row of data as a single JSON object with a leading comma. Data lines are wrapped in brackets, and it is expected that the entire result set will be exported to a file.
I would like to see if anyone can see ways to improve their performance?
Here's a query with an example table:
declare @xd table (col1 varchar(max), col2 int, col3 real, colNull int) insert into @xd select '', null, null, null UNION ALL select 'ItemA', 123, 123.123, null UNION ALL select 'ItemB', 456, 456.456, null UNION ALL select '7890', 789, 789.789, null select '[{}' UNION ALL select ',{' + STUFF(( (select ',' + '"' + r.value('local-name(.)', 'varchar(max)') + '":' + case when r.value('./@xsi:nil', 'varchar(max)') = 'true' then 'null' when isnumeric(r.value('.', 'varchar(max)')) = 1 then r.value('.', 'varchar(max)') else '"' + r.value('.', 'varchar(max)') + '"' end from rows.nodes('/row/*') as x(r) for xml path('')) ), 1, 1, '') + '}' from ( -- Arbitrary query goes here, (fields go where t.* is, table where @xd t is) select (select t.* for xml raw,type,elements XSINIL) rows from @xd t ) xd UNION ALL select ']'
My biggest criticism is that he is insanely slow.
It currently takes around 3:30 for ~ 42,000 lines.
My other big criticism is that it is currently assumed that everything that looks like a number is a number. It is not trying to detect the type of the column at least (and I'm not even sure what it can).
The last minor criticism is that the first row of data will have a comma up and technically it should not. To compensate for this, this requires that an empty JSON object in the first line trigger a JSON array.
Other critical sentences (preferably with solutions), the only real limitation that I have is that the solution can be reproduced with a sufficient degree of repeatability in many arbitrary SQL queries without the need to explicitly identify column names.
I am using SQL Server 2012.
Thanks to everyone who liked, who searched for generalized SQL results -> JSON Array converter, ENJOY!