-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathJsonResultToJsonArray.sql
More file actions
38 lines (37 loc) · 1.13 KB
/
JsonResultToJsonArray.sql
File metadata and controls
38 lines (37 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
CREATE OR ALTER FUNCTION JsonResultToJsonArray
(@JSONResult AS NVARCHAR(MAX))
/**
Summary: >
converts a JSON array-on-array document from a JSON result
produced using FOR JSON AUTO ,INCLUDE_NULL_VALUES
it must include null values!
Author: Phil Factor
Date: 01/10/2018
Examples: >
DECLARE @JSONResult NVARCHAR(MAX)=
(SELECT * FROM adventureworks2016.person.person
FOR JSON AUTO, INCLUDE_NULL_VALUES)
SELECT dbo.JsonResultToJsonArray(@JSONresult)
Returns: >
JSON Array-on-array document
**/
RETURNS NVARCHAR(MAX) --JSON Array-on-array document
--WITH ENCRYPTION|SCHEMABINDING, ...
AS
BEGIN
DECLARE @JSON NVARCHAR(MAX)=(
SELECT '['+ String_Agg(f.EachLine,',')+']'
FROM
(SELECT '['+String_Agg (
CASE WHEN shredded.type=1
THEN '"'+String_Escape(Coalesce(shredded.value,'null'),'json')+'"'
ELSE Coalesce(shredded.value,'null')
END, ',') +']'
AS TheValue
FROM OpenJson(@JSONResult) f
CROSS apply OpenJson(f.value) shredded
GROUP BY f.[Key])f(EachLine)
)
RETURN @json
END
GO