13.6.5.2 IF Statement语句

IF search_condition THEN statement_list
    [ELSEIF search_condition THEN statement_list] ...
    [ELSE statement_list]
END IF

The IF statement for stored programs implements a basic conditional construct.针对存储程序的IF语句实现了一个基本的条件构造。

Note注意

There is also an IF() function, which differs from the IF statement described here. 还有一个IF()函数,它与这里描述的IF语句不同。See Section 12.5, “Flow Control Functions”. 请参阅第12.5节,“流量控制功能”The IF statement can have THEN, ELSE, and ELSEIF clauses, and it is terminated with END IF.IF语句可以有THENELSEELSEIF子句,并以END IF终止。

If a given search_condition evaluates to true, the corresponding THEN or ELSEIF clause statement_list executes. 如果search_condition的计算结果为true,则执行相应的THENELSEIF子句语句列表。If no search_condition matches, the ELSE clause statement_list executes.如果没有匹配的search_condition,则执行ELSE子句statement_list

Each statement_list consists of one or more SQL statements; an empty statement_list is not permitted.每个statement_list由一个或多个SQL语句组成;不允许使用空statement_list

An IF ... END IF block, like all other flow-control blocks used within stored programs, must be terminated with a semicolon, as shown in this example:IF ... END IF块与存储程序中使用的所有其他流控制块一样,必须以分号终止,如本例所示:

DELIMITER //

CREATE FUNCTION SimpleCompare(n INT, m INT)
  RETURNS VARCHAR(20)

  BEGIN
    DECLARE s VARCHAR(20);

    IF n > m THEN SET s = '>';
    ELSEIF n = m THEN SET s = '=';
    ELSE SET s = '<';
    END IF;

    SET s = CONCAT(n, ' ', s, ' ', m);

    RETURN s;
  END //

DELIMITER ;

As with other flow-control constructs, IF ... END IF blocks may be nested within other flow-control constructs, including other IF statements. 与其他流控制构造一样,IF ... END IF块可以嵌套在其他流控制构造中,包括其他IF语句。Each IF must be terminated by its own END IF followed by a semicolon. 每个IF都必须以自己的END IF后面跟着一个分号结束。You can use indentation to make nested flow-control blocks more easily readable by humans (although this is not required by MySQL), as shown here:您可以使用缩进使嵌套的流控制块更容易被人读取(尽管MySQL不需要这样做),如下所示:

DELIMITER //

CREATE FUNCTION VerboseCompare (n INT, m INT)
  RETURNS VARCHAR(50)

  BEGIN
    DECLARE s VARCHAR(50);

    IF n = m THEN SET s = 'equals';
    ELSE
      IF n > m THEN SET s = 'greater';
      ELSE SET s = 'less';
      END IF;

      SET s = CONCAT('is ', s, ' than');
    END IF;

    SET s = CONCAT(n, ' ', s, ' ', m, '.');

    RETURN s;
  END //

DELIMITER ;

In this example, the inner IF is evaluated only if n is not equal to m.在本例中,仅当n不等于m时才计算内部IF