Create a loop in a stored procedure to insert many rows with random data

A solution based on this Stack Overflow answer to insert many random data rows to given table in SQL:

TRUNCATE TABLE `devices`;

DROP PROCEDURE IF EXISTS InsertRand;

DELIMITER $$
CREATE PROCEDURE InsertRand(IN NumRows INT)
    BEGIN
        DECLARE i INT;
        SET i = 1;
        START TRANSACTION;
        WHILE i <= NumRows DO
            SET @dn = CONV(FLOOR(RAND() * 99999999999999), 20, 36);
            INSERT INTO `devs` VALUES (NULL, FLOOR((RAND() * 3)), CONCAT('Dev ', @dn));
            SET i = i + 1;
        END WHILE;
        COMMIT;
    END$$
DELIMITER;

To execute this little piece just call:

CALL InsertRand(77);

That’s all folks! :>

Leave a Reply