Some basic exception handling tutorials in Mysql stored procedures _mysql

Source: Internet
Author: User

Sometimes, you do not want the stored procedure to throw an error abort execution, but rather to return an error code. Mysql supports exception handling by defining Continue/exit exception handling HANDLER to capture Sqlwarning/not found/sqlexception (warning/No data/other exceptions). Where, for later, you can change to sqlwarning, not FOUND, SQLEXCEPTION to indicate that all exceptions are handled, equivalent to others in Oracle. For example, when exception handling is not done, the following code throws an error 1062 (23000) fault directly:

CREATE PROCEDURE test_proc_ins1 (
     in i_id INT, in
     i_name VARCHAR ()
)
BEGIN inserts into
     testproc VALUES (i_id,i_name);
     INSERT into TestProc VALUES (i_id,i_name);
End;

After exception handling, you can avoid throwing errors, but define a return parameter O_ret give a special value to represent a failure, such as in Java code, you can handle the business logic by getting the return value instead of catching the exception. For example, set the return value to-1:

CREATE PROCEDURE test_proc_ins1 (
     in i_id INT, in
     i_name VARCHAR (M), out
     o_ret INT)
BEGIN
     DECLARE EXIT HANDLER for SQLSTATE ' 23000 ' Set o_ret =-1;
--You can also use this:
--DECLARE EXIT HANDLER for Sqlwarning,not found,sqlexception set o_ret=-1;
     INSERT into TestProc VALUES (i_id,i_name);
     INSERT into TestProc VALUES (i_id,i_name);
     Set o_ret = 1;
End;

Of course, for a specific SQL statement, you can also specify such as the primary key conflict, rollback;

DECLARE exit HANDLER for SQLSTATE ' 23000 '

delimiter//

CREATE PROCEDURE TEST ()
BEGIN
DECLARE exit HANDLER for Sqlexception,sqlwarning,not FOUND
begin
rollback;
Insert into BB values (' Error ');
End;
START TRANSACTION;
INSERT into AA VALUES (1);
INSERT into AA VALUES (2);
COMMIT;
End;
Call

Test ()//

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.