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)
以上是我們如何建立一個使用表中動態資料的 MySQL 儲存函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!