如何从MYSQL的外部IF语句退出

时间:2018-07-12 11:13:46

标签: mysql if-statement stored-procedures

如何从外部IF语句退出并继续存储过程

IF (true) THEN

    -- do some work here

    IF (somethingWrong=true) THEN
        -- Exit from the outer IF and continue SP
    END IF;

    -- do some work here
END IF;

2 个答案:

答案 0 :(得分:1)

您可以测试相反的条件:

IF (true) THEN
    /* do some work here */
    IF (NOT somethingWrong) THEN
        /* Do whatever is remaining to do in this outer IF block */
    END IF;
END IF;

如果您有多个实例想要像这样的纾困,那么您可能不想嵌套IF块,如下所示:

IF (true) THEN
    /* do some work here */
    IF (NOT somethingWrong) THEN
        /* do some more work here */
        IF (NOT somethingWrong) THEN
            /* Do whatever is remaining to do in this outer IF block */
        END;
    END IF;
END IF;

...这可能会深深嵌套。而是使用一个变量(检查SET语法)来跟踪错误情况并展平IF。像这样:

SET err = 0
IF (true) THEN
    /* do some work here */
    IF (NOT err)
        /* do some more work here that maybe sets the err variable to some non-zero value */
    END IF;
    IF (NOT err)
        /* do some more work here that maybe sets the err variable non-zero */
    END IF;
    IF (NOT err)
        /* do the remaining work */
    END IF;
END IF;

您甚至可以在其中使用相同的原理进行一些循环:

IF (true) THEN
    /* do some work here */
    IF (NOT err)
        /* do some more work here that maybe sets the err variable to some non-zero value */
    END IF;
    IF (NOT err)
        /* do some more work here that maybe sets the err variable non-zero */
    END IF;
    WHILE (NOT err AND some_loop_condition) DO
        /* some work that needs to repeat a few times, 
           but should be interrupted when err is non-zero */
    END WHILE
    IF (NOT err)
        /* do the remaining work */
    END IF;
END IF;

答案 1 :(得分:0)

您可以使用(滥用)loop construct

fauxloop: LOOP
    IF somethingIsWrong THEN
        LEAVE fauxloop;
    END IF;

    -- do some work here

    IF somethingElseIsWrong THEN
        LEAVE fauxloop;
    END IF;

    -- do some work here

    LEAVE fauxloop;
END LOOP fauxloop;