Login | Register  

Selecting random record from database

by Scud   Thursday, July 05, 2007 Rating:
 Vote this news:



This ASP source code describes a short way to select a record from database. First we need to calculate how many records we have in our table. Using randomize function, we generate a random number between 0 to count of records in database.

Last part of code to select our record using our random number. We must move dynamic cursor in database table and move it to row number. There a few ways to move cursor to row, but personally we can do it similiar as paging records. We select all records from table dividing one record per page. That's all fox.

Here is the all code.

<%
    set cn =server.CreateObject("adodb.connection")
    cn.open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" &server.MapPath("news.mdb")
    set rs = cn.execute("select count(*) from gnews_articles")

    countOfRec = rs(0)
    randomize
    random_number = int(rnd * countOfRec)+1
    
    rs.close
    set rs = nothing
    Set rs = Server.CreateObject ("ADODB.Recordset")
    rs.CursorLocation = 3
    rs.Open "select * from news", cn, 3,1
    if not rs.eof then
    rs.PageSize = 1
    rs.AbsolutePage = random_number

    response.write "Random Number: " & random_number & "<br/>"

    response.write rs("newsID") & " - " & rs("headline")
    end if

    rs.Close
    set rs = Nothing

    cn.Close
    set cn = Nothing
%>
 




Dotnetindex.com is listed with 411asp.net
Dotnetindex.com is listed with aspin.com
Dotnetindex.com is listed with jspin.com
PHP, ASP, .NET, JSP Resources, Reviews







page counter
Copyright © 2007 Powered by GNews Publisher Positive. All rights reserved. Contact Us - Load Time: 0.04 second(s)