Select*fromstudent_info;+------+ ---------+----------------+----------------+|id |Name &nb"/> Select*fromstudent_info;+------+ ---------+----------------+----------------+|id |Name &nb">
#The MySQL IF statement implements basic conditional construction in stored procedures. The syntax is as follows -
IF expression THEN Statements; END IF;
It must end with a semicolon. To demonstrate the use of IF statements in MySQL stored procedures, we will create the following stored procedure, which is 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 file named Procedure of "coursedetails_IF" which contains IF statement -
mysql> DELIMITER // ; mysql> CREATE PROCEDURE coursedetails_IF(IN S_Subject Varchar(20), OUT S_Course varchar(20)) -> 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)'; -> END IF; -> END // Query OK, 0 rows affected (0.00 sec)
Now when we call this procedure we can see the following result -
mysql> Delimiter ; // mysql> CALL coursedetails_IF('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)
The above is the detailed content of How is the MySQL IF statement used in a stored procedure?. For more information, please follow other related articles on the PHP Chinese website!