Home > Database > Mysql Tutorial > How is the MySQL IF statement used in a stored procedure?

How is the MySQL IF statement used in a stored procedure?

王林
Release: 2023-09-16 22:49:02
forward
847 people have browsed it

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

#The MySQL IF statement implements basic conditional construction in stored procedures. The syntax is as follows -

IF expression THEN
Statements;
END IF;
Copy after login

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

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

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

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!

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