SQL Server 2016 for JSON output integer array

前端 未结 2 821
梦毁少年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:52

    In AdventureWorks 2016 CTP3 JSON sample you can find a function that can clean array of key:value pairs and create array od values:

    DROP FUNCTION IF EXISTS dbo.ufnToRawJsonArray
    GO
    CREATE FUNCTION
    [dbo].[ufnToRawJsonArray](@json nvarchar(max), @key nvarchar(400)) returns nvarchar(max)
    AS BEGIN
           declare @new nvarchar(max) = replace(@json, CONCAT('},{"', @key,'":'),',')
           return '[' + substring(@new, 1 + (LEN(@key)+5), LEN(@new) -2 - (LEN(@key)+5)) + ']'
    END
    

    Just provide result of your SELECT FOR JSON expression as @json parameter and name of the key that you want to remove as second parameter. Probably something like:

    select
    e.Name as Employee,
    JSON_QUERY(dbo.ufnToRawJsonArray(
        (select 
         convert(nvarchar(10),ep.PermissionID) as PermID 
         from @EmployeePermissions ep 
         where ep.EmployeeID=e.ID 
         for json path)
      , 'PermID'))
       as 'Permissions'
    from
    @Employees e
    for json path, root('EmployeePermissions')
    

提交回复
热议问题