사실 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; CASE 문은 WHEN 절이 실행되지 않은 경우 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)
다음 쿼리는 CASE 문이 포함된 'coursedetails_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 // Query OK, 0 rows affected (0.11 sec)
이제 이 프로시저를 호출할 때 아래 결과를 볼 수 있습니다.
mysql> DELIMITER ;
mysql> CALL coursedetails_CASE ('Computers', @S_course);
Query OK, 1 row affected (0.08 sec)
mysql> Select @S_Course;
+-------------+
| @S_Course |
+-------------+
| B.Tech(CSE) |
+-------------+
1 row in set (0.00 sec)
mysql> CALL coursedetails_CASE ('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)
mysql> CALL coursedetails_CASE ('Math', @S_course);
Query OK, 0 rows affected (0.00 sec)
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);
Query OK, 1 row affected (0.01 sec)
mysql> Select @S_Course;
+--------------------+
| @S_Course |
+--------------------+
| Masters in History |
+--------------------+
1 row in set (0.00 sec)