0

I have to move the data from table A to table B (they have almost the same fields).

What I have now is a cursor, that iterates over the records that has to be moved, insert one record in the destination table and updates the is_processed field in the source table. Something like:

BEGIN
    FOR i IN (SELECT *
                FROM A 
               WHERE A.IS_PROCESSED = 'N')
    LOOP
        INSERT INTO B(...) VALUES(i....);
        UPDATE A SET IS_PROCESSED = 'Y' WHERE A.ID = i.ID;
        COMMIT;
    END LOOP;

END;

The questions is, how to do the same using INSERT FROM SELECT(without the loop) and then update IS_PROCESSED of all the moved rows?

1
  • I think you could everything in one step in pure SQL using a MERGE statement. No need of PL/SQL, row-by-row is slow-by-slow. Commented Dec 24, 2015 at 12:53

3 Answers 3

2

There is no BULK COLLECT INTO for INSERT .. SELECT

May be you can try this. I don't think it's better than your LOOP.

DECLARE
  TYPE        l_src_tp IS TABLE OF t_source%ROWTYPE;
  l_src_rows  l_src_tp;
BEGIN
  SELECT *
    BULK COLLECT INTO l_src_rows
    FROM t_source;
  FORALL c IN l_src_rows.first .. l_src_rows.last 
    INSERT INTO t_dest (td_id, td_value)
         VALUES (l_src_rows(c).ts_id, l_src_rows(c).ts_value);   
  FORALL c IN l_src_rows.first .. l_src_rows.last          
    UPDATE t_source 
       SET ts_is_proccesed = 'Y'
     WHERE ts_id = l_src_rows(c).ts_id;
END;
Sign up to request clarification or add additional context in comments.

1 Comment

A cursor for loop internally does a BULK COLLECT LIMIT 100
2

If you reverse the order and first make update and then insert you can use:

DECLARE
    ids sys.odcinumberlist;
BEGIN
    UPDATE a SET is_processed = 'Y' WHERE is_processed = 'N' RETURNING id BULK COLLECT INTO ids;
    INSERT INTO b (id) SELECT column_value id FROM TABLE(ids);
    COMMIT;
END;

In the SELECT you can join the ids table and get other data from other tables you want to insert into b.

Comments

0

Hello I should prefer pure SQL rather than PLSQL. I don't know why another update statement is requires for this simpler task. Let me know if this helps.

INSERT INTO <new table>
SELECT col1,col2,
.....,'Y'
FROM <old_table>
WHERE processed_in = 'N';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.