Skip to content

Instantly share code, notes, and snippets.

@BenCavens
Last active December 12, 2019 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenCavens/1a765a86268347a7fbe5e13d70673715 to your computer and use it in GitHub Desktop.
Save BenCavens/1a765a86268347a7fbe5e13d70673715 to your computer and use it in GitHub Desktop.
Small mysql loop for generating unique alphanumerical codes
DROP PROCEDURE IF EXISTS generator;
DELIMITER //
CREATE PROCEDURE generator(total INTEGER UNSIGNED, max_chars INTEGER UNSIGNED)
BEGIN
SET @currentLoop = 0;
REPEAT
SET @code = '';
WHILE LENGTH(@code) < max_chars DO
SET @code = CONCAT(@code, substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(round(rand()*4294967296))*36+1, 1));
END WHILE;
# OUR TABLE expects to have a column 'code' with an unique constraint. With the IGNORE statement, any duplicate codes will not get inserted.
INSERT IGNORE INTO randoms SET code = @code;
SET @currentLoop = @currentLoop + 1;
UNTIL @currentLoop >= total END REPEAT;
END //
DELIMITER ;
# Here we trigger the generate procedure. Two arguments are expected: first the total amount of codes, secondly the length of each generated code.
# In the example below we generate 1000 codes with each a length of 8 characters.
CALL generator(1000, 8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment