It turned out that I can’t refer to JSON fields in an INSERT statement when using a cursor in a stored procedure:
Let’s assume that r is a cursor, which refers to a row with the only JSON field “rec”. rec contains the following record: {“inner_field”: “testvalue”}
Then the following statement would not work:
INSERT INTO tbl VALUES(r.rec::$inner_field)
Instead, it would raise an exception:
Could anyone please explain why it’s not possible to refer to json fields like that?
I assume you are using COLLECT to store the query results in an array? If so, try copying r.rec into a new variable and then try your INSERT statement using that new variable.
The example here demonstrates copying into a new variable when using COLLECT:
This is done on the lines:
_id = x.id;
_name = x.name;
Tangential question: what does your stored procedure look like?
I ask because if you’re just using it to extract sub-values from a stream of JSON objects and insert them into a single table, native JSON pipelines with CREATE PIPELINE … FORMAT JSON (perhaps with a SET clause for transforming data) would be faster and likely easier to set up. Even if you do need special stored-procedure-only logic, it’ll generally be more efficient to use FORMAT JSON to extract sub-values from input JSON objects and pass them as structured data to the stored procedure for further processing.
BEGIN
FOR r IN collect(batch) LOOP
IF r.rec::$ATT_CHANGE_OPER = ‘D’ then #RAISE user_exception(“other exception”);
_ROW_ID = r.rec::$ROW_ID;
DELETE FROM s_srv_req_ct_3 WHERE ROW_ID = _ROW_ID;
ELSE