I am using stored procedure to generate sequence consisting of prefix and number in given range (etc sequence “AB100″, “AB101″, …, “AB199″, “AB200″)
The stored procedure includes REPEAT
loop, in which character string is constructed and inserted into table.
When all the looping is inside transaction, the procedure runs very fast, but when I insert data without transaction, running the procedure lasts 400 times longer.
Can anyone explain, why is that so?
Alternatively, if anyone has better idea how to generate sequences like this, i will be happy to hear them.
Here is the code:
-- create table
CREATE TABLE seq
(
Code CHAR(12)
) ENGINE = INNODB;
-- fast procedure with transactions
DELIMITER $$
CREATE PROCEDURE sp_sequence(IN val_prefix CHAR(2), IN val_from INT, IN val_to INT )
BEGIN
START TRANSACTION;
SET @val = val_from;
REPEAT
INSERT INTO seq (Code) VALUES (CONCAT(val_prefix, @val));
SET @val = @val + 1;
UNTIL @val > val_to END REPEAT;
COMMIT;
END$$
DELIMITER ;
-- slow procedure without transactions
DROP PROCEDURE IF EXISTS sp_sequence_slow;
DELIMITER $$
CREATE PROCEDURE sp_sequence_slow(IN val_prefix CHAR(2), IN val_from INT, IN val_to INT )
BEGIN
SET @val = val_from;
REPEAT
INSERT INTO seq (Code) VALUES (CONCAT(val_prefix, @val));
SET @val = @val + 1;
UNTIL @val > val_to END REPEAT;
END$$
DELIMITER ;
And here are results:
mysql> CALL sp_sequence('TX', 11000, 12000);
Query OK, 0 rows affected (0.09 sec)
mysql> CALL sp_sequence_slow('TX', 11000, 12000);
Query OK, 0 rows affected (40.07 sec)