The project needs to dynamically and randomly generate some random numbers with a fixed number of digits, such as 8 digits, 5 digits, etc.
The way I saw it written before is like this
ROUND(ROUND(RAND(),5)*100000)
This way of writing is not very accurate. There is a chance of 4 digits. The Rand() function takes 0 ~ 1( Infinitely close) random function
If a certain random number is taken out is 0.05321
, then the converted result is 5321, which only has 4 digits.
It would be perfect if you could wrap it up with a function. When you find that the number of digits is wrong after taking the value, you can just fill it in.
The following is a function I modified, but the disadvantage is that the generated function cannot have more than 20 digits. 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; IF(CHAR_LENGTH (sTemp)
SET sTempCounts = counts - CHAR_LENGTH(sTemp);
SET sTemp = CONCAT(sTemp, RIGHT(CONCAT(POW(10,sTempCounts),),sTempCounts));
END IF;
RETURN sTemp;
END$$
DELIMITER ;