I\'m using Microsoft SQL Server 2016. This version supports JSON.
I have a Person table with the following data:
Pe
Sure It would be very hard (if not impossible) to implement a Json tree using recursive CTE.
ALTER FUNCTION fn_Json(@PersonId INT, @IsRoot INT )
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @Json NVARCHAR(MAX) = '{}', @Name NVARCHAR(MAX) , @Children NVARCHAR(MAX)
SET @Json =
(SELECT P.Name ,JSON_QUERY(dbo.fn_Json(P.PersonId, 2) ) AS Children
FROM dbo.Persons AS P
WHERE P.FatherId = @PersonId
FOR JSON AUTO);
IF(@IsRoot = 1)
BEGIN
SELECT @Name = P.Name FROM dbo.Persons AS P WHERE P.PersonId = @PersonId
SET @Json = '{"Name":"' + @Name + '","Children":' + CAST(@Json AS NVARCHAR(MAX)) + '}'
SET @IsRoot = 2
END
RETURN @Json
END
GO
It worth mentioning that functions can not be built if its interior objects are invalid. Therefore, it is necessary to build the function as:
CREATE FUNCTION fn_Json(@PersonId INT, @IsRoot INT)
RETURNS VARCHAR(MAX)
BEGIN
RETURN 1
END
and then to use the fist code. If you want that the root node is included set
@IsRoot = 1
if not @IsRoot = 2
or some other values