However, I still hope that the old birds will give me more advice. Now let's get started with the question:
Random Function: rand ()
Run select rand () in the query analyzer. The result is a random decimal number similar to this: 0.36361513486289558,
Decimal places like this are rarely used in practical applications. Generally, random numbers are used as random integers. Let's look at the following two random integer acquisition methods:
1,
A:
Select floor (rand () * N) --- The generated number is as follows: 12.0
B:
Select cast (floor (rand () * N) as int) --- The generated number is as follows: 12
2,
A: select ceiling (rand () * N) --- The generated number is as follows: 12.0
B: select cast (ceiling (rand () * N) as int) --- The generated number is as follows: 12
The N in it is an integer you specify, such as 100. We can see that the method of the two methods contains. the decimal value of 0, and the B method is the real integer.
Generally, there is no difference between the two methods? There is actually one thing, that is, their range of random numbers:
The number range of Method 1: 0 to N-1, for example cast (floor (rand () * 100) as int) will generate any integer between 0 and 99
The number range of Method 2: 1 to N. For example, cast (ceiling (rand () * 100) as int) generates any integer between 1 and 100.
For this difference, you can see the online help of SQL:
Bytes ------------------------------------------------------------------------------------
Compare CEILING and FLOOR
The CEILING function returns the smallest integer greater than or equal to the given numeric expression. The FLOOR function returns the largest integer less than or equal to the given numeric expression. For example, for the numeric expression 12.9273, CEILING returns 13 and FLOOR returns 12. The data types returned by FLOOR and CEILING are the same as those of the input numeric expression.
----------------------------------------------------------------------------------
Now, you can use these two methods as needed to obtain the random number ^_^.
In addition, I would like to remind you that the method for randomly obtaining any N records in the table is very simple, just use newid ():
Select top N * from table_name order by newid () ---- N is an integer you specify, and the table is the number of records obtained.
OK. This article is written here.