MySQL The IF ELSE statement implements basic conditional construction when the expression evaluates to false. The syntax is as follows -
IF expression THEN statements; ELSE else-statements; END IF;
statement must end with a semicolon.
To demonstrate the use of the IF ELSE statement in a MySQL stored procedure, we have created the following stored procedure: based on the values of the table named "student_info" as shown below -
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)
The following query will create a procedure called "coursedetails_IFELSE" which contains the IF ELSE statement-
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)
Now when we call this procedure, we can see the following results-
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)
The above is the detailed content of How is the MySQL IF ELSE statement used in stored procedures?. For more information, please follow other related articles on the PHP Chinese website!