A little bit about MySQL stored procedure exception handling

Source: Internet
Author: User

DROP PROCEDURE IF EXISTS ' Sp_model ';

DELIMITER;;
CREATE PROCEDURE ' Sp_model ' (in V_type INT)
BEGIN
/********** stored procedure template, combined • Return custom error message • Error exit • • Things Roll back • function ***********/
DECLARE v_test INT DEFAULT 0;

DECLARE v_err_no INT DEFAULT 0;
DECLARE v_err_msg VARCHAR (+) DEFAULT ' successful execution ';
DECLARE CONTINUE HANDLER for sqlexception,sqlwarning,not FOUND SET v_err_no=1;

--CREATE TABLE ' Test_error ' (
--' a ' int (one) not NULL,
--' B ' int (one) DEFAULT NULL,
--PRIMARY KEY (' a ')
--) Engine=innodb DEFAULT Charset=utf8;

--TRUNCATE TABLE test_error;
--Call Sp_model (1);
--SELECT * from Test_error;

START TRANSACTION;

IF V_type=1 Then
INSERT into Test_error (A, B) VALUES (+);
INSERT into Test_error (A, B) VALUES (+);

IF V_err_no=1 Then
SET v_err_msg= ' You have already inserted, do not repeat the insertion ~ ';
--LEAVE Label;
END IF;

SET v_test=1;

INSERT into Test_error (A, B) VALUES (3, ' a ');
IF V_err_no=1 Then
SET v_err_msg= ' size is not right, plug in ~ ';
LEAVE Label;
END IF;

INSERT into Test_error (A, B) VALUES (4,1);

SET v_test=2;

ELSE
SET v_err_msg= ' incoming parameter v_type incorrect ';
SET v_err_no=1; --Directly set the value of this variable to 1, and actively throw an exception
LEAVE Label;
END IF;

END Label;

IF V_err_no=1 Then
ROLLBACK;
ELSE
COMMIT;
END IF;

SELECT V_err_no as err_no,v_err_msg as Err_msg, v_test as TEST; --Return to execution results
END

;;

DELIMITER;

A little bit about MySQL stored procedure exception handling

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.