【问题标题】:How to exit from outer IF statement in MYSQL如何从MYSQL中的外部IF语句退出
【发布时间】:2018-07-12 11:13:45
【问题描述】:

如何退出外层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;

【问题讨论】:

  • 您现在拥有代码的方式,无论内部条件是否为真,执行都会以任何方式退出外部IF 块。您到底在寻找什么?
  • IF (somethingWrong==true) THEN == 在 MySQL 中不存在 (sqlfiddle.com/#!9/340e01/441) 你需要使用 = 来检查等于

标签: mysql if-statement stored-procedures


【解决方案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 语法)来跟踪错误情况并扁平化您的IFs。像这样的:

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;

【讨论】:

    猜你喜欢
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2015-12-08
    • 1970-01-01
    • 2011-01-05
    • 2013-08-19
    • 2013-06-15
    相关资源
    最近更新 更多