Home > Database > Mysql Tutorial > How is the MySQL IF ELSE statement used in stored procedures?

How is the MySQL IF ELSE statement used in stored procedures?

WBOY
Release: 2023-09-21 23:17:04
forward
850 people have browsed it

MySQL IF ELSE 语句如何在存储过程中使用?

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;
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template