Skip to content

Instantly share code, notes, and snippets.

@HRezaei
Created March 25, 2017 11:31
Show Gist options
  • Save HRezaei/2f84b4e10b9a7806b23c9eed1ff758fd to your computer and use it in GitHub Desktop.
Save HRezaei/2f84b4e10b9a7806b23c9eed1ff758fd to your computer and use it in GitHub Desktop.
Generate random bit strings in MySQL
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `random_str`() RETURNS char(16) CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci
BEGIN
DECLARE chars varchar(16);
DECLARE rs varchar(16);
SET rs = '';
SET chars = 'ABCDEF1234567890';
WHILE (LENGTH(rs) < 16) DO
SET rs = CONCAT(rs, SUBSTRING(chars, RAND() * LENGTH(chars), 1));
END WHILE;
RETURN rs;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `fill_test`(IN `cnt` INT UNSIGNED)
NO SQL
BEGIN
DECLARE c int;
DECLARE rs varchar(16);
SET c = 0;
while (c < cnt) DO
set rs = random_str();
INSERT INTO test_random_binary_codes (hash) VALUES (rs);
set c = c + 1;
end while;
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment