C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » SQL »

Randomly selecting row from database


Posted Date: 03 Aug 2009    Resource Type: Code Snippets    Category: SQL
Author: satyaMember Level: Diamond    
Rating: 1 out of 5Points: 5





Selecting a Random Row From Databse:



Description:


If you want to select row randomly from the databse, you can use this.




Stored Procedure:



CREATE PROCEDURE PS_GetRandomProduct
AS
DECLARE @NoOfRows int
Begin
SELECT @NoOfRows = max(ProductId) FROM Products

SELECT QuantityPerUnit, ProductName FROM Products
WHERE ProductId = (SELECT CAST((RAND()* @NoOfRows) AS int) + 1)
End
GO

Explanation:



ProductId is the primary key of the table (Products). It is the identity field

(auto-incrementing).we are taking maximum value of identity field and assigning

this value into the variable @NoOfRows.A random number is then generated with a br>
maximum possible value of @NoOfRows.


The rand() function generates a random number between 0 and 1, which is multiplied

to the @NoOfRows variable.You may be wondering why 1 is added to the result. The

reason is that the rand() function may return 0 while the ProductId column starts at 1.




Responses

Author: Prashant Mishra    17 Sep 2009Member Level: Bronze   Points : 0
Nice Example of RAND()


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Randomly selecting row from database  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Change Data Type in SQL Server
Previous Resource: SQL and Linq
Return to Discussion Resource Index
Post New Resource
Category: SQL


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use