This is my stored procedure:
CREATE PROCEDURE `procedureName`
(
IN var1 VARCHAR(45),
IN var2 VARCHAR(100),
IN var3 VARCHAR(45),
IN var4 DATE,
IN someMoreVars VARCHAR(100)
)
COMMENT 'just a comment'
BEGIN
DECLARE tempVar INT DEFAULT -1;
DECLARE exit handler for sqlexception
BEGIN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'SQLError occured. Triggered ROLLBACK';
-- ERROR
ROLLBACK;
END;
DECLARE exit handler for sqlwarning
BEGIN
SIGNAL SQLSTATE '35000' SET MESSAGE_TEXT = 'SQLWarning occured. Triggered ROLLBACK';
-- WARNING
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO `schemaName`.`table1` (`column1`, `column2`, `moreColumns`)
VALUES (var1, var2, moreVars);
SELECT LAST_INSERT_ID() INTO tempVar;
INSERT INTO `schemaName`.`table2` (`column1`, `column2`, `evenMoreColumns`)
VALUES (tempVar, var3, var4);
COMMIT;
END
Why does that stored procedure not rollback? When I use parameters that work for the first insert but raise an Exception on the 2nd insert this procedure does not rollback and I end up with data in the first table but no data in the 2nd table.
I am using InnoDB engine.
I have tested this behavior with MySQL Workbench and since it has this weird Autocommit behaviour built into the GUI I have also tested it by calling the procedure from an C# script.
I have also checked if the LAST_INSERT_ID() function is mentioned in the documentation as a function which causes an implicit commit. But have not found it in the list. Or does that function call another function which does cause an implicit commit? And if yes, is there any workaround? I need to call this function to use its PRIMARY KEY as a FOREIGN KEY in the second table. If this information helps: I am also using Triggers.
This is the insert trigger of one of the tables (they are in almost all tables on insert/update/delete):
CREATE DEFINER = CURRENT_USER TRIGGER `schema`.`table1_AFTER_INSERT` AFTER INSERT ON `table1` FOR EACH ROW
BEGIN
INSERT INTO `schema`.`table1_audit` (`table1_audit_action`, `table1_audit_timestamp`, `table1_audit_user`, `table1_val1`, `table1_some_more_columns`)
VALUES ('insert', CURRENT_TIMESTAMP(), SESSION_USER(), NEW.table1_val1, NEW.table1_some_more_columns);
END
Thanks :)