问题描述
我有一个表,每行存储 1 个 json 对象,我想对存储在每行中的 json 对象调用 OPEnjsON 并将所有结果合并在一起。我不知道我会提前多少行。
以下是一些可供参考的示例数据
DROP TABLE #tmp_json_tbl
DECLARE @json1 NVARCHAR(2048) = N'{
"members": [
{
"name": "bob","status": "subscribed"
},{
"name": "larry","status": "unsubscribed"
}
]
}';
SELECT @json1 as json_obj,1 as jid into #tmp_json_tbl
INSERT into #tmp_json_tbl
VALUES ( N'{
"members": [
{
"name": "bob","status": "unsubscribed"
}
]
}',2 );
SELECT * from #tmp_json_tbl
--how can i recursively union together results for all values of jid?
-- I Could use a cursor but I would rather figure out a way to do it using a recursive cte
SELECT * FROM Openjson((SELECT json_obj from #tmp_json_tbl where jid=1),'$.members')
WITH (
name VARCHAR(80) '$.name',mstatus varchar(100) '$.status'
)```
解决方法
这就是我想要的
SELECT name,m_status
FROM #tmp_json
CROSS APPLY OPENJSON(j,'$.members')
WITH (
name VARCHAR(80) '$.name',m_status varchar(100) '$.status'
)
在这里找到我的答案:How to use OPENJSON on multiple rows