如何在存储过程中使用 MySQL IF ELSEIF ELSE 语句?
MySQL IF ELSEIF ELSE 会基于多个表达式来执行语句,其语法如下 −
IF expression THEN statements; ELSEIF elseif-expression THEN elseif-statements; … … … … ELSE else-statements; END IF;
这些语句必须以分号结尾。
为了演示在 MySQL 存储过程中使用 IF ELSEIF ELSE 语句,我们根据如下所示的名为 'student_info' 表中的值创建了以下存储过程 −
mysql> Select * from student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 125 | Raman | Shimla | Computers | +------+---------+------------+------------+ 3 rows in set (0.00 sec)
以下查询将创建一个名为 'coursedetails_IF_ELSEIF' 的存储过程,其中包含 IF ELSEIF ELSE 语句 −
mysql> DELIMITER // ; mysql> CREATE PROCEDURE coursedetails_IF_ELSEIF(IN S_Subject Varchar(20), OUT S_Course varchar(20)) -> BEGIN -> DECLARE Sub Varchar(20); -> SELECT Subject INTO SUB -> FROM Student_info WHERE S_Subject = Subject; -> IF Sub = 'Computers' THEN -> SET S_Course = 'B.Tech(CSE)'; -> ELSEIF Sub = 'History' THEN -> SET S_Course = 'Masters in History'; -> ELSEIF Sub = 'Literature' THEN -> SET S_Course = 'Masters in English'; -> END IF; -> END // Query OK, 0 rows affected (0.00 sec)
现在,当我们调用这个存储过程时,我们可以在下面看到结果 −
mysql> Delimiter ; // mysql> CALL coursedetails_IF_ELSEIF('Computers', @S_Course); Query OK, 1 row affected (0.00 sec) mysql> Select @S_Course; +-------------+ | @S_Course | +-------------+ | B.Tech(CSE) | +-------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_IF_ELSEIF ('Literature', @S_Course); Query OK, 1 row affected (0.00 sec) mysql> Select @S_Course; +--------------------+ | @S_Course | +--------------------+ | Masters in English | +--------------------+ 1 row in set (0.00 sec)
广告