我该如何创建一个存储过程来更新 MySQL 表格中的值?
我们可以利用 IN 操作符创建一个存储过程来更新 MySQL 表格中的值。为了更好地理解,我们以一个名为“student_info”的表为例,其中包含以下数据 −
mysql> Select * from student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | | 125 | Raman | Bangalore | Computers | +------+---------+------------+------------+ 4 rows in set (0.01 sec)
现在,通过创建名为‘update_studentinfo’ 的过程如下,我们可以更新‘student_info’ 表中的值 −
mysql> DELIMITER // ; mysql> Create Procedure Update_studentinfo ( IN p_id INT, IN p_address varchar(20)) -> BEGIN -> UPDATE student_info -> SET -> address = p_address WHERE id = p_id; -> END // Query OK, 0 rows affected (0.13 sec)
现在,使用我们要在表中更新的值调用这个过程如下 −
mysql> Delimiter ; // mysql> CALL Update_studentinfo(125, 'Shimla'); Query OK, 1 row affected (0.14 sec) mysql> Select * from student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | | 125 | Raman | Shimla | Computers | +------+---------+------------+------------+ 4 rows in set (0.00 sec)
以上结果集显示了 ID = 125 的记录的地址已在表中更新。
广告