How can I create a stored procedure to update values in a MySQL table?



We can create a stored procedure with IN operator to update values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −

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)

Now, by creating the procedure named ‘update_studentinfo’ as follow, we can update the values in ‘student_info’ table −

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)

Now, invoke the procedure with the values we want to update in the table as follows −

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)

The above result set shows that the address of record having id = 125 updated in the table.

Updated on: 2020-06-22T05:37:02+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements