Search code examples
sqlplsqlsql-insertsql-merge

How to integrate data incrementally in PL/SQL


How can you incrementally insert data from two different table into another one ?

Let's say I have table A and B and I want to insert rows incrementally into table C. Rows should only be inserted once (if the row already exists nothing should be inserted) and not be updated or deleted in table C.

I thought it would work with a cursor in a loop and then merge and insert data if not matched. Am I completely wrong because I got the error message "table or view does not exist".

for x in A --cursor with data from given table
        loop
        MERGE INTO C USING A
        ON (x.id = C.id)
        WHEN NOT MATCHED THEN
        insert(C.id, C.email, C.address) values(x.id, x.email, x.address);
        end loop;

for x in B --cursor with data from given table
            loop
            MERGE INTO C USING B
            ON (x.id = C.id)
            WHEN NOT MATCHED THEN
            insert(C.id, C.email, C.address) values(x.id, x.email, x.address);
            end loop;

Solution

  • Merge takes a select statement, not a cursor. Somewhere your code has "cursor A is select...", then you try "merge into table using (A)..." However merge needs an the actual select. The correct format is "merge into c using(select ...) A" And remove the cursor.

       merge into c 
       using ( select id, email, address 
                 from a
             ) x
       on (x.id = c.id)
       when not matched then
            insert(c.id, c.email, c.address) 
            values(x.id, x.email, x.address);
     
    merge into c 
       using ( select id, email, address 
                 from b
             ) x
       on (x.id = c.id)
       when not matched then
            insert(c.id, c.email, c.address) 
            values(x.id, x.email, x.address);