Jen*_*sen 10 sql-server arrays json sql-server-2016
我想使用SQL Server 2016的For JSON功能获取带有整数数组的JSON .我对整数数组感到困惑.
数据库表结构:
declare @Employees table (ID int, Name nvarchar(50))
insert into @Employees values
(1, 'Bob'),
(2, 'Randy')
declare @Permissions table (ID int, PermissionName nvarchar(50))
insert into @Permissions values
(1, 'Post'),
(2, 'Comment'),
(3, 'Edit'),
(4, 'Delete')
declare @EmployeePermissions table (EmployeeID int, PermissionID int)
insert into @EmployeePermissions values
(1, 1),
(1, 2),
(2, 1),
(2, 2),
(2, 3)
Run Code Online (Sandbox Code Playgroud)
期望的结果:
{"EmployeePermissions": [
{"Employee":"Bob", "Permissions":[1,2]},
{"Employee":"Randy", "Permissions":[1,2,3]}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的最接近的,但不是我想要的.
select
e.Name as Employee,
(select
convert(nvarchar(10),ep.PermissionID) as PermID
from @EmployeePermissions ep
where ep.EmployeeID=e.ID
for json path) as 'Permissions'
from
@Employees e
for json path, root('EmployeePermissions')
Run Code Online (Sandbox Code Playgroud)
收益:
{"EmployeePermissions": [
{"Employee":"Bob", "Permissions":[{"permID":1},{"permID":2}]},
{"Employee":"Randy", "Permissions":[{"permID":1},{"permID":2},{"permID":3}]}
}
Run Code Online (Sandbox Code Playgroud)
在AdventureWorks 2016 CTP3 JSON示例中,您可以找到一个可以清除键:值对的数组并创建数组od值的函数:
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
Run Code Online (Sandbox Code Playgroud)
只需将SELECT FOR JSON表达式的结果作为@json参数和要作为第二个参数删除的键的名称.可能是这样的:
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')
Run Code Online (Sandbox Code Playgroud)
这应该适用于SQL Server 2017 (14.x) 及更高版本
SELECT '[' + STRING_AGG(ep.PermissionID, ',') + ']'
FROM @EmployeePermissions ep
Run Code Online (Sandbox Code Playgroud)
仅当结果字符串超过 8000 字节时,才必须将值转换为 NVarchar(max)
SELECT '[' + STRING_AGG(cast(ep.PermissionID AS NVARCHAR(MAX)), ',') + ']'
FROM @EmployeePermissions ep
Run Code Online (Sandbox Code Playgroud)
完整查询
SELECT e.Name as Employee,
(SELECT
'[' + STRING_AGG(cast(ep.PermissionID AS NVARCHAR(MAX)), ',') + ']'
FROM @EmployeePermissions ep
WHERE ep.EmployeeID=e.ID) as Permissions
FROM
@Employees e
FOR JSON PATH, root('EmployeePermissions')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3770 次 |
| 最近记录: |