How can we perform START transactions inside MySQL stored procedure?


As we know the START transaction will start the transaction and set the auto-commit mode to off. In the following example, we have created a stored procedure with a START transaction which will insert a new record in table employee.tbl having the following data −

mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
| 1  | Mohan   |
| 2  | Gaurav  |
| 3  | Rahul   |
+----+---------+
3 rows in set (0.00 sec)

Example

mysql> Delimiter //
mysql> Create Procedure st_transaction()
   -> BEGIN
   -> START TRANSACTION;
   -> INSERT INTO employee.tbl(name) values ('Saurabh');
   -> END //
Query OK, 0 rows affected (0.00 sec)

Now when we invoke this procedure, it will insert the value in table employee.tbl.

mysql> Delimiter ;
mysql> Call st_transaction();
Query OK, 0 rows affected (0.17 sec)

mysql> Select * from employee.tbl;
+----+---------+
| Id | Name    |
+----+---------+
|  1 | Mohan   |
|  2 | Gaurav  |
|  3 | Rahul   |
|  4 | Saurabh |
+----+---------+
4 rows in set (0.00 sec)

Updated on: 22-Jun-2020

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements