代码之家  ›  专栏  ›  技术社区  ›  Melad Basilius

如何从MySQL中退出外部if语句

  •  0
  • Melad Basilius  · 技术社区  · 6 年前

    如何退出外部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 回复  |  直到 6 年前
        1
  •  1
  •   trincot    6 年前

    你可以试试相反的情况:

    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 语法)可以跟踪错误情况并将 如果 就像这样:

    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;
    
        2
  •  0
  •   Salman Arshad    6 年前

    你可以用 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;