如何创建存储过程来更新 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 的记录地址在表中更新。
广告