我想使用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)
期望的结果:
{"EmployeePermissions": [
{"Employee":"Bob", "Permissions":[1,2]},
{"Employee":"Randy", "Permissions":[1,2,3]}
}
这是我最接近的,但不是我想要的。
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')
返回:
{"EmployeePermissions": [
{"Employee":"Bob", "Permissions":[{"permID":1},{"permID":2}]},
{"Employee":"Randy", "Permissions":[{"permID":1},{"permID":2},{"permID":3}]}
}
答案 0 :(得分:9)
在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
只需将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')
答案 1 :(得分:2)
您可以使用FOR XML PATH
和STUFF
为每个PermissionID
分隔Employee
个字符串逗号,在其上使用QUOTENANE
,然后将所有变量放入变量并将"[
替换为[
,将]"
替换为]
:
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
输出:
{"EmployeePermissions":[
{"Employee":"Bob","Permissions":[1,2]},
{"Employee":"Randy","Permissions":[1,2,3]}
]}
修改强>
另一种方式:
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,'') + ']}'
输出:
{"EmployeePermissions":[
{"Employee":"Bob","Permissions":[1,2]},
{"Employee":"Randy","Permissions":[1,2,3]}
]}