How to use goto label in MySQL stored function

对着背影说爱祢 提交于 2019-11-27 06:59:22

问题


I would like to use goto in MySQL stored function. How can I use? Sample code is:

if (action = 'D') then
    if (rowcount > 0) then
        DELETE FROM datatable WHERE id = 2;      
    else
       SET p=CONCAT('Can not delete',@b);
       goto ret_label;
    end if;
end if;

Label: ret_label;
return 0;

回答1:


There are GOTO cases which can't be implemented in MySQL, like jumping backwards in code (and a good thing, too).

But for something like your example where you want to jump out of everything to a final series of statements, you can create a BEGIN / END block surrounding the code to jump out of:

aBlock:BEGIN
    if (action = 'D') then
        if (rowcount > 0) then
            DELETE FROM datatable WHERE id = 2;      
        else
           SET p=CONCAT('Can not delete',@b);
           LEAVE aBlock;
        end if;
    end if;
END aBlock;
return 0;

Since your code is just some nested IFs, the construct is unnecessary in the given code. But it makes more sense for LOOP/WHILE/REPEAT to avoid multiple RETURN statements from inside a loop and to consolidate final processing (a little like TRY / FINALLY).




回答2:


There is no GOTO in MySQL Stored Procs. You can refer to this post: MySQL :: Re: Goto Statement



来源:https://stackoverflow.com/questions/11134300/how-to-use-goto-label-in-mysql-stored-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!