oracle-databaseoracle-apexnested-tablevarray

Oracle Apex - Save list of numbers in a varray-table-field


I have a table with varray of number field type aptitude_list as varray(60) of number and want to save/update a comma separated list from an apex-text-field in it.

My SQL statement looks like :

INSERT INTO tbl_aptitude (ID, APTITUDE)
VALUES ('12345678', aptitude_list(1,2,3,4));

and works fine in SQL Developer.

Now I want to replace the numbers with my textfield aptitude_list(:P7_APTITUDE) with P7_APTITUDE='1,2,3,4'. This can´t be saved, because '1,2,3,4' is not valid number.

How can I tell the system, that I want to store four different numbers and not one?

Thanks for your help!


Solution

  • There are many, many ways to split a delimited string in Oracle.

    One way is to use a function:

    Oracle Setup:

    CREATE type aptitude_list as varray(60) of number
    /
    
    CREATE OR REPLACE FUNCTION split_String(
      i_str    IN  VARCHAR2,
      i_delim  IN  VARCHAR2 DEFAULT ','
    ) RETURN aptitude_list DETERMINISTIC
    AS
      p_result       aptitude_list := aptitude_list();
      p_start        NUMBER(5) := 1;
      p_end          NUMBER(5);
      p_count        NUMBER(3) := 0;
      c_len CONSTANT NUMBER(5) := LENGTH( i_str );
      c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
    BEGIN
      IF c_len > 0 THEN
        p_end := INSTR( i_str, i_delim, p_start );
        WHILE p_end > 0 LOOP
          p_result.EXTEND;
          p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
          p_start := p_end + c_ld;
          p_end := INSTR( i_str, i_delim, p_start );
        END LOOP;
        IF p_start <= c_len + 1 THEN
          p_result.EXTEND;
          p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
        END IF;
      END IF;
      RETURN p_result;
    END;
    /
    
    CREATE TABLE tbl_aptitude (
      ID       VARCHAR2(20),
      APTITUDE aptitude_list
    ); 
    

    Then you can use:

    INSERT INTO tbl_aptitude (ID, APTITUDE)
    VALUES ('12345678', split_String(:P7_APTITUDE));
    

    Query:

    SELECT *
    FROM   tbl_aptitude;
    

    Output:

    | ID       | APTITUDE               |
    |----------|------------------------|
    | 12345678 | APTITUDE_LIST(1,2,3,4) |