|
An Overview of Errors Based on the Possibilities of their Handling | Processing Errors and Exceptions in SQL | Diagnostic Tools |
Transactions join database operations into atomic units. Most errors affect transactions, an error may cause a transaction to terminate prematurely or cause a rollback.
If an error or an exception causes a transaction rollback to occur, further actions may be one of the following:
If an exception of the "rollback exception condition" type is raised, changes since the transaction beginning are rolled back, however, the commands after the block end - where the EXIT handler for this exception is declared - are executed. If such behavior is undesirable, the EXIT handler can be moved to the external block or the RESIGNAL command can be executed inside it.
Exception handling can be illustrated by the following example:
The Handling procedure listed bellow demonstrates exception handling using EXIT handler. The handlable parameter determines whether they are raised by "handlable exception condition" (true) or "rollback exception condition" (false). The resignal_it parameter determines whether the handler will execute the RESIGNAL command. If the resignal_it parameter is true, then the procedure returns an error, since no other handler for this error has been declared.
To raise "handlable exception condition", we will use user exception ABC. To raise "rollback exception condition", we will use a table with a unique key; the procedure will try to insert into it values causing key duplicity. The table is defined like follows:
CREATE TABLE RESTAB (VAL INTEGER, CONSTRAINT INDEX1 UNIQUE (VAL) NULL )
The table will simultaneously contain a result of procedure work. The procedure is:
PROCEDURE Handling(IN handlable Boolean, IN resignal_it Boolean); BEGIN declare abc condition; delete from restab; insert into restab values(0); commit; BEGIN declare exit handler for sqlexception, abc BEGIN update restab set val=val+100; commit; IF resignal_it THEN resignal; END IF; END; // make an update and commit it: update restab set val=val+1; // sets [val] to 1 commit; // make an uncommitted update: update restab set val=val+10; // sets [val] to 11 // raise the exception: IF handlable THEN signal abc; // raises the user-defined handlable exception ELSE insert into restab values(11); // raises the "key duplicity" rollback-type exception END IF; update restab set val=val+1000; // not done because the block had been exited END; update restab set val=val+10000; // done unless the exception is resignalled END
Execution of the Handling procedure has following result:
Parameter handlable | Parameter resignal_it | Result val | Procedure return code |
false | false | 10101 | OK |
false | true | 101 | Key duplicity 40004 |
true | false | 10111 | OK |
true | true | 111 | User exception ABC is not handled 45000 |
An Overview of Errors Based on the Possibilities of their Handling | Processing Errors and Exceptions in SQL | Diagnostic Tools |