0

If there is a ParentTable table1 and child-table table2 and I want to make sure either both get created (in proper order!) or none get created, is this the correct syntax?

begin    
  insert into table1 values (seq.nextvalue, 'test') ;
  insert into table2 values (seq.currvalue, 'test3');
  commit;
end;
3
  • INSERT INTO t1 SELECT a, b FROM dual OR INSERT INTO t1 VALUES (a, b) Your code kinda slips between the two :) Commented Apr 26, 2012 at 10:51
  • 2
    I'd put a field list into the INSERT statements - e.g. INSERT INTO T1 (FIELDNAME_1, FIELDNAME_2) VALUES (seq.NEXTVALUE, 'test'). I like to offer the database the fewest number of chances possible to fold, spindle, mutilate, or misinterpret what I meant. Commented Apr 26, 2012 at 14:10
  • No need to use BEGIN/END if you have disabled autocommit Commented Apr 26, 2012 at 14:50

2 Answers 2

1

If you are worried about different values in your sequence assignment then fetch it into a variable before your insertion. If any exceptions are raised it'll rollback the insertions, otherwise it'll commit them.

DECLARE
   v_seq_id NUMBER;
BEGIN
   SELECT seq.nextval
     INTO v_seq_id
     FROM dual;
   --
   INSERT INTO table1
   VALUES (
      v_seq_id,
      'test'
   );
   --
   INSERT INTO table2
   VALUES (
      v_seq_id,
      'test3'
   );
   --
   COMMIT;
EXCEPTION
   WHEN others
   THEN
      <log_error>
      ROLLBACK;
END;

Hope it helps...

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not just worried about different seq values, but only first insert taking place and not the other - for whatever reason. I'm guessing that's where exception thing comes in. Btw, am I right in being worried about different seq values?
@progtick, it depends on whether you really need the sequence values to match (i.e. for a foreign key relationship). As for the inserts and one happening without the other, you are correct, the exception section would ensure that if there was an error in one of the inserts, a rollback would occur ensuring nothing was inserted into either table.
In the EXCEPTION block you might want to replace <log_error> with DBMS_OUTPUT.PUT_LINE('Error - ' || SQLCODE || ' : ' || SQLERRM).
@BobJarvis, I was hoping the OP had their own custom error logging to insert there :-)
0

Not tested but must be like that

begin    
  insert into table1 values(seq.nextval, 'test') ;
  insert into table2 values(seq.currval, 'test3');
  commit;
end;

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.