Hello AskTom-Team,
is there a possibility to contrain and check JSON data?
For example:
insert into test(questionnaire_id, var_val, year)
'{
"f1": "2571",
"f11": "38124",
"f31": "332.64",
"f41": "332.64",
"f190": "4.62",
"f194": "7.00",
"f201": "46.86",
"f488": "Braunschweig"
}',2017);
I want to check e.g.
1) wether the value for f1 exists in an other table wz,
2) wether the value belonging to f31 is equal or greater as 0,
3) wether the combination of values from f11 and f488 (e.g. 38124, Braunschweig) exists in a table plz.
I found something for sql server tables but I cannot transform this to oracle tables. I really appreciate your help.
Thanks!
1. Add a virtual column returning the value for f1. And create a foreign key on that.
2. Add a check constraint verifying the value >= 0.
3. Not sure what you're asking here...
create table wz (
f1 varchar2(10) primary key
);
create table test (
questionnaire_id integer,
var_val varchar2(1000)
check ( var_val is json ),
year integer
);
insert into wz values ( '2571' );
commit;
insert into test(questionnaire_id, var_val, year)
values ( 1, '{
"f1": "2571",
"f11": "38124",
"f31": "332.64",
"f41": "332.64",
"f190": "4.62",
"f194": "7.00",
"f201": "46.86",
"f488": "Braunschweig"
}',2017
);
alter table test
add f1 varchar2(10)
generated always as (
json_value ( var_val, '$.f1' returning varchar2(10) )
)
references wz ( f1 );
insert into test(questionnaire_id, var_val, year)
values ( 2, '{
"f1": "not here",
"f11": "38124",
"f31": "332.64",
"f41": "332.64",
"f190": "4.62",
"f194": "7.00",
"f201": "46.86",
"f488": "Braunschweig"
}',2017
);
ORA-02291: integrity constraint (CHRIS.SYS_C009543) violated - parent key not found
alter table test
add constraint f31_c
check ( json_value ( var_val, '$.f31' ) >= 0 );
insert into test(questionnaire_id, var_val, year)
values ( 3, '{
"f1": "2571",
"f11": "38124",
"f31": -1,
"f41": "332.64",
"f190": "4.62",
"f194": "7.00",
"f201": "46.86",
"f488": "Braunschweig"
}',2017
);
ORA-02290: check constraint (CHRIS.F31_C) violated
select questionnaire_id from test;
QUESTIONNAIRE_ID
1