简体   繁体   中英

oracle stored procedure to insert via select

I am writing a stored procedure where I have 2 complex join select query which is again outer joined. And the result needs to be inserted into another table via stored procedure.

Do you see any issue with the syntax of the stored procedure below: Any help on the syntax will be much appreciated.

create or replace
PROCEDURE STATS_PROCEDURE(
column1 varchar2, 
column2 varchar2,
column3 varchar2,
column4 varchar2,

) IS
BEGIN
    insert into STATS_PRODUCT
      column1 , column2 , column3 , column4)

      select table1.column1, table1.column2 from 
        (SELECT column1, column2 from table_name) table1 
      FULL OUTER JOIN
    (select column3, column4 from table_name) table2 
      on
      table1.column1 = table2.column1 and table1.column2 = table1.column2
END; 

Thanks in advance!

In your INSERT clause you have specified 4 columns but in your SELECT statement you done only 2 columns, your need to modify your query to include all 4 columns in SELECT like the following

BEGIN
    INSERT INTO STATS_PRODUCT
            ( column1
            ,column2
            ,column3
            ,column4
            )
            SELECT table1.column1
                    ,table1.column2
                    ,table2.column3 --Added
                    ,table2.column4 --Added
                FROM (
                        SELECT column1
                            ,column2
                        FROM table_name
                        ) table1
                FULL OUTER JOIN (
                                    SELECT column3
                                        ,column4
                                    FROM table_name
                                ) table2
                    ON table1.column1 = table2.column1
                        AND table1.column2 = table1.column2
END; 

as alternative you can rewrite using WITH clause that makes it easier to read

WITH    table1
          AS (
               SELECT column1
                   ,column2
                FROM table_name
             ),
        table2
          AS (
               SELECT column1
                   ,column2
                   ,column3
                   ,column4
                FROM table_name
             )
    INSERT INTO STATS_PRODUCT
            ( column1
            ,column2
            ,column3
            ,column4                
            )
            SELECT t1.column1
                   ,t1.column2
                   ,t2.column3
                   ,t2.column4
                FROM table1 AS t1
                FULL OUTER JOIN table2 AS t2
                    ON t1.column1 = t2.column1
                       AND t1.column2 = t2.column2

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