MySQL IF ELSEIF ELSE基于多个表达式执行语句。其语法如下-
IF expression THEN statements; ELSEIF elseif-expression THEN elseif-statements; … … … … ELSE else-statements; END IF;
语句必须以分号结尾。
为了演示IF ELSEIF ELSE语句在MySQL存储过程中的使用,我们基于以下名为“ 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 //
现在,当我们调用此过程时,我们可以看到以下结果:
mysql> Delimiter ; // mysql> CALL coursedetails_IF_ELSEIF('Computers', @S_Course); mysql> Select @S_Course; +-------------+ | @S_Course | +-------------+ | B.Tech(CSE) | +-------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_IF_ELSEIF ('Literature', @S_Course); mysql> Select @S_Course; +--------------------+ | @S_Course | +--------------------+ | Masters in English | +--------------------+ 1 row in set (0.00 sec)