Sometimes we have some special need for a stored procedure to call another to do something. That is fine, but what if the second stored proc failed for some reason? Maybe you want to halt the first stored procedure (the caller) and not proceed with the work until the problem is verified and resolved. So How do you do it?

Simple, get a return code from the called procedure to determine if it worked or not!

Here’s a sample piece of code to explain better:


DROP PROCEDURE IF EXISTS `test`.`testing123`;
DELIMITER $$

CREATE
PROCEDURE `test`.`testing123`(OUT a INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET a=2;
END;
SET a=0;

# toggle the below as comment or not to see the call at the bottom working
# if you uncomment select abc you'll see the error, otherwise all is cool

# select abc;

END$$

DELIMITER ;

DROP PROCEDURE IF EXISTS `test`.`testing456`;
DELIMITER $$

CREATE
PROCEDURE `test`.`testing456`()
BEGIN
SET @a=0;
CALL `test`.`testing123` (@a);

IF @a != 0 THEN
SELECT "There is a problem with proc `testing123`";
ELSE
SELECT "Everything is cool";
END IF;

END$$

DELIMITER ;

CALL `test`.`testing456` ();

testing123 is the second stored proc in this case, called from testing456. The trick is to have an exit handler which returns a status number to the first stored proc (testing456). The latter will hold an if condition to do `something` depending on the return code received by testing123.

If you have any other suggestions I’d appreciate your input.

VN:F [1.9.22_1171]
Rating: 6.7/10 (3 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 5 votes)

Getting a return code from a stored procedure, 6.7 out of 10 based on 3 ratings

*