0

我有一个每行存储 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": "subscribed"
        },
        {
            "name": "larry",
            "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'  
 
)```
4

1 回答 1

0

这就是我想要的

SELECT name, m_status
FROM   #tmp_json
CROSS APPLY OPENJSON(j, '$.members') 
WITH (   
  name VARCHAR(80)       '$.name',  
  m_status  varchar(100) '$.status'  
)

在这里找到我的答案:如何在多行上使用 OPENJSON

于 2021-03-26T18:41:38.467 回答