Skip to content

SQLSTATE

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
@sqlstate = RETURNED_SQLSTATE, @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
SET @full_error = CONCAT('ERROR', @errno, ' (', @sqlstate, '): ', @text);
SELECT @full_error;
ROLLBACK;
END;
ERROR1146 (42S02): Table 'test.non_existant_table' doesn't exist

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.