Correct usage of whenever sqlerror in oracle. Can we have examples.
Correct usage of whenever sqlerror in oracle. Can we have examples.
Docs says: Performs the specified action (exits SQLPlus by default) if a SQL command or PL/SQL block generates an error.*
Nothing easier than an example:
script without WHENEVER clause
Create a script (script1.sql) with the following lines. Note the error in the CREATE TABLE statement for tab1 - this statement will error out.
koens macbook % cat script1.sql
prompt first statement
CREATE TABLE tab1 (col1 NUMBERX);
prompt second statement
CREATE TABLE tab2 (col2 NUMBER);
Now run this script - I'm using sqlcl as client:
18c>@script1
first statement
Error starting at line : 3 File @ /Users/klostrie/tmp/script1.sql
In command -
CREATE TABLE tab1 (col1 NUMBERX)
Error report -
ORA-00902: invalid datatype
00902. 00000 - "invalid datatype"
*Cause:
*Action:
second statement
Table TAB2 created.
18c>
Note that the first statement fails as expected but the script continues with the next statement
script with WHENEVER clause
Now lets try the same using WHENEVER SQLERROR
18c>!cat script2.sql
whenever sqlerror exit sql.sqlcode
prompt first statement
CREATE TABLE tab1 (col1 NUMBERX);
prompt second statement
CREATE TABLE tab2 (col2 NUMBER);
18c>@script2
first statement
Error starting at line : 4 File @ /Users/klostrie/tmp/script2.sql
In command -
CREATE TABLE tab1 (col1 NUMBERX)
Error report -
ORA-00902: invalid datatype
00902. 00000 - "invalid datatype"
*Cause:
*Action:
Disconnected from Oracle Database 18c EE High Perf Release 18.0.0.0.0 - Production
Version 18.7.0.0.0
koens macbook %
See the difference ? Because of the WHENEVER SQLERROR EXIT the script stops after the first error and exits the oracle client (sqlcl) with the actual error code (ORA-902)
Check the docs for other arguments of WHENEVER SQLERROR.