MySQL?IF ELSE 語句在表達式計算結果為 false 時實現基本條件構造。其語法如下 –
IF expression THEN statements; ELSE else-statements; END IF;
登錄后復制
語句必須以分號結尾。
為了演示在 MySQL 存儲過程中使用 IF 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_IFELSE”的過程,其中包含 IF ELSE 語句 –
mysql> DELIMITER // ; mysql> CREATE PROCEDURE coursedetails_IFELSE(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; -> IF Sub = 'Computers' THEN -> SET S_Course = 'B.Tech(CSE)'; -> ELSE -> SET S_Course = 'Subject Not in the table '; -> END IF; -> END // Query OK, 0 rows affected (0.00 sec)
登錄后復制
現在,當我們調用這個過程時,我們可以看到下面的結果 –
mysql> Delimiter ; // mysql> CALL coursedetails_IFELSE('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_IFELSE ('History', @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 IF ELSE 語句如何在存儲過程中使用?的詳細內容,更多請關注www.92cms.cn其它相關文章!