Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : transaction within a stored procedure

The basic structure of my stored procedure is,

BEGIN      .. Declare statements ..      START TRANSACTION;          .. Query 1 ..         .. Query 2 ..         .. Query 3 ..      COMMIT;  END 

MySQL version: 5.1.61-0ubuntu0.11.10.1-log

Currently, if 'query 2' fails, result of 'query 1' is committed.

  • How can I rollback the transaction if any of the query fails?
like image 244
Priyank Kapasi Avatar asked Apr 02 '12 09:04

Priyank Kapasi


People also ask

Can we have transaction in stored procedure?

Yes, a stored procedure can be run inside a transaction.

Which Cannot be used inside stored routine?

Stored routines cannot contain arbitrary SQL statements. The following statements are not permitted: The locking statements LOCK TABLES and UNLOCK TABLES . ALTER VIEW .


1 Answers

Take a look at http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html

Basically you declare error handler which will call rollback

START TRANSACTION;  DECLARE EXIT HANDLER FOR SQLEXCEPTION      BEGIN         ROLLBACK;         EXIT PROCEDURE;     END; COMMIT; 
like image 146
rkosegi Avatar answered Sep 18 '22 12:09

rkosegi