IFsearch_condition
THENstatement_list
[ELSEIFsearch_condition
THENstatement_list
] ... [ELSEstatement_list
] END IF
The 针对存储程序的IF
statement for stored programs implements a basic conditional construct.IF
语句实现了一个基本的条件构造。
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
语句可以有THEN
、ELSE
和ELSEIF
子句,并以END IF
终止。
If a given 如果search_condition
evaluates to true, the corresponding THEN
or ELSEIF
clause statement_list
executes. search_condition
的计算结果为true
,则执行相应的THEN
或ELSEIF
子句语句列表。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
。