2

I am trying to produce some oracle records snapshots using JSON_OBJECT but, surprisingly it seems that I cannot use a variable in the clause statement?

CREATE TABLE SAMPLE(
  person_id NUMBER,
  first_name VARCHAR2(50) NOT NULL,
  last_name VARCHAR2(50) NOT NULL,
  PRIMARY KEY(person_id)
);

INSERT INTO SAMPLE (person_id, first_name, last_name)
  VALUES (1, 'John', 'Doe');
INSERT INTO SAMPLE (person_id, first_name, last_name)
  VALUES (2, 'Mary', 'Doe');

SET SERVEROUTPUT ON
DECLARE
  name VARCHAR2(50) := 'John';   
  jsonResult CLOB;
BEGIN
  SELECT JSON_OBJECT(*)
  INTO jsonResult
  FROM SAMPLE
  WHERE first_name = name;
  DBMS_OUTPUT.PUT_LINE( jsonResult );
END;

Error report:
ORA-00904: "NAME": invalid identifier
ORA-06512: at line 5

4
  • hope the new example is of your liking Commented May 27, 2021 at 21:46
  • What database version are you using? It appears that JSON_OBJECT(*) was introduced in Oracle 19 so if you are using a version prior to that then you will have to list every key. Commented May 27, 2021 at 21:57
  • Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production Commented May 27, 2021 at 22:04
  • This looks to be a bug. The query works if you use a text literal but not with a PL/SQL variable. Trying WHERE first_name = (SELECT name FROM DUAL); gives an internal error. Commented May 27, 2021 at 22:25

1 Answer 1

1

For now I found one, sad, workaround... replacing the wildcard "*" for the list of columns.

This works:

-- WORKs!
SET SERVEROUTPUT ON
DECLARE 
   name VARCHAR2(50) := 'John';
   jsonResult CLOB;
BEGIN
    SELECT JSON_OBJECT(person_id, first_name, last_name ) INTO jsonResult FROM SAMPLE WHERE first_name = name;
    DBMS_OUTPUT.PUT_LINE( jsonResult );
END;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.