Mysql generates random numbers with fixed digits

Source: Internet
Author: User

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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.