鉴于存储在nvarchar(max)
列中的以下JSON,如何生成显示的表?我可以说的是,如果嵌套对象是[]
,数组而不是结构{}
DECLARE @JSON AS NVARCHAR(MAX);
SET @JSON = N'{
"ACCOUNT": 1
, "USERS" : {
"BOB" : 1
, "JOHN" : 2
, "RODGER" : 3
}
}';
SELECT JSON_QUERY(@JSON,'$.USERS')
ACCOUNT USER USER_VALUE
================================
1 BOB 1
1 JOHN 2
1 RODGER 3
答案 0 :(得分:2)
您可以尝试使用OPENJSON
(具有ACCOUNT
和USERS
列的显式结构)和其他CROSS APPLY
的下一种方法:
-- JSON
DECLARE @JSON AS NVARCHAR(MAX);
SET @JSON = N'{
"ACCOUNT": 1
, "USERS" : {
"BOB" : 1
, "JOHN" : 2
, "RODGER" : 3
}
}';
-- Statement
SELECT i.ACCOUNT, v.[key] AS [USER], v.[value] AS USER_VALUE
FROM OPENJSON(@json)
WITH (
ACCOUNT int '$.ACCOUNT',
USERS nvarchar(max) '$.USERS' AS JSON
) i
CROSS APPLY (
SELECT *
FROM OPENJSON(i.USERS)
) v
输出:
ACCOUNT USER USER_VALUE
1 BOB 1
1 JOHN 2
1 RODGER 3