Friday, October 22, 2004

Select Random Rows from MS Access

(Seleccionar filas aleatoriamente en MS Access)

Usually you have to take a random row from an Access DB, the following code makes it.

Tip: If You're accesing Access in a web (.aspx page, web service) You need remenber that ASPnet user must have full access(read, create, delete, modify) to the folder where the mdb lies, because it has to modify the .mdb file and create/deltete the .ldb file.

Added: Better code in v2.0 Select Random Rows from MS Access


Dim adapter As New OleDbDataAdapter("SELECT * from myTable", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Request.MapPath("data.mdb") + ";")

Dim data As New DataSet
adapter.Fill(data)
Dim table As DataTable = data.Tables(0)
If table.Rows.Count = 0 Then
Throw New Exception("The query return 0 rows")
End If
table.Columns.Add("Random", GetType(Double))
Dim random As New Random
For Each row As DataRow In table.Rows
row("Random") = random.NextDouble
Next

Dim dv As DataView = table.DefaultView
dv.Sort = "Random ASC"
Dim sResult As String

'the first column
sResult = dv.Item(0).Row(0).ToString()




Permalink: Select Random Rows from MS Access 

6 Comments:

At 4:21 PM, Blogger Jose Blanco said...

This comment has been removed by a blog administrator.

 
At 4:24 PM, Blogger Jose Blanco said...

This comment has been removed by a blog administrator.

 
At 4:45 PM, Blogger Jose Blanco said...

HI:

In the code "sResult = dv.Item(Random mod table.rows.count).Row(0).ToString()", which fails,
what is Random?
Why "Random mod table.rows.count" and no a "random number" between 0 and table.rows.count
Why then you need the dataview and does table.Rows(iRandomNumber).Item(0)?

 
At 4:53 PM, Blogger Jose Blanco said...

Hi:
It still is bad, because random is an object
Dim Random As New Random(System.DateTime.Now.Millisecond)
Dim iRandomNumber As Integer = Random.Next(0, table.Rows.Count)

 
At 12:12 PM, Anonymous Anonymous said...

vaya misterio
si pones en el order

ORDER BY Rnd(campo)

tb sale

 
At 3:33 PM, Anonymous Anonymous said...

Visit Website

 

Post a Comment

<< Home