.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Code Snippets >> SQL Query >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Get the Random Records from a Table

Posted By:Lakhan Pal Garg       Posted Date: May 09, 2010    Points: 10    Category: SQL Query    URL: http://www.dotnetspark.com  

Query to Get the Random Records from a Table in a Database

Query to Get the Random Records from a Table in a Database.
Supoose we want to show 5 Random News on main page of the website.
Table Name:tblNews
Columns: NewsID,Description,DatePosted

SELECT TOP 5 NewsID,Description,DatePosted FROM tblNews ORDER By NEWID() 

OUTPUT: 5 News will be fetched from table at Random. each times 5 different news will be picked from the table.

Thanks & Regards
Lakhan Pal Garg


Further Readings:

Author: VIJAY P         Company URL: http://www.dotnetspark.com
Posted Date: December 02, 2010

Try this solution
Dim DT1 As New DataTable
DT1.Rows.Add("1", "Test1")
DT1.Rows.Add("2", "Test2")
DT1.Rows.Add("3", "Test3")
DT1.Rows.Add("4", "Test4")
DT1.Rows.Add("5", "Test5")
DT1.Rows.Add("6", "Test6")
DT1.Rows.Add("7", "Test7")
DT1.Rows.Add("8", "Test8")
DT1.Rows.Add("9", "Test9")
DT1.Rows.Add("10", "Test10")
DataGridView1.DataSource = DT1

Dim DT2 As New DataTable
Dim I, CNT, J As Integer
Dim RS As New Random

While DT1.Rows.Count > 0
CNT = DT1.Rows.Count - 1
J = RS.Next(CNT)
DT2.Rows.Add(DT1.Rows(J)("SN1"), DT1.Rows(RS.Next(CNT))("NAME1"))
Catch ex As Exception
End Try
End While
DataGridView2.DataSource = DT2

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend