How to use savepoints in oracle procedure

Tajinder picture Tajinder · May 5, 2014 · Viewed 9.9k times · Source

I have multiple updates and insert statements in a procedure.

Please refer below example:

Procedure Example

--code

Update 1

insert 1

Update 2

Update 3 --Suppose exception occurs

Now i want to rollback to before 1st update statement means no update or insert affects.

Answer

krokodilko picture krokodilko · May 5, 2014
BEGIN

  Savepoint do_update_1;

  Update 1;

  insert 1;

  Update 2;

  Update 3; --Suppose exception occurs

EXCEPTION
  WHEN some_exception THEN Rollback To do_update_1;
END;


====== edit ==========

Working example: http://sqlfiddle.com/#!4/b94a93/1

create table tttt(
  id int,
  val int
)
/

declare 
  x int := 0;
begin
  insert into tttt values( 1,1);
  insert into tttt values( 2,2);
  Savepoint do_update_1;

  insert into tttt values( 3,3);
  update tttt set val = 0 where id = 2;
  update tttt set val = 10 / val where id = 2;

exception
  when zero_divide then rollback to do_update_1;
end;
/