Error Handling

SQL*Plus doesn’t offer too much in the way of error handling. By default, SQL*Plus simply ignores errors and goes on to execute either the next command you type in, or the next command in the script you are running. For interactive use, this is good enough. If an error occurs, you will see the message and take appropriate action. However, the situation is different when you are running a script. Depending on what the script is doing, you may not want SQL*Plus to blindly proceed to the next command when an error occurs. Consider the following script, which creates a new table, copies data to it, then deletes the original table:

CREATE TABLE employees AS 
   SELECT * FROM employee;
DROP TABLE employee;

If the CREATE TABLE command failed, you certainly wouldn’t want the script to continue, because you would lose all your data! To help with this type of situation, SQL*Plus provides the WHENEVER command.

The WHENEVER Command

With the WHENEVER command, you can give SQL*Plus instructions on what to do when an error occurs. Your choices are a bit limited: you can either continue when an error occurs, or you can exit SQL*Plus entirely, possibly returning an error code. Returning an error code is useful if you are calling SQL*Plus from a Unix shell script or a DOS batch file.

There are two types of errors you can handle with WHENEVER. Each has its own variation of the command. WHENEVER SQLERROR is used to handle SQL errors and errors raised from PL/SQL blocks. WHENEVER OSERROR ...

Get Oracle SQL*Plus: The Definitive Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.