简体   繁体   中英

Oracle pipelined table function and insert results into an oracle table

I'm using an Oracle pipelined table function and based on the records returned, I would like to insert each row of data into an Oracle table, that has the exact same column count, ie:

I have written a split function that has a return type pipelined which all works fine.

SELECT column_value as val
FROM   TABLE(split(',AA,BB,CC,,,FF,GG,,,HH,'))

which returns me 11 rows of data under the columns alias of val

val
----
NULL
AA
BB
CC,
NULL
NULL
FF
GG
NULL
NULL
HH

Now I also have a msg_log table that has the following definition:

CREATE TABLE msg_log
(
    C001    VARCHAR2(4000 BYTE),
    C002    VARCHAR2(4000 BYTE),
    C003    VARCHAR2(4000 BYTE),
    C004    VARCHAR2(4000 BYTE),
    C005    VARCHAR2(4000 BYTE),
    C006    VARCHAR2(4000 BYTE),
    C007    VARCHAR2(4000 BYTE),
    C008    VARCHAR2(4000 BYTE),
    C009    VARCHAR2(4000 BYTE),
    C010    VARCHAR2(4000 BYTE),
    C011    VARCHAR2(4000 BYTE)
);

Using the values return from my pipelined split function, how can I access each individual 11 records and insert them into my msg_log table.

Basically would like to take each row and insert it into my table.

Oracle Setup :

Pipelined version of this split function :

CREATE OR REPLACE FUNCTION split(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST PIPELINED
AS
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  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
      PIPE ROW( 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
      PIPE ROW ( SUBSTR( i_str, p_start, c_len - p_start + 1 ) );
    END IF;
  END IF;
END;
/

Insert :

Just add a row number and pivot:

INSERT INTO msg_log ( C001, C002, C003, C004, C005, C006, C007, C008, C009, C010, C011 )
SELECT *
FROM   (
  SELECT ROWNUM AS RN,
         COLUMN_VALUE As value
  FROM   TABLE( SPLIT( ',AA,BB,CC,,,FF,GG,,,HH,' ) )
)
PIVOT( MAX( value ) FOR rn IN ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ) )

Output :

SELECT * FROM msg_log;
\nC001 |  C002 |  C003 |  C004 |  C005 |  C006 |  C007 |  C008 |  C009 |  C010 |  C011 \n:--- |  :--- |  :--- |  :--- |  :--- |  :--- |  :--- |  :--- |  :--- |  :--- |  :--- \nnull |  AA |  BB |  CC |  null |  null |  FF |  GG |  null |  null |  HH   \n

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM