Home > Database > Mysql Tutorial > body text

How do we create a MySQL stored function that uses dynamic data from a table?

PHPz
Release: 2023-09-18 13:37:03
forward
1352 people have browsed it

我们如何创建一个使用表中动态数据的 MySQL 存储函数?

MySQL stored functions can reference tables, but they cannot use statements that return result sets. So we can say that there is no SELECT query that returns a result set. But we can use SELECT INTO to get rid of this problem. For example, we are creating a function "Avg_marks" which calculates the average score using dynamic data from a table called "Student_marks" (with the following records).

mysql> Select * from Student_marks;
+-------+------+---------+---------+---------+
| Name  | Math | English | Science | History |
+-------+------+---------+---------+---------+
| Raman |   95 |      89 |      85 |      81 |
| Rahul |   90 |      87 |      86 |      81 |
+-------+------+---------+---------+---------+
2 rows in set (0.00 sec)

mysql> DELIMITER //
mysql> Create Function Avg_marks(S_name Varchar(50))
    -> RETURNS INT
    -> DETERMINISTIC
    -> BEGIN
    -> DECLARE M1,M2,M3,M4,avg INT;
    -> SELECT Math,English,Science,History INTO M1,M2,M3,M4 FROM Student_marks W
HERE Name = S_name;
    -> SET avg = (M1+M2+M3+M4)/4;
    -> RETURN avg;
    -> END //
Query OK, 0 rows affected (0.01 sec)

mysql> DELIMITER ;
mysql> Select Avg_marks('Raman') AS 'Raman_Marks';
+-------------+
| Raman_Marks |
+-------------+
|          88 |
+-------------+
1 row in set (0.07 sec)

mysql> Select Avg_marks('Rahul') AS 'Raman_Marks';
+-------------+
| Raman_Marks |
+-------------+
|          86 |
+-------------+
1 row in set (0.00 sec)
Copy after login

The above is the detailed content of How do we create a MySQL stored function that uses dynamic data from a table?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!