SQLSTATE
SQLSTATE is the standard error handling mechanism in SQL. It is a universal return code system which returns complete information about the execution of a SQL statement. It consists of a five-character code wherein the first two characters define the class of the exception and the last three characters specify the subclass or the specific exception within the class.
Example
Output
Explanation
In this code block, a SQL exception handler is declared. This handler is supposed to act when a SQL error occurs. The GET DIAGNOSTICS STATEMENT retrieves information about errors. The details of the error are stored in the variables @sqlstate
, @errno
, and @text
. The error message is then composed by concatenating the message components and assigned to the @full_error
variable. The error message (@full_error
) is returned with a SELECT statement. After the error message is returned, the transaction is rolled back with ROLLBACK. This ensures that partial transactions resulting from an error are not committed to the database.
Example
Output
Explanation
The provided SQL code is an anonymous code block that raises a notice in PostgreSQL with the message ‘An example of SQLSTATE’. The EXCEPTION
block is designed to handle any exceptions that are raised within the BEGIN
and END
block, capturing the SQLSTATE of the exception. However, because no explicit error is raised, the OTHERS
exception handler captures the success SQLSTATE, which is ‘00000’ in PostgreSQL.
Example
Output
Explanation
The example demonstrates SQLSTATE usage by purposely generating a divide-by-zero error. The error is caught in the CATCH
block where error information is then selected and returned. The ERROR_STATE()
function specifically retrieves the state number of the error.
Example
Output
Explanation
The code above is a basic example of how the SQLCODE
and SQLERRM
functions can be used in Oracle SQL to return the SQLSTATE status. However, as there is no error in this code, no output related to SQLSTATE occurs. The SQLCODE
function returns the numeric code of the exception and the SQLERRM
function returns the message associated with the exception. SQLSTATE is a standard set of error codes for SQL that are returned in these kinds of situations (errors, warnings, etc.).