[英]Updating json array of objects in Oracle
嗨,我在 Oracle 数据库中有一个 json 列,其中的数据如 [{"id":100, "make":"BMW"},{"id":110,"make":"mercedes"}]... .现在我如何使用 sql/plsql 将 ID 为 110 的 object 的品牌更新为 Toyota ..谢谢..
您可以使用json_table()
版本的json_table()
函数来解析 json 列。 顺便说一句,可以通过为相关字符串类型列添加检查约束来检出诸如clob
、 varchar2
类的字符串类型列。 所以使用:
update tab
set jsdata=(select case when js.id = 110 then replace(jsdata,js.make,'toyota') end
from tab
cross join
json_table(jsdata, '$[*]'
columns(make varchar2(50) path '$.make',
id int path '$.id')) js
where js.id = 110 )
不幸的是,更改数组中的数据并不容易。
create table t(
id number primary key,
json_ds varchar2(4000) check(json_ds is json)
);
insert into t values (1, '[{"id":100, "make":"BMW"},{"id":110,"make":"mercedes"}]');
commit;
update /*+ WITH_PLSQL */ t a
set json_ds = (
with function update_json(p_in in varchar2) return varchar2 is
l_ja json_array_t;
l_po json_object_t;
l_id number;
begin
l_ja := json_array_t.parse(p_in);
for i in 0..l_ja.get_size - 1 loop
l_po := json_object_t(l_ja.get(i));
l_id := l_po.get_number('id');
if l_id = 110 then
l_po.put('make', 'Toyota');
end if;
end loop;
return l_ja.to_string;
end update_json;
select update_json(a.json_ds) from dual
)
where id = 1;
/
select * from t;
ID JSON_DS
1 [{"id":100,"make":"BMW"},{"id":110,"make":"Toyota"}]
最好的问候, 炖阿什顿
您可以在 19.8 及更高版本中使用 JSON_TRANSFORM()。
with example as
(select '[{"id":100, "make":"BMW"},{"id":110,"make":"mercedes"}]' as json from dual)
select json_transform(example.json, set '$[*]?(@.id==110).make' = 'Toyota') as newjson from example;
Output:
[{"id":100,"make":"宝马"},{"id":110,"make":"丰田"}]
您也可以使用 JSON_MERGEPATCH(19c 及更高版本)但它无法在 arrays 内更新,需要更新整个数组
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.