📅  最后修改于: 2023-12-03 14:44:26.902000             🧑  作者: Mango
In MySQL, the ELSE IF
statement allows programmers to conditionally execute a block of code based on multiple conditions. This statement is used in conjunction with the IF
statement and can be very useful in controlling the flow of execution in a program.
The basic syntax of the ELSE IF
statement in MySQL is as follows:
IF condition1 THEN
-- code block 1
ELSEIF condition2 THEN
-- code block 2
...
ELSE
-- default code block
END IF;
Each condition
is an expression that evaluates to either true or false. The code block associated with the first condition that evaluates to true is executed. If none of the conditions evaluate to true, the code block associated with the ELSE
statement (if present) is executed.
Let's consider an example where we want to determine the grade of a student based on their score. Here, we'll use the ELSE IF
statement to assign the appropriate grade based on different score ranges.
DELIMITER //
CREATE PROCEDURE GetGrade(IN score INT)
BEGIN
DECLARE grade VARCHAR(10);
IF score >= 90 THEN
SET grade = 'A';
ELSEIF score >= 80 THEN
SET grade = 'B';
ELSEIF score >= 70 THEN
SET grade = 'C';
ELSEIF score >= 60 THEN
SET grade = 'D';
ELSE
SET grade = 'F';
END IF;
SELECT grade;
END //
DELIMITER ;
In this example, we created a stored procedure named GetGrade
that takes a single input parameter score
. Based on the value of score
, it assigns a grade to the grade
variable using the ELSE IF
statement. Finally, it returns the grade using the SELECT
statement.
The ELSE IF
statement in MySQL provides a way to conditionally execute code blocks based on multiple conditions. It is a powerful tool that allows programmers to control the flow of execution in their programs. Use it whenever you need to implement complex conditional logic.