It is often used to obtain a random number between two numbers. C # has a built-in method, and the database does not. I have previously found a method that is implemented through database user-defined functions, but I cannot find it. I wrote it myself today and recorded it for backup!
CodeAs follows:
If Exists ( Select * From SYS. Objects Where Name = ' F_random ' )
Drop Function F_random
Go
/*
Obtain a random number between two numbers
*/
Create Function F_random
(
@ Min_num Int ,
@ Max_num Int
)
Returns Int
As
Begin
Declare @ Basicnumber Decimal ( 18 , 9 ) -- Base
Declare @ Randnumber Decimal ( 18 , 9 ) -- Random Number
If @ Max_num <= 10
Set @ Basicnumber = 10
Else If @ Max_num <= 100
Set @ Basicnumber = 100
Else If @ Max_num <= 1000
Set @ Basicnumber = 1000
Else If @ Max_num <= 10000
Set @ Basicnumber = 10000
While 1 = 1
Begin
Select @ Randnumber = Randvalue From Vrandom
Set @ Randnumber = @ Randnumber * @ Basicnumber
If @ Randnumber > = @ Min_num And @ Randnumber < @ Max_num
Break
Else
Continue
End
Return Cast ( @ Randnumber As Int )
End
Go
Usage:
Select DBO. f_random (1,100) as randnum
Be sure to add DBO!