Skip to content

Instantly share code, notes, and snippets.

@ThangLeQuoc
Last active February 13, 2023 05:30
Show Gist options
  • Save ThangLeQuoc/4a8011ec28066e1aa065fa2a15fe080f to your computer and use it in GitHub Desktop.
Save ThangLeQuoc/4a8011ec28066e1aa065fa2a15fe080f to your computer and use it in GitHub Desktop.
MySQL - Generate Random String With Desired Length Function script
DELIMITER $$
DROP FUNCTION IF EXISTS fn_generate_random_code $$
CREATE FUNCTION fn_generate_random_code (desired_code_len INTEGER) RETURNS VARCHAR(100)
NO SQL
BEGIN
SET @possible_characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
SET @len = LENGTH(@possible_characters);
SET @random_code = '';
append_char_to_random_code: LOOP
IF LENGTH(@random_code) >= desired_code_len THEN
LEAVE append_char_to_random_code;
END IF;
SET @random_char_pos = FLOOR(RAND()*(@len - 0 + 1) + 0);
SET @extracted_char = SUBSTRING(@possible_characters, @random_char_pos, 1);
SET @random_code = CONCAT(@random_code, @extracted_char);
END LOOP;
RETURN @random_code;
END $$
@ThangLeQuoc
Copy link
Author

ThangLeQuoc commented Feb 16, 2020

Execute by calling the function with expected string len
SELECT fn_generate_random_code(6); , this will produce a 6-length random string with pattern contains characters in the @possible_characters variable, which is 0-9 and A-Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment