如何編寫 MySQL 儲存函式來更新表格中的值?


眾所周知,當我們要返回結果時,最好使用函式。因此,當我們要建立儲存函式來操作表格,如插入或更新值時,它或多或少就像儲存過程。在以下示例中,我們建立了一個名為“tbl_update”的儲存函式,它將更新名為“student_marks”的表格中的值。

mysql> Select * from student_marks//
+---------+------+---------+---------+---------+
| Name    | Math | English | Science | History |
+---------+------+---------+---------+---------+
| Raman   |   95 |      89 |      85 |      81 |
| Rahul   |   90 |      87 |      86 |      81 |
| Mohit   |   90 |      85 |      86 |      81 |
| Saurabh | NULL |    NULL |    NULL |    NULL |
+---------+------+---------+---------+---------+
4 rows in set (0.00 sec)

mysql> Create Function tbl_Update(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT)
    -> RETURNS INT
    -> DETERMINISTIC
    -> BEGIN
    -> UPDATE student_marks SET Math = M1,English = M2, Science = M3, History =M4 WHERE Name = S_name;
    -> RETURN 1;
    -> END //
Query OK, 0 rows affected (0.03 sec)

mysql> Select tbl_update('Saurabh',85,69,75,82);
+------------------------------------+
| tbl_update('Saurabh',85,69,75,82)  |
+------------------------------------+
|                                  1 |
+------------------------------------+
1 row in set (0.07 sec)

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

更新於: 2020 年 2 月 13 日

1000+ 瀏覽

開啟你的事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.