SQL Server 2016 for JSON output integer array

前端 未结 2 820
梦毁少年i
梦毁少年i 2020-12-06 17:06

I\'d like to get JSON with an array of integers using SQL Server 2016\'s For JSON feature. I\'m stumped on array of integers.

Database table structures:

2条回答
  •  孤城傲影
    2020-12-06 17:58

    You can use FOR XML PATH and STUFF to make PermissionID one string comma separated for each Employee, use QUOTENANE on it, then put all in variable and replace "[ with [ and ]" with ] :

    DECLARE @json NVARCHAR(max)
    
    SELECT @json = REPLACE(REPLACE((
        SELECT  e.Name as [Employee],
                QUOTENAME(STUFF((SELECT ','+CAST(ep.PermissionID as nvarchar(10))
                FROM EmployeePermissions ep
                WHERE e.ID = ep.EmployeeID
                FOR XML PATH('')),1,1,''))
                as [Permissions]
        FROM Employees e 
        FOR JSON AUTO, ROOT('EmployeePermissions')
    ),'"[','['),']"',']')
    
    SELECT @json
    

    Output:

    {"EmployeePermissions":[
        {"Employee":"Bob","Permissions":[1,2]},
        {"Employee":"Randy","Permissions":[1,2,3]}
    ]}
    

    EDIT:

    Another way:

    SELECT '{"EmployeePermissions":[' + STUFF((
    SELECT  ',{"Employee":"' + e.Name + '","Permissions":[' +
            STUFF((SELECT ',' + CAST(PermissionID as nvarchar(10))
            FROM EmployeePermissions ep
            WHERE ep.EmployeeID = e.ID
            FOR XML PATH('')),1,1,'') +']}'
    FROM Employees e
    FOR XML PATH('')),1,1,'') + ']}'
    

    Output:

    {"EmployeePermissions":[
        {"Employee":"Bob","Permissions":[1,2]},
        {"Employee":"Randy","Permissions":[1,2,3]}
    ]}
    

提交回复
热议问题