I’m using MySQL and InnoDB and I’ve run into some problem recently.
This is the statement I’m trying to run (I’ve removed some personal details):
START TRANSACTION;
SET FOREIGN_KEY_CHECKS = 0;
INSERT INTO zdb_user (U_DateStart, U_Main_Adres_ID)
VALUES ('2012-04-08', 0);
SET FOREIGN_KEY_CHECKS = 1;
SET @newUID = LAST_INSERT_ID();
INSERT INTO zdb_adres (A_User_ID, A_Zipcode, A_Number)
VALUES (@newUID, '1234AB', 12);
UPDATE zdb_user SET U_Main_Adres_ID = LAST_INSERT_ID() WHERE User_ID = @newUID;
COMMIT;
The problem is that I’m using a ‘circle’ foreign key reference. I bypassed that now by disabling the key checks.
zdb_adres.A_User_ID requires a valid User_ID. And zdb_user.U_Main_Adres_ID requires a valid Adres_ID, but I don’t have either one. Now this all works ‘okay’ as long as the record in zdb_user can actually be created. But there are several constraints on it that could cause it to not be created.
I thought that on an error the transaction would halt, but after running a simple test I discovered this isn’t true at all. Therefore I went googling and I found several solutions like:
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING, NOT FOUND BEGIN ROLLBACK; CALL ERROR_ROLLBACK_OCCURRED; END;
Too bad it doesn’t work, I’m receiving a syntax error when I add it after the START TRANSACTION;:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING, NOT FOUND BEGIN ROLLBACK' at line 1
Does anybody know what the problem is?
The only way to get rid of disabling of foreign key checks is by making
U_Main_Adresnullable.