How can a MySQL stored procedure call another MySQL stored procedure inside it?


It is quite possible that a MySQL stored procedure can call another MySQL stored procedure inside it. To demonstrate it, we are taking an example in which a stored procedure will call another stored procedure to find out the last_insert_id.

Example

mysql> Create table employee.tbl(Id INT NOT NULL AUTO_INCREMENT, Name Varchar(30) NOT NULL, PRIMARY KEY(id))//
Query OK, 0 rows affected (3.87 sec)

mysql> Create Procedure insert1()
   -> BEGIN insert into employee.tbl(name) values ('Ram');
   -> END//
Query OK, 0 rows affected (0.10 sec)

Now, in the next procedure insert2() we will call the 1st stored procedure i.e. insert1().

mysql> Create Procedure insert2()
   -> BEGIN
   -> CALL insert1();
   -> Select last_insert_id();
   -> END //
Query OK, 0 rows affected (0.11 sec)
mysql> Delimiter ;

mysql> Call insert2();
+------------------+
| last_insert_id() |
+------------------+
| 1                |
+------------------+
1 row in set (0.36 sec)
Query OK, 0 rows affected (0.37 sec)

The above result set shows that when we call insert1() then it inserted the first value in the table called employee.tbl and when we select last_insert_id() in 2nd stored procedure i.e. insert2() then it gives the output 1.

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements