I have a lot of SQL INSERT statements that have been generated dynamically in code. I want to pass this string of generated queries to a stored procedure to run them, BUT within a transaction. Can this be done?? So something like
Is there a better way of executing these dynamic sql statements? I've been at this problem for ages now! Any help appreciated, thanks
Code:
-- Create the table
CREATE TABLE tblA(a int auto_increment primary key, b int)
-- Create stored procedure
CREATE PROCEDURE `foobar`(IN sSQL varchar(1000))
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
BEGIN
ROLLBACK;
END;
SET AUTOCOMMIT = 0;
[COLOR=red] START TRANSACTION;[/color]
BEGIN
SET @sSQL = sSQL;
PREPARE stmt FROM @sSQL;
[COLOR=red]EXECUTE stmt;[/color]
COMMIT;
END;
END;
-- Call procedure with generated mysql
call foobar([b]"declare MyID int;insert into tblA(b)values(100);set MyID = LAST_INSERT_ID();insert into tblA(b)values (MyID);"[/b]);
/*
-- SQL that is being run
DECLARE MyID int;
INSERT INTO tblA(b)values(100);
SET MyID = LAST_INSERT_ID();
INSERT INTO tblA(b)values (MyID);
*/
Is there a better way of executing these dynamic sql statements? I've been at this problem for ages now! Any help appreciated, thanks