SQL SERVER – Simple Method to Generate Fixed Digit OTP Code Using Random Function

One of my blog readers sent me the following mail after reading my earlier blog posts about Random Function and OTP Code. Before you read the email, you can read those blog posts here, here, and here.

SQL SERVER - Simple Method to Generate Fixed Digit OTP Code Using Random Function OPTimage

“I want to generate a six digit number to send the customers who register for the app. It is like an OTP (One Time Password). What is the simpler way to do this in SQL?”

Well. 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). The logic is to multiply value returned by RAND() by 1 billion so that it has enough digits and apply LEFT function to extract 6 digits needed.

SELECT LEFT(CAST(RAND()*1000000000 AS INT),6) as OTP

Now as RAND() sometimes give 0, to handle it, we can change the code to

SELECT LEFT(CAST(RAND()*1000000000+999999 AS INT),6) as OTP

so that you always get 6 digit number.

SQL SERVER - Simple Method to Generate Fixed Digit OTP Code Using Random Function otp

This is really a simple method of generating 6 digit number. It can be easily extended to any number of digits.

You may be interested to read these posts related to RAND function.

SQL SERVER – Random Number Generator Script – SQL Query
SQL SERVER – Using RAND() in User Defined Functions (UDF)
SQL SERVER – Generate Different Random Number for Each Group Using RAND() Function 

Reference: Pinal Dave (https://blog.SQLAuthority.com)

SQL Password, SQL Random, SQL Scripts, SQL Server
Previous Post
SQL SERVER – How to Generate Random Password? – Enhanced Version – Part 2
Next Post
SQL SERVER – UDF – User Defined Function to Extract Only Numbers From String

Related Posts

1 Comment. Leave new

  • Hi Pinal,

    Can we use below query also? I know, it’s including Characters in the result.

    select LEFT(NEWID(),6)

    Reply

Leave a Reply