Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate x digit random number in sql server 2008 R2

I have to generate 12 digit number(bigint) in sql server 2008 R2 itsleft. i have used these methods which i found on the internet

convert(numeric(12,0),rand() * 999999999999) 

and

RIGHT(CAST(CAST(NEWID() AS VARBINARY(36)) AS BIGINT), 12)

while these do work the problem is sometimes the generated number has leading zeroes and that is stripped resulting in a 10 or 11 digit number.

Is there a consistent way to generate x digit numbers in sql?

Thanks. this is very urgent.

like image 522
Pankaj Kumar Avatar asked Oct 10 '11 06:10

Pankaj Kumar


People also ask

How do I generate a random 10 digit number in SQL?

There are several methods to generate a random number. One simple method is to make use of RAND() function available in SQL Server. RAND() function simply generate a decimal number between 0 (inclusive) and 1 (exclusive).

How do you generate a 9 digit random number in SQL?

for example 0987654321 note that each digit appear once.. it generates but at some point numbers repeat. but it is client need to make sure in 9 digit sequence no number appears twice.. You are not looking for a random number then as it is perfectly valid for a random number generator to repeat the same value.

How do you generate a random number in SQL?

SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

How do you generate unique random numbers in SQL Server?

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.


2 Answers

One solution is to just make sure it's in the 12 digit range.

convert(numeric(12,0),rand() * 899999999999) + 100000000000
like image 65
Rinze Smits Avatar answered Oct 02 '22 10:10

Rinze Smits


How about add a random number to 100000000000

like image 29
Mike Christensen Avatar answered Oct 02 '22 12:10

Mike Christensen