实际上,CASE语句具有IF-THEN-ELSE语句的功能。它具有以下语法-
CASE WHEN condition_1 THEN {...statements to execute when condition_1 is TRUE...} [ WHEN condition_2 THEN {...statements to execute when condition_2 is TRUE...} ] [ WHEN condition_n THEN {...statements to execute when condition_n is TRUE...} ] [ ELSE {...statements to execute when all conditions were FALSE...} ] END CASE;
如果没有执行任何WHEN子句,则CASE语句将执行ELSE子句。
为了演示CASE 语句在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_CASE”的过程,该过程中具有CASE语句-
mysql> Delimiter // mysql> CREATE PROCEDURE coursedetails_CASE(IN S_subject Varchar(20), OUT S_Course Varchar(50)) -> BEGIN -> DECLARE SUB VArchar(20); -> SELECT SUBJECT INTO Sub -> FROM Student_Info WHERE S_Subject = Subject; -> CASE S_Subject WHEN 'Computers' THEN -> SET S_Course = 'B.Tech(CSE)’; -> WHEN 'History' THEN -> SET S_Course = 'Masters in History'; -> WHEN 'Literature' THEN -> SET S_Course = 'Masters in English'; -> ELSE -> SET S_Course = 'Subject not in the table'; -> END CASE ; -> END //
现在,当我们调用此过程时,我们可以看到以下结果:
mysql> DELIMITER ; mysql> CALL coursedetails_CASE ('Computers', @S_course); mysql> Select @S_Course; +-------------+ | @S_Course | +-------------+ | B.Tech(CSE) | +-------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_CASE ('literature', @S_course); mysql> Select @S_Course; +--------------------+ | @S_Course | +--------------------+ | Masters in English | +--------------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_CASE ('Math', @S_course); mysql> Select @S_Course; +--------------------------------+ | @S_Course | +--------------------------------+ | Subject Not in the table | +--------------------------------+ 1 row in set (0.00 sec) mysql> CALL coursedetails_CASE ('History', @S_course); mysql> Select @S_Course; +--------------------+ | @S_Course | +--------------------+ | Masters in History | +--------------------+ 1 row in set (0.00 sec)