Mysql - How to quit/exit from stored procedure












108















I have very simple question but i did't get any simple code to exit from SP using Mysql.
Can anyone share with me how to do that?



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NULL THEN
#Exit this stored procedure here
END IF;

#proceed the code
END;









share|improve this question




















  • 1





    Or, you could use IF tablename IS NOT NULL THEN ... ;)

    – OMG Ponies
    Jun 7 '11 at 2:50






  • 4





    I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

    – Joe Ijam
    Jun 7 '11 at 3:07











  • Good reference URL: bytes.com/topic/mysql/answers/…

    – Avishek
    Feb 24 '18 at 18:08
















108















I have very simple question but i did't get any simple code to exit from SP using Mysql.
Can anyone share with me how to do that?



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NULL THEN
#Exit this stored procedure here
END IF;

#proceed the code
END;









share|improve this question




















  • 1





    Or, you could use IF tablename IS NOT NULL THEN ... ;)

    – OMG Ponies
    Jun 7 '11 at 2:50






  • 4





    I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

    – Joe Ijam
    Jun 7 '11 at 3:07











  • Good reference URL: bytes.com/topic/mysql/answers/…

    – Avishek
    Feb 24 '18 at 18:08














108












108








108


31






I have very simple question but i did't get any simple code to exit from SP using Mysql.
Can anyone share with me how to do that?



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NULL THEN
#Exit this stored procedure here
END IF;

#proceed the code
END;









share|improve this question
















I have very simple question but i did't get any simple code to exit from SP using Mysql.
Can anyone share with me how to do that?



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NULL THEN
#Exit this stored procedure here
END IF;

#proceed the code
END;






mysql sql stored-procedures






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 7 '11 at 2:49









OMG Ponies

258k61443469




258k61443469










asked Jun 7 '11 at 2:44









Joe IjamJoe Ijam

86031024




86031024








  • 1





    Or, you could use IF tablename IS NOT NULL THEN ... ;)

    – OMG Ponies
    Jun 7 '11 at 2:50






  • 4





    I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

    – Joe Ijam
    Jun 7 '11 at 3:07











  • Good reference URL: bytes.com/topic/mysql/answers/…

    – Avishek
    Feb 24 '18 at 18:08














  • 1





    Or, you could use IF tablename IS NOT NULL THEN ... ;)

    – OMG Ponies
    Jun 7 '11 at 2:50






  • 4





    I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

    – Joe Ijam
    Jun 7 '11 at 3:07











  • Good reference URL: bytes.com/topic/mysql/answers/…

    – Avishek
    Feb 24 '18 at 18:08








1




1





Or, you could use IF tablename IS NOT NULL THEN ... ;)

– OMG Ponies
Jun 7 '11 at 2:50





Or, you could use IF tablename IS NOT NULL THEN ... ;)

– OMG Ponies
Jun 7 '11 at 2:50




4




4





I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

– Joe Ijam
Jun 7 '11 at 3:07





I am trying to fine short cut... otherwise i have to code inside the IF statement, and this is not the only EXIT statement... that y i need exit function instead we do multiple IF inside Stored Proc.

– Joe Ijam
Jun 7 '11 at 3:07













Good reference URL: bytes.com/topic/mysql/answers/…

– Avishek
Feb 24 '18 at 18:08





Good reference URL: bytes.com/topic/mysql/answers/…

– Avishek
Feb 24 '18 at 18:08












6 Answers
6






active

oldest

votes


















169














CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
proc_label:BEGIN
IF tablename IS NULL THEN
LEAVE proc_label;
END IF;

#proceed the code
END;





share|improve this answer
























  • Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

    – user645280
    May 22 '13 at 14:36






  • 2





    can you leave and return a value?

    – ygaradon
    Apr 8 '14 at 10:28






  • 25





    Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

    – SNag
    Jun 1 '14 at 19:03











  • @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

    – David Harkness
    Aug 11 '14 at 20:42






  • 1





    I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

    – Umair Malhi
    Aug 9 '17 at 10:06



















12














To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
CALL SP_Reporting_2(tablename);
END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
#proceed with code
END;





share|improve this answer





















  • 6





    Yucks, why not use the first solution instead?

    – Pacerier
    Apr 1 '15 at 7:42






  • 1





    Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

    – Max Heiber
    Jul 31 '15 at 18:22













  • Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

    – jlh
    Nov 21 '18 at 14:46











  • @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

    – Bohemian
    Nov 21 '18 at 14:53



















7














If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).



As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more poignant manner.



Here's how:



DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

IF <Some Error Condition> THEN
SIGNAL CUSTOM_EXCEPTION
SET MESSAGE_TEXT = 'Your Custom Error Message';
END IF;


Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).



For more on this subject, check out:



https://dev.mysql.com/doc/refman/5.5/en/signal.html



How to raise an error within a MySQL function



http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html



Addendum



As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).



For example:



CALL AttemptedToInsertSomethingInvalid;



Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!






share|improve this answer


























  • This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

    – Fodagus
    Nov 28 '17 at 0:47











  • Most correct/elegant answer! +1

    – MarcM
    Sep 4 '18 at 15:42



















1














Why not this:



CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
#proceed the code
END IF;
# Do nothing otherwise
END;





share|improve this answer



















  • 4





    The code is very long... i cannot use this... That is just a sample.

    – Joe Ijam
    Jun 7 '11 at 2:53











  • No matter the length, it will not execute.

    – Stephen
    Jun 7 '11 at 2:54











  • If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

    – bobobobo
    Jun 6 '13 at 19:38











  • @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

    – Pacerier
    Apr 1 '15 at 7:43






  • 1





    May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

    – borjab
    Apr 21 '15 at 17:00



















1














This works for me :



 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN

DECLARE v_pkg_name varchar(50) ;

DECLARE v_pkg_temp_id int(10) ;

DECLARE v_workflow_count INT(10);

-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;

this_proc:BEGIN -- this_proc block start here

IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;

select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;

END ;-- this_proc block end here

END





share|improve this answer































    0














    MainLabel:BEGIN

    IF (<condition>) IS NOT NULL THEN
    LEAVE MainLabel;
    END IF;

    ....code

    i.e.
    IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
    LEAVE MainLabel;
    END IF;





    share|improve this answer



















    • 1





      What does this add on top of the accepted answer?

      – Matthew Read
      Jun 27 '17 at 19:21








    • 2





      @MatthewRead, an opportunity for sdfor to get upvotes.

      – Andrew Steitz
      Sep 29 '17 at 20:59











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6260157%2fmysql-how-to-quit-exit-from-stored-procedure%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    6 Answers
    6






    active

    oldest

    votes








    6 Answers
    6






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    169














    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    proc_label:BEGIN
    IF tablename IS NULL THEN
    LEAVE proc_label;
    END IF;

    #proceed the code
    END;





    share|improve this answer
























    • Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

      – user645280
      May 22 '13 at 14:36






    • 2





      can you leave and return a value?

      – ygaradon
      Apr 8 '14 at 10:28






    • 25





      Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

      – SNag
      Jun 1 '14 at 19:03











    • @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

      – David Harkness
      Aug 11 '14 at 20:42






    • 1





      I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

      – Umair Malhi
      Aug 9 '17 at 10:06
















    169














    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    proc_label:BEGIN
    IF tablename IS NULL THEN
    LEAVE proc_label;
    END IF;

    #proceed the code
    END;





    share|improve this answer
























    • Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

      – user645280
      May 22 '13 at 14:36






    • 2





      can you leave and return a value?

      – ygaradon
      Apr 8 '14 at 10:28






    • 25





      Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

      – SNag
      Jun 1 '14 at 19:03











    • @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

      – David Harkness
      Aug 11 '14 at 20:42






    • 1





      I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

      – Umair Malhi
      Aug 9 '17 at 10:06














    169












    169








    169







    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    proc_label:BEGIN
    IF tablename IS NULL THEN
    LEAVE proc_label;
    END IF;

    #proceed the code
    END;





    share|improve this answer













    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    proc_label:BEGIN
    IF tablename IS NULL THEN
    LEAVE proc_label;
    END IF;

    #proceed the code
    END;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 7 '11 at 3:29









    piotrmpiotrm

    9,28232226




    9,28232226













    • Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

      – user645280
      May 22 '13 at 14:36






    • 2





      can you leave and return a value?

      – ygaradon
      Apr 8 '14 at 10:28






    • 25





      Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

      – SNag
      Jun 1 '14 at 19:03











    • @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

      – David Harkness
      Aug 11 '14 at 20:42






    • 1





      I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

      – Umair Malhi
      Aug 9 '17 at 10:06



















    • Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

      – user645280
      May 22 '13 at 14:36






    • 2





      can you leave and return a value?

      – ygaradon
      Apr 8 '14 at 10:28






    • 25





      Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

      – SNag
      Jun 1 '14 at 19:03











    • @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

      – David Harkness
      Aug 11 '14 at 20:42






    • 1





      I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

      – Umair Malhi
      Aug 9 '17 at 10:06

















    Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

    – user645280
    May 22 '13 at 14:36





    Great! You even point out that the END proc_label; syntax (shown in most official MySQL examples) is not needed. (this is a great way to comment out a stored proc without having to scroll to the bottom to put */ in place)

    – user645280
    May 22 '13 at 14:36




    2




    2





    can you leave and return a value?

    – ygaradon
    Apr 8 '14 at 10:28





    can you leave and return a value?

    – ygaradon
    Apr 8 '14 at 10:28




    25




    25





    Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

    – SNag
    Jun 1 '14 at 19:03





    Just label the BEGIN section of every proc 'this_proc'. Because LEAVE this_proc; sounds perfect!

    – SNag
    Jun 1 '14 at 19:03













    @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

    – David Harkness
    Aug 11 '14 at 20:42





    @ygaradon Stored procedures do not return values. You need to use a stored function and return <value> to return a value.

    – David Harkness
    Aug 11 '14 at 20:42




    1




    1





    I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

    – Umair Malhi
    Aug 9 '17 at 10:06





    I think space is necessary between : and BEGIN as proc_label:BEGIN gave syntax error while proc_label: BEGIN worked.

    – Umair Malhi
    Aug 9 '17 at 10:06













    12














    To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    CALL SP_Reporting_2(tablename);
    END IF;
    END;

    CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
    BEGIN
    #proceed with code
    END;





    share|improve this answer





















    • 6





      Yucks, why not use the first solution instead?

      – Pacerier
      Apr 1 '15 at 7:42






    • 1





      Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

      – Max Heiber
      Jul 31 '15 at 18:22













    • Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

      – jlh
      Nov 21 '18 at 14:46











    • @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

      – Bohemian
      Nov 21 '18 at 14:53
















    12














    To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    CALL SP_Reporting_2(tablename);
    END IF;
    END;

    CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
    BEGIN
    #proceed with code
    END;





    share|improve this answer





















    • 6





      Yucks, why not use the first solution instead?

      – Pacerier
      Apr 1 '15 at 7:42






    • 1





      Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

      – Max Heiber
      Jul 31 '15 at 18:22













    • Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

      – jlh
      Nov 21 '18 at 14:46











    • @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

      – Bohemian
      Nov 21 '18 at 14:53














    12












    12








    12







    To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    CALL SP_Reporting_2(tablename);
    END IF;
    END;

    CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
    BEGIN
    #proceed with code
    END;





    share|improve this answer















    To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    CALL SP_Reporting_2(tablename);
    END IF;
    END;

    CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
    BEGIN
    #proceed with code
    END;






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 '18 at 14:52

























    answered Jun 7 '11 at 2:55









    BohemianBohemian

    297k65423557




    297k65423557








    • 6





      Yucks, why not use the first solution instead?

      – Pacerier
      Apr 1 '15 at 7:42






    • 1





      Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

      – Max Heiber
      Jul 31 '15 at 18:22













    • Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

      – jlh
      Nov 21 '18 at 14:46











    • @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

      – Bohemian
      Nov 21 '18 at 14:53














    • 6





      Yucks, why not use the first solution instead?

      – Pacerier
      Apr 1 '15 at 7:42






    • 1





      Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

      – Max Heiber
      Jul 31 '15 at 18:22













    • Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

      – jlh
      Nov 21 '18 at 14:46











    • @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

      – Bohemian
      Nov 21 '18 at 14:53








    6




    6





    Yucks, why not use the first solution instead?

    – Pacerier
    Apr 1 '15 at 7:42





    Yucks, why not use the first solution instead?

    – Pacerier
    Apr 1 '15 at 7:42




    1




    1





    Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

    – Max Heiber
    Jul 31 '15 at 18:22







    Wish I could vote this up twice. Just because SQL isn't a real programming language doesn't give anyone an excuse to write 200+ lines of code in a single procedure.

    – Max Heiber
    Jul 31 '15 at 18:22















    Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

    – jlh
    Nov 21 '18 at 14:46





    Is this answer just plain wrong or am I missing something? Why does it have upvotes? Clearly there is a way to achieve this which is demonstrated by the accepted solution.

    – jlh
    Nov 21 '18 at 14:46













    @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

    – Bohemian
    Nov 21 '18 at 14:53





    @jlh it was wrong (text corrected now) in that I didn’t know about mysql’s label technique, but the code isn’t wrong - it will work, on any DB actually.

    – Bohemian
    Nov 21 '18 at 14:53











    7














    If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).



    As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more poignant manner.



    Here's how:



    DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

    IF <Some Error Condition> THEN
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
    END IF;


    Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).



    For more on this subject, check out:



    https://dev.mysql.com/doc/refman/5.5/en/signal.html



    How to raise an error within a MySQL function



    http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html



    Addendum



    As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).



    For example:



    CALL AttemptedToInsertSomethingInvalid;



    Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!






    share|improve this answer


























    • This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

      – Fodagus
      Nov 28 '17 at 0:47











    • Most correct/elegant answer! +1

      – MarcM
      Sep 4 '18 at 15:42
















    7














    If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).



    As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more poignant manner.



    Here's how:



    DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

    IF <Some Error Condition> THEN
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
    END IF;


    Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).



    For more on this subject, check out:



    https://dev.mysql.com/doc/refman/5.5/en/signal.html



    How to raise an error within a MySQL function



    http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html



    Addendum



    As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).



    For example:



    CALL AttemptedToInsertSomethingInvalid;



    Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!






    share|improve this answer


























    • This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

      – Fodagus
      Nov 28 '17 at 0:47











    • Most correct/elegant answer! +1

      – MarcM
      Sep 4 '18 at 15:42














    7












    7








    7







    If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).



    As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more poignant manner.



    Here's how:



    DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

    IF <Some Error Condition> THEN
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
    END IF;


    Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).



    For more on this subject, check out:



    https://dev.mysql.com/doc/refman/5.5/en/signal.html



    How to raise an error within a MySQL function



    http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html



    Addendum



    As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).



    For example:



    CALL AttemptedToInsertSomethingInvalid;



    Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!






    share|improve this answer















    If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).



    As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more poignant manner.



    Here's how:



    DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

    IF <Some Error Condition> THEN
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
    END IF;


    Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).



    For more on this subject, check out:



    https://dev.mysql.com/doc/refman/5.5/en/signal.html



    How to raise an error within a MySQL function



    http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html



    Addendum



    As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).



    For example:



    CALL AttemptedToInsertSomethingInvalid;



    Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Oct 12 '18 at 18:10

























    answered Sep 22 '17 at 13:34









    BuvinJBuvinJ

    3,99323050




    3,99323050













    • This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

      – Fodagus
      Nov 28 '17 at 0:47











    • Most correct/elegant answer! +1

      – MarcM
      Sep 4 '18 at 15:42



















    • This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

      – Fodagus
      Nov 28 '17 at 0:47











    • Most correct/elegant answer! +1

      – MarcM
      Sep 4 '18 at 15:42

















    This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

    – Fodagus
    Nov 28 '17 at 0:47





    This feels like the most correct, thorough answer to me and was exactly what i wanted. Like the OP, i have several tests (input validation) i need to run and i didn't want to nest them all , so this works well for me.

    – Fodagus
    Nov 28 '17 at 0:47













    Most correct/elegant answer! +1

    – MarcM
    Sep 4 '18 at 15:42





    Most correct/elegant answer! +1

    – MarcM
    Sep 4 '18 at 15:42











    1














    Why not this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    #proceed the code
    END IF;
    # Do nothing otherwise
    END;





    share|improve this answer



















    • 4





      The code is very long... i cannot use this... That is just a sample.

      – Joe Ijam
      Jun 7 '11 at 2:53











    • No matter the length, it will not execute.

      – Stephen
      Jun 7 '11 at 2:54











    • If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

      – bobobobo
      Jun 6 '13 at 19:38











    • @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

      – Pacerier
      Apr 1 '15 at 7:43






    • 1





      May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

      – borjab
      Apr 21 '15 at 17:00
















    1














    Why not this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    #proceed the code
    END IF;
    # Do nothing otherwise
    END;





    share|improve this answer



















    • 4





      The code is very long... i cannot use this... That is just a sample.

      – Joe Ijam
      Jun 7 '11 at 2:53











    • No matter the length, it will not execute.

      – Stephen
      Jun 7 '11 at 2:54











    • If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

      – bobobobo
      Jun 6 '13 at 19:38











    • @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

      – Pacerier
      Apr 1 '15 at 7:43






    • 1





      May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

      – borjab
      Apr 21 '15 at 17:00














    1












    1








    1







    Why not this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    #proceed the code
    END IF;
    # Do nothing otherwise
    END;





    share|improve this answer













    Why not this:



    CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
    BEGIN
    IF tablename IS NOT NULL THEN
    #proceed the code
    END IF;
    # Do nothing otherwise
    END;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 7 '11 at 2:50









    StephenStephen

    15.3k65395




    15.3k65395








    • 4





      The code is very long... i cannot use this... That is just a sample.

      – Joe Ijam
      Jun 7 '11 at 2:53











    • No matter the length, it will not execute.

      – Stephen
      Jun 7 '11 at 2:54











    • If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

      – bobobobo
      Jun 6 '13 at 19:38











    • @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

      – Pacerier
      Apr 1 '15 at 7:43






    • 1





      May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

      – borjab
      Apr 21 '15 at 17:00














    • 4





      The code is very long... i cannot use this... That is just a sample.

      – Joe Ijam
      Jun 7 '11 at 2:53











    • No matter the length, it will not execute.

      – Stephen
      Jun 7 '11 at 2:54











    • If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

      – bobobobo
      Jun 6 '13 at 19:38











    • @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

      – Pacerier
      Apr 1 '15 at 7:43






    • 1





      May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

      – borjab
      Apr 21 '15 at 17:00








    4




    4





    The code is very long... i cannot use this... That is just a sample.

    – Joe Ijam
    Jun 7 '11 at 2:53





    The code is very long... i cannot use this... That is just a sample.

    – Joe Ijam
    Jun 7 '11 at 2:53













    No matter the length, it will not execute.

    – Stephen
    Jun 7 '11 at 2:54





    No matter the length, it will not execute.

    – Stephen
    Jun 7 '11 at 2:54













    If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

    – bobobobo
    Jun 6 '13 at 19:38





    If you're worried about indenting, just unindent the entire section in the if statement. It's logically identical to an "early return".

    – bobobobo
    Jun 6 '13 at 19:38













    @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

    – Pacerier
    Apr 1 '15 at 7:43





    @bobobobo, He's saying in his case it makes logically much more sense not tot rewire the logic around this sql limitation.

    – Pacerier
    Apr 1 '15 at 7:43




    1




    1





    May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

    – borjab
    Apr 21 '15 at 17:00





    May be he has a login with lots of checks "if x IS NULL THEN SETresult = -1". You want it to REALLY stop doing things. It reduces the complexity of ifs. Less {} annidated

    – borjab
    Apr 21 '15 at 17:00











    1














    This works for me :



     CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
    IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
    OUT o_number INT )
    BEGIN

    DECLARE v_pkg_name varchar(50) ;

    DECLARE v_pkg_temp_id int(10) ;

    DECLARE v_workflow_count INT(10);

    -- checking if workflow created for package
    select count(*) INTO v_workflow_count from workflow w where w.package_id =
    package_id ;

    this_proc:BEGIN -- this_proc block start here

    IF v_workflow_count = 0 THEN
    select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET o_number = -2 ;
    LEAVE this_proc;
    END IF;

    select 'work flow created ' as 'workflow_status' ;
    -- To send some message
    SET o_message ='SUCCESSFUL';
    SET o_number = 1 ;

    END ;-- this_proc block end here

    END





    share|improve this answer




























      1














      This works for me :



       CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
      IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
      OUT o_number INT )
      BEGIN

      DECLARE v_pkg_name varchar(50) ;

      DECLARE v_pkg_temp_id int(10) ;

      DECLARE v_workflow_count INT(10);

      -- checking if workflow created for package
      select count(*) INTO v_workflow_count from workflow w where w.package_id =
      package_id ;

      this_proc:BEGIN -- this_proc block start here

      IF v_workflow_count = 0 THEN
      select 'no work flow ' as 'workflow_status' ;
      SET o_message ='Work flow is not created for this package.';
      SET o_number = -2 ;
      LEAVE this_proc;
      END IF;

      select 'work flow created ' as 'workflow_status' ;
      -- To send some message
      SET o_message ='SUCCESSFUL';
      SET o_number = 1 ;

      END ;-- this_proc block end here

      END





      share|improve this answer


























        1












        1








        1







        This works for me :



         CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
        IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
        OUT o_number INT )
        BEGIN

        DECLARE v_pkg_name varchar(50) ;

        DECLARE v_pkg_temp_id int(10) ;

        DECLARE v_workflow_count INT(10);

        -- checking if workflow created for package
        select count(*) INTO v_workflow_count from workflow w where w.package_id =
        package_id ;

        this_proc:BEGIN -- this_proc block start here

        IF v_workflow_count = 0 THEN
        select 'no work flow ' as 'workflow_status' ;
        SET o_message ='Work flow is not created for this package.';
        SET o_number = -2 ;
        LEAVE this_proc;
        END IF;

        select 'work flow created ' as 'workflow_status' ;
        -- To send some message
        SET o_message ='SUCCESSFUL';
        SET o_number = 1 ;

        END ;-- this_proc block end here

        END





        share|improve this answer













        This works for me :



         CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
        IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
        OUT o_number INT )
        BEGIN

        DECLARE v_pkg_name varchar(50) ;

        DECLARE v_pkg_temp_id int(10) ;

        DECLARE v_workflow_count INT(10);

        -- checking if workflow created for package
        select count(*) INTO v_workflow_count from workflow w where w.package_id =
        package_id ;

        this_proc:BEGIN -- this_proc block start here

        IF v_workflow_count = 0 THEN
        select 'no work flow ' as 'workflow_status' ;
        SET o_message ='Work flow is not created for this package.';
        SET o_number = -2 ;
        LEAVE this_proc;
        END IF;

        select 'work flow created ' as 'workflow_status' ;
        -- To send some message
        SET o_message ='SUCCESSFUL';
        SET o_number = 1 ;

        END ;-- this_proc block end here

        END






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 11 '18 at 10:07









        Devendra SingraulDevendra Singraul

        11411




        11411























            0














            MainLabel:BEGIN

            IF (<condition>) IS NOT NULL THEN
            LEAVE MainLabel;
            END IF;

            ....code

            i.e.
            IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
            LEAVE MainLabel;
            END IF;





            share|improve this answer



















            • 1





              What does this add on top of the accepted answer?

              – Matthew Read
              Jun 27 '17 at 19:21








            • 2





              @MatthewRead, an opportunity for sdfor to get upvotes.

              – Andrew Steitz
              Sep 29 '17 at 20:59
















            0














            MainLabel:BEGIN

            IF (<condition>) IS NOT NULL THEN
            LEAVE MainLabel;
            END IF;

            ....code

            i.e.
            IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
            LEAVE MainLabel;
            END IF;





            share|improve this answer



















            • 1





              What does this add on top of the accepted answer?

              – Matthew Read
              Jun 27 '17 at 19:21








            • 2





              @MatthewRead, an opportunity for sdfor to get upvotes.

              – Andrew Steitz
              Sep 29 '17 at 20:59














            0












            0








            0







            MainLabel:BEGIN

            IF (<condition>) IS NOT NULL THEN
            LEAVE MainLabel;
            END IF;

            ....code

            i.e.
            IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
            LEAVE MainLabel;
            END IF;





            share|improve this answer













            MainLabel:BEGIN

            IF (<condition>) IS NOT NULL THEN
            LEAVE MainLabel;
            END IF;

            ....code

            i.e.
            IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
            LEAVE MainLabel;
            END IF;






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 25 '16 at 19:28









            sdforsdfor

            3,220104357




            3,220104357








            • 1





              What does this add on top of the accepted answer?

              – Matthew Read
              Jun 27 '17 at 19:21








            • 2





              @MatthewRead, an opportunity for sdfor to get upvotes.

              – Andrew Steitz
              Sep 29 '17 at 20:59














            • 1





              What does this add on top of the accepted answer?

              – Matthew Read
              Jun 27 '17 at 19:21








            • 2





              @MatthewRead, an opportunity for sdfor to get upvotes.

              – Andrew Steitz
              Sep 29 '17 at 20:59








            1




            1





            What does this add on top of the accepted answer?

            – Matthew Read
            Jun 27 '17 at 19:21







            What does this add on top of the accepted answer?

            – Matthew Read
            Jun 27 '17 at 19:21






            2




            2





            @MatthewRead, an opportunity for sdfor to get upvotes.

            – Andrew Steitz
            Sep 29 '17 at 20:59





            @MatthewRead, an opportunity for sdfor to get upvotes.

            – Andrew Steitz
            Sep 29 '17 at 20:59


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6260157%2fmysql-how-to-quit-exit-from-stored-procedure%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith