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



We can create a stored procedure with an IN operator to insert 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    | +------+---------+-----------+------------+ | 100  | Aarav   | Delhi     | Computers  | | 101  | YashPal | Amritsar  | History    | | 105  | Gaurav  | Jaipur    | Literature | | 110  | Rahul  | Chandigarh | History    | +------+---------+------------+------------+ 4 rows in set (0.00 sec)

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

mysql> DELIMITER // ; mysql> Create PROCEDURE insert_studentinfo(IN p_id int, IN p_name varchar(20),IN p_Address Varchar(20), IN p_subject Varchar(20))     -> BEGIN     -> insert into student_info(id, name, address, subject) values (p_id, p_name,p_address, p_subject);     -> END // Query OK, 0 rows affected (0.09 sec)

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

mysql> CALL insert_studentinfo(125,'Raman','Bangalore','Computers')// Query OK, 1 row affected (0.78 sec) mysql> DELIMITER ; // mysql> Select * from Student_info; +-----+---------+------------+------------+ | id  | Name    | Address    | Subject    | +-----+---------+------------+------------+ | 100 | Aarav   | Delhi      | Computers  | | 101 | YashPal | Amritsar   | History    | | 105 | Gaurav  | Jaipur     | Literature | | 110 | Rahul   | Chandigarh | History    | | 125 | Raman   | Bangalore  | Computers  | +------+---------+------------+-----------+ 5 rows in set (0.00 sec)

The above result set shows that the values get inserted in the table.

Updated on: 2020-06-22T05:34:45+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements