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 語句如何在預存程序中使用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!