Last active
February 13, 2023 05:30
-
-
Save ThangLeQuoc/4a8011ec28066e1aa065fa2a15fe080f to your computer and use it in GitHub Desktop.
MySQL - Generate Random String With Desired Length Function script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 $$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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