dimanche 16 mai 2021

Best way to Create a Random String in MySql with function

I would like to create random password with lenght 5 Character in mysql. Then I found the best way is to creating a function in MySql that I could call every where.

Function Structure:

 DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    FUNCTION `database`.`RandString` () 
    RETURNS CHAR(5) CHARACTER SET utf8
    /*ADD HERE */
    READS SQL DATA
    DETERMINISTIC
    BEGIN
        SET @returnStr = '';
    SET @allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    SET @i = 0;

    WHILE (@i < 5) DO
        SET @returnStr = CONCAT(@returnStr, SUBSTRING(@allowedChars, FLOOR(RAND() * LENGTH(@allowedChars) + 1), 1));
        SET @i = @i + 1;
    END WHILE;

    RETURN @returnStr;
    
    END$$

DELIMITER ;

And you can use it like:

RandString()

When you know better way please comment below.




Aucun commentaire:

Enregistrer un commentaire