0

I need generate a random string in MySql stored function. I solved this problem, but my solution seems too ugly and too slow:

CREATE FUNCTION generate_salt() RETURNS varchar(11) CHARSET utf8
BEGIN
    DECLARE res varchar(11) DEFAULT '';
    DECLARE salt_sym varchar(2);
    DECLARE tmp_res varchar(20) DEFAULT'';
    DECLARE salt_len int DEFAULT 10;

    WHILE salt_len > 0 DO
      SET salt_sym = HEX(FLOOR(32 + RAND() * 96));
      SET tmp_res = CONCAT(tmp_res, salt_sym), salt_len = salt_len - 1;
    END WHILE;
    set res=UNHEX(tmp_res);
    RETURN res;
END

This code converts the random integers from a diapason [32, 126] to hexadecimal string and then converts the hexadecimal string to ascii-string using unhex() function.

Is there any way to convert a digit to ASCII character ( 0x30 => '0', 0x31=>'1', 0x32=> '2', etc.) without double (byte => hex 2-literal string => char) conversion?

2 Answers 2

1

Why not just use:

return sha2(rand(), 256)

If you want more randomness, just concat multiple rand() calls.

Sign up to request clarification or add additional context in comments.

Comments

0

For generating random string, you can use CHAR() (to cast the integer to a character) and MOD() functions:

CHAR(65+MOD(ROUND(RAND()*100),26))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.