Conditional Control in MySQL Stored Procedure
Conditional control enables you to execute the code based on the value of an expression or a combination of expression using logical operators. MySQL supports two conditional control statement such as IF and CASE.
The IF Statement
The syntax of IF statement is simple as follows:
IF expression THEN commands
[ELSEIF expression THEN commands]
[ELSE commands]
END IF;
The commands associated with IF or ELSEIF or ELSE only executed when the expression is evaluated as TRUE. One of the common trap of IF statement is NULL value; When the expression is evaluated as NULL it is neither TRUE nor FALSE. Here are several combination of IF statement
IF expression THEN commands
END IF;
IF expression THEN commands
ELSE commands
END IF;
IF expression THEN commands
ELSEIF expression THEN commands
ELSE commands
END IF;
You can have IF statement nested with other IF statements.
The CASE Statement
When multiple conditions are used with IF statement the code is not easy to read. At this time, the CASE can be used to make the code clearer. The syntax of the CASE statement is as follows:
CASE
WHEN expression THEN commands
…
WHEN expression THEN commands
ELSE commands
END CASE;