12.2 版包含直接从 SQL 查询生成 JSON 文档的新功能。实现目标的最简单方法是使用函数:JSON_OBJECT
和JSON_ARRAYAGG
。
create table tab as
select level col1, 'value '||level col2 from dual connect by level <= 2
/
select max (rownum) rn, json_arrayagg (
json_object (
key 'col1' value col1,
key 'col2' value col2
) format json returning clob
) as json_doc
from tab;
结果:
RN JSON_DOC
---------- ---------------------------------------------------------
2 [{"col1":1,"col2":"value 1"},{"col1":2,"col2":"value 2"}]
用大量数据进行测试:
select rn, length (json_doc) json_size, json_doc from (
<query mentoined above here>
cross join (select dummy from dual connect by level <= 1e5)
);
RN JSON_SIZE JSON_DOC
---------- ---------- ---------------------------------------------------------
200000 5600001 [{"col1":1,"col2":"value 1"},{"col1":2,"col2":"value 2"},
在慢速测试机器上花了大约 1 秒。创建 5,6M JSON。
在 19c 版本中,函数的语法JSON_OBJECT
被简化了。
上面的查询现在看起来像这样:
select json_arrayagg (
json_object (*) returning clob
) as json_doc
from tab;
在实时 SQL上。