I have some SQL code which generates random numbers using the following technique:
DECLARE @Random1 INT, @Random2 INT, @Random3 INT, @Random4 INT, @Random5 I
For Laravel:
public function generatUniqueId()
{
$rand = rand(10000, 99999);
$itemId = $rand;
while (true) {
if (!BookItem::whereBookItemId($itemId)->exists()) {
break;
}
$itemId = rand(10000, 99999);
}
return $itemId;
}
I guess you could do something like this much simpler and much easier
DECLARE @Upper INT;
DECLARE @Lower INT;
SET @Lower = 1; /* -- The lowest random number */
SET @Upper = 49; /* -- The highest random number */
SELECT @Lower + CONVERT(INT, (@Upper-@Lower+1)*RAND());
For getting a random number without repetition, this will do the job
WITH CTE
AS
(
SELECT randomNumber, COUNT(1) countOfRandomNumber
FROM (
SELECT ABS(CAST(NEWID() AS binary(6)) %49) + 1 randomNumber
FROM sysobjects
) sample
GROUP BY randomNumber
)
SELECT TOP 5 randomNumber
FROM CTE
ORDER BY newid()
To set the highest limit, you can replace 49 with your highest limit number.
You can use Rand() function .
select CEILING(RAND() *<max of random numbers))