How to generate hierarchical JSON data with Microsoft SQL Server 2016?

后端 未结 2 621
难免孤独
难免孤独 2021-01-04 21:20

I\'m using Microsoft SQL Server 2016. This version supports JSON.

I have a Person table with the following data:

Pe         


        
2条回答
  •  耶瑟儿~
    2021-01-04 22:09

    Sure It would be very hard (if not impossible) to implement a Json tree using recursive CTE.

    However, using recursive function is really helpful and solves the Problem:

    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

提交回复
热议问题