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?