Returns a random number in the range of two SQL numbers.

Source: Internet
Author: User

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!

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.