MySQL 存储函数可以引用表,但不能使用返回结果集的语句。因此我们可以说不存在返回结果集的 SELECT 查询。但我们可以使用 SELECT INTO 来摆脱这个问题。例如,我们正在创建一个函数“Avg_marks”,它使用名为“Student_marks”的表中的动态数据(具有以下记录)来计算平均分数。
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)