
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using MySQL IF Statement in Stored Procedures
MySQL IF statement implements a basic conditional construct within a stored procedure. Its syntax is as follows −
IF expression THEN Statements; END IF;
It must end with a semicolon. To demonstrate the use of IF statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘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)
The following query will create a procedure named ‘coursedetails_IF’ which have IF statements in it −
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, we can see the result below when we invoke this procedure −
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)
Advertisements