I need to generate a random number between 1 and 99 but without decimals. Try one select
like the following:
SELECT RAMD () 1 AND 99
But the same gives me an error search in Google and I did not understand.
I need to generate a random number between 1 and 99 but without decimals. Try one select
like the following:
SELECT RAMD () 1 AND 99
But the same gives me an error search in Google and I did not understand.
I leave you the example, I hope it helps you
SQL Server has since version 2005 of the function
RAND()
which returns a pseudo random floating point number. The way to generate integers in a certain range is using the following formula:In your example it would be something like this:
Important:
RAND()
receives a parameterseed
that is the seed of the random generator, we must take into account that if we indicate a certain seed at any time, the generation of numbers will always be the same. ThisSELECT RAND(100), RAND(), RAND()
will always return the same three numbers.Another thing to be aware of
RAND()
is if it is used inside aSELECT
. If we do something like this:SELECT id, RAND() FROM Tabla
we will always obtain the same number, this is because implicitly the same seed is always used, in these cases the solution is to use a different value per row as "seed", it could beROW_NUMBER()
but it may be too obvious, the other alternative is to useNEWID()
as follows:SELECT id, RAND(CAST( NEWID() AS varbinary)) FROM Tabla
A first option is using the rand() function. I use it in the following way:
To generate, for example, a 4-digit code.
A second option using the checksum and newid functions:
The newid() returns a long alphanumeric value, the checksum minimizes this, but there are times when it returns negative values, so using abs() returns the absolute value.