MySQL: stored procedure return statement

It is a bit confusing that MySQL function supports return statement but stored procedure does not.

However there is LEAVE statement which can serve the same goal:

this statement is used to exit the flow control construct that has the given label. It can be used within BEGIN … END or loop constructs (LOOP, REPEAT, WHILE).

For example the stored procedure below returns the passed number only if it is non-zero:

DROP PROCEDURE IF EXISTS TestProc;
CREATE PROCEDURE TestProc
(
  vTestNum INT
)
TOP:BEGIN
 
IF vTestNum = 0 THEN
  LEAVE TOP;
END IF;
 
SELECT vTestNum;
 
END;

1 Comment so far

  1. hfrmobile on January 30th, 2014

    Thanks for that hint!

    Just for better readability: I put the BEGIN into an extra line otherwise TOP:BEGIN looks like that LEAVE jumps to BEGIN.

Leave a reply