假设我有一张这样的桌子
id name address Doc
1 {1:mark,2:john} {1:Home,2:Work,3:Club} {NI:299,Pass:A159}
2 {1:Max,2:Mo} {1:Home} {NI:300011}
我想要的是编写一个查询来根据键从单元格中选择一个值 例如
i want the value which has key = 2 in column named(Name) where id=1
所以它应该返回
john
等等。 那么我怎样才能在不使用子字符串的情况下做类似的事情呢?
假设您有有效的 json 值:
CREATE TABLE mytable (
id int,
name VARCHAR2 (200) ,
address VARCHAR2 (200),
Doc VARCHAR2 (200),
CONSTRAINT ensure_json CHECK (name IS JSON)
);
insert into mytable
select 1, '{"1":"mark","2":"john"}', '{"1":"Home","2":"Work","3":"Club"}', '{"NI":299,"Pass":"A159"}' from dual union all
select 2, '{"1":"Max","2":"Mo"}', '{"1":"Home"}', '{"NI":300011}' from dual
查询可以是:
select t.name."2"
from mytable t
where id = 1
如果无效 JSON 中只有键值对,则:
with cte as (
select REGEXP_REPLACE(name,
'([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)',
'"\1":"\2"') as name
from mytable t
where id = 1
)
select json_value(name, '$."2"')
from cte