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

MySQLMySQLi Database

MySQL Stored functions can reference tables but they cannot make use of statements that return a result set. Hence we can say that there is no SELECT query that returns result set. But we can have SELECT INTO to get rid of that. For example, we are creating a function ‘Avg_marks’ that uses the dynamic data from table named ‘Student_marks’, having following records, to calculate the average of 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)
raja
Published on 21-Feb-2018 11:49:06
Advertisements