Insert data in a table in MySQL stored procedure?


To insert in a table in stored procedure, the syntax is as follows −

create procedure yourProcedureName(OptionalParameter)
   begin
   insert into yourTableName() values(yourValue1,yourValue2,...N);
end

To understand the above syntax, let us first create a table −

mysql> create table DemoTable1928
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Age int
   );
Query OK, 0 rows affected (0.00 sec)

Here is the query to create a stored procedure −

mysql> delimiter //
mysql> create procedure insert_demo(IN Name varchar(40),IN Age int)
   begin
   insert into DemoTable1928(Name,Age) values(Name,Age);
   end
   //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

Now you can call a stored procedure using CALL command −

mysql> call insert_demo('Chris',24);
Query OK, 1 row affected, 1 warning (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1928;

This will produce the following output −

+----+-------+------+
| Id | Name  |  Age |
+----+-------+------+
|  1 | Chris |   24 |
+----+-------+------+
1 row in set (0.00 sec)

Updated on: 30-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements