28.7.09

Rand function and floor function in SQL Server

Rand function and floor function in SQL Server:

Most of the time, we need a functionality to generate random numbers in our application. SQL Server is offering a handy function to generate random numbers. Here is a small sample,

select rand()

The above query is used to fetch the value between 0 and 1. If I need to create a random number between 0 and 100.

Then, we need to multiply the function with 100.

SELECT 100*RAND()
The above query will fetch the recordds with decimal values which ranges from 0 to 100.



In case, If we need the value in Integer type. Then, we have to go for floor command which will remove the decimal part from the output.

SELECT floor(100*RAND())



In case, If you want to restrict the records between 2 to 100 (I dont want 0 and 1 to be retrieved). Then, we can use the below query.
SELECT floor(98*RAND())+2

Thanks and Regards,

Venkatesan Prabu .J

No comments:

Post a Comment