oracle JSON到SQL对象

os8fio9y  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(117)
CREATE OR REPLACE TYPE json_record_type
AS
  OBJECT
  (
    id    NUMBER,
    name  VARCHAR2(50),
    ` age NUMBER );
CREATE OR REPLACE TYPE json_table_type
AS
  TABLE OF json_record_type;
  ;
  DECLARE
    json_data CLOB := '{ "data": [ {"id": 1, "name": "John", "age": 30}, {"id": 2, "name": "Alice", "age": 25} ] }';
    json_obj json_table_type;
  BEGIN
    SELECT * BULK COLLECT
    INTO json_obj
    FROM JSON_TABLE(json_data, '$.data[*]' COLUMNS ( ID NUMBER PATH '$.id', name VARCHAR2(50) PATH '$.name', age NUMBER PATH '$.age' ) );
    FOR i IN 1..json_obj.COUNT
    LOOP
      DBMS_OUTPUT.PUT_LINE('ID: ' || json_obj(i).id || ', Name: ' || json_obj(i).name || ', Age: ' || json_obj(i).age);
    END LOOP;
  END;
  '
qni6mghb

qni6mghb1#

给定您的类型(不包括随机附加字符):

CREATE OR REPLACE TYPE json_record_type AS OBJECT(
  id    NUMBER,
  name  VARCHAR2(50),
  age   NUMBER
);
CREATE OR REPLACE TYPE json_table_type AS TABLE OF json_record_type;

将对象的示例(包含值)大容量收集到集合中:

DECLARE
  json_data CLOB := '{ "data": [ {"id": 1, "name": "John", "age": 30}, {"id": 2, "name": "Alice", "age": 25} ] }';
  json_obj json_table_type;
BEGIN
  SELECT json_record_type(id, name, age)
  BULK COLLECT INTO json_obj
  FROM   JSON_TABLE(
           json_data,
           '$.data[*]'
           COLUMNS (
             ID   NUMBER       PATH '$.id',
             name VARCHAR2(50) PATH '$.name',
             age  NUMBER       PATH '$.age'
           )
         );

  FOR i IN 1..json_obj.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(
      'ID: ' || json_obj(i).id
      || ', Name: ' || json_obj(i).name
      || ', Age: ' || json_obj(i).age
    );
  END LOOP;
END;
/

其输出:

ID: 1, Name: John, Age: 30
ID: 2, Name: Alice, Age: 25

fiddle

相关问题