Random Number in SQL

Generate Random number inside SQL using timestamp (GetDate function)
One of small hidden treasure I had in my old library

CodeFunctionName
What is this?

Public

Tested

Imported
Q. How can I get random numbers from SQL Server? Using rand() I always get the same sequence. (v1.0    1999.03.24)
A. This is because you need to start the rand function off with a random number. Use something like :-


SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()) )

SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()) )
    As Deci1,
Convert(int , RAND( (DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()) )
    * 100000 ) As Intx10000,
Convert(int , RAND( (DATEPART(mm, GETDATE()) * 100000 ) + (DATEPART(ss, GETDATE()) * 1000 ) + DATEPART(ms, GETDATE()) )
    * 100000000 ) As Intx100000000

Views 175

Downloads 97

CodeID
DB ID

ANmarAmdeen
626
Attachments
Revisions

v1.0

Tuesday
January
30
2024