05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

258<br />

CHAPTER 8 ■ TRANSACTIONS<br />

3 begin<br />

4 if ( inserting ) then<br />

5 update t2 set cnt = cnt +1;<br />

6 else<br />

7 update t2 set cnt = cnt -1;<br />

8 end if;<br />

9 dbms_output.put_line( 'I fired <strong>and</strong> updated ' ||<br />

10 sql%rowcount || ' rows' );<br />

11 end;<br />

12 /<br />

Trigger created.<br />

In this situation, it is less clear what should happen. If the error occurs after the trigger<br />

has fired, should the effects of the trigger be there or not? That is, if the trigger fired <strong>and</strong><br />

updated T2, but the row was not inserted into T, what should the outcome be? Clearly the<br />

answer is that we would not like the CNT column in T2 to be incremented if a row is not actually<br />

inserted into T. Fortunately in <strong>Oracle</strong>, the original statement from the client—INSERT INTO T,<br />

in this case—either entirely succeeds or entirely fails. This statement is atomic. We can confirm<br />

this, as follows:<br />

ops$tkyte@ORA10G> set serveroutput on<br />

ops$tkyte@ORA10G> insert into t values (1);<br />

I fired <strong>and</strong> updated 1 rows<br />

1 row created.<br />

ops$tkyte@ORA10G> insert into t values(-1);<br />

I fired <strong>and</strong> updated 1 rows<br />

insert into t values(-1)<br />

*<br />

ERROR at line 1:<br />

ORA-02290: check constraint (OPS$TKYTE.SYS_C009597) violated<br />

ops$tkyte@ORA10G> select * from t2;<br />

CNT<br />

----------<br />

1<br />

■Note When using SQL*Plus from <strong>Oracle</strong>9i Release 2 <strong>and</strong> before, in order to see that the trigger fired,<br />

you will need to add a line of code, exec null, after the second insert. This is because SQL*Plus does<br />

not retrieve <strong>and</strong> display the DBMS_OUTPUT information after a failed DML statement in those releases. In<br />

<strong>Oracle</strong> 10g it does.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!