I would like to generate a 5 digit number which do not repeat inside the database. Say I have a table named numbers_mst with field named my_number.
I want to generate the number the way that it do not repeat in this my_number field. And preceding zeros are allowed in this. So numbers like 00001 are allowed. Another thing is it should be between 00001 to 99999. How can I do that?
One thing I can guess here is I may have to create a recursive function to check number into table and generate.
php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) != 1) { foreach ($check as $val) { if ($val == $page_no) { $page_no = mt_rand(1,10); continue; } } return $page_no; } else { return $page_no; } } ?>
The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.
SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.
SELECT FLOOR(RAND() * 99999) AS random_num FROM numbers_mst WHERE "random_num" NOT IN (SELECT my_number FROM numbers_mst) LIMIT 1
What this does:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With