The project needs to dynamically generate random numbers with fixed digits, such as 8-bit and 5-bit.
The method we saw earlier is as follows:
ROUND (RAND (), 5) * 100000)
This is not accurate, and there is a probability that four digits will occur. The Rand () function is 0 ~ 1 (infinitely close) Random Function
If a random number is 0.05321
In this way, the conversion is 5321, with only four digits.
If you can wrap it with a function, when you find that the number of digits is incorrect after the value is obtained, it is perfect to fill in the bits.
The following is a function I modified, but the disadvantage is that the number of digits of the generated function cannot exceed 20. Of course, you can change it.
DELIMITER $
USE 'prvecard '$
Drop function if exists 'getrand' $
Create definer = 'pecard '@' % 'FUNCTION 'getrand' (counts INTEGER) returns varchar (20) CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR (20 );
DECLARE sTempCounts INTEGER;
SET sTemp = CONCAT (ROUND (RAND (), counts) * (POW (10, counts ))),);
IF (CHAR_LENGTH (sTemp) <counts) THEN
SET sTempCounts = counts-CHAR_LENGTH (sTemp );
SET sTemp = CONCAT (sTemp, RIGHT (CONCAT (POW (10, sTempCounts),), sTempCounts ));
End if;
RETURN sTemp;
END $
DELIMITER;