All source code in ASP/ VbScript Ask a ASP/ VbScript Pro Discussion Forum Categories All jobs in ASP/ VbScript
Quick Search for:  in language:    
return,group,Random,Records,from,database,exa
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
ASP/ VbScript Stats

 Code: 281,486. lines
 Jobs: 101. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login

NEW! LEARNING CENTER
Special educational offers, white papers, webcasts, podcasts

  NEW! Download Rational Performance Tester V8 (download now)
  NEW! Download Rational Functional Tester V8 (download now)
  NEW! Download Rational Service Tester for SOA Quality V8 (download now)
  NEW! Teleconference: Quality In Action - Using Rational Quality Manager with Functional, Performance and Web Service Testing Products (download now)
  NEW! Introducing IBM Rational AppScan Developer Edition – easing security testing by non-security professionals (download now)

 

 


Latest postings for ASP/ VbScript.
Click here to see a screenshot of this code!Mess Officer Management System (Sistem Pengurusan Mess Pegawai)
By Mohd Fauzi on 11/23

(Screen Shot)

Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!



 
 
   

Return a Group of Random Records

Print
Email
 
article
Submitted on: 5/28/2000 6:02:14 PM
By: Larry Boggs  
Level: Beginner
User Rating: By 6 Users
Compatibility:ASP (Active Server Pages)

Users have accessed this article 11702 times.
 
 
     To return a group of Random Records from a database. For example, a group of random questions for a quiz/test.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
<--random.asp--> <--Copyright (c) 1999 by Larry L. Boggs. All rights reserved.--> <--Generate a random recordset from an Access database--> Random Recordset

Return a Group of Random Records

While working on a web based competency-testing application I needed a way to return not just ONE random record but a group of random records. I searched the net high and low for a couple of months trying to find something that would allow me do this. I eventually hunkered down and came up with my own way of doing this.

First comes the SQL statement to return the set of records you will pick your Random records from:

    <%
    strConnection="driver={Microsoft Access Driver (*.mdb)};dbq=" & server.mappath("/testdb.mdb")
    strSQL = "SELECT id FROM tblQuestions"
    set objConn = Server.CreateObject("ADODB.Connection")
    Set objRst = Server.CreateObject("ADODB.Recordset")
    objConn.Open strConnection
    set objRst.ActiveConnection = objConn
    objRst.LockType = adLockOptimistic
    objRst.CursorType = adOpenKeySet
    objRst.Open strSQL
    %>

Next, set the upper limit of the Randomize function by setting the variable rndMax equal to the RecordCount.

    <%
    objRst.MoveLast
    cnt = objRst.RecordCount
    cnt1 = cnt
    rndMax = cnt
    %>

Next, set the number of records returned to either the number of questions they asked for or equal to the RecordCount.

    <%
    If CInt(Request.Form("maxNumber")) < cnt Then
    	cnt1 = CInt(Request.Form("maxNumber"))
    End If
    %>

Now we want to return a Random number. Check if the variable “str1” already contains that number. If so then that number is skipped and it loops again returning another Random record number. This ensures that NO values are repeated. If not then plug that number into the “str1” variable so we will know that that number has already been used the next time through the loop. If the random number is not contained within the “str1” variable then the value of the “ID” field is returned and plugged into the “str” variable. This loops until the appropriate number of values have been plugged into the “str” variable.

    <%
    str = ","
    str1 = ","
    	
    Do Until cnt1 = 0
    Randomize
    RndNumber = Int(Rnd * rndMax)
    If (InStr(1, str1, "," & RndNumber & "," ) = 0) Then
    	str1 = str1 & RndNumber & ","
    	cnt1 = cnt1 - 1
    	objRst.MoveFirst
    	objRst.Move RndNumber
    str = str & objRst("id") & ","
    	End If
    Loop
    %>

Now we have a variable, (str), that contains a comma-delimited list of values from the “ID” field. Now, just reference the comma- delimited string contained within the “str” variable in your SQL statement:

    <%
    sql = "SELECT * FROM tblQuestions WHERE (((InStr(1,'" & str & "',(',' & [id] & ',')))<>0)) "
    %>

This will return your Random set of records!

Here's the whole thing:

    <%
    <--Generate a random recordset from an Access database-->
    <--#include virtual="/adovbs.inc"--> 
    <%
    Dim objConn
    Dim objRst
    Dim strSQL
    Dim strConnection
    Dim str
    Dim str1
    Dim cnt
    Dim cnt1
    Dim rndMax
    Dim RndNumber
    strConnection="driver={Microsoft Access Driver (*.mdb)};dbq=" & server.mappath("/testdb.mdb")
    strSQL = "SELECT id FROM tblQuestions"
    set objConn = Server.CreateObject("ADODB.Connection")
    Set objRst = Server.CreateObject("ADODB.Recordset")
    objConn.Open strConnection
    set objRst.ActiveConnection = objConn
    objRst.LockType = adLockOptimistic
    objRst.CursorType = adOpenKeySet
    objRst.Open strSQL
    objRst.MoveLast
    cnt = objRst.RecordCount
    cnt1 = cnt
    rndMax = cnt
    If CInt(Request.Form("maxNumber")) < cnt Then
    	cnt1 = CInt(Request.Form("maxNumber"))
    End If
    str = ","
    str1 = ","
    	
    Do Until cnt1 = 0
    Randomize
    RndNumber = Int(Rnd * rndMax)
    If (InStr(1, str1, "," & RndNumber & "," ) = 0) Then
    	str1 = str1 & RndNumber & ","
    	cnt1 = cnt1 - 1
    	objRst.MoveFirst
    	objRst.Move RndNumber
    str = str & objRst("id") & ","
    	End If
    Loop
    objRst.Close
    Set objRst = Nothing
    sql = "SELECT * FROM tblQuestions WHERE (((InStr(1,'" & str & "',(',' & [id] & ',')))<>0)) "
    Set objRst = Server.CreateObject("ADODB.Recordset")
    set objRst.ActiveConnection = objConn
    objRst.LockType = adLockOptimistic
    objRst.CursorType = adOpenKeySet
    objRst.Open sql
    %>
    ...DISPLAY THE RECORDS RETURNED...
    <%
    objRst.Close
    Set objRst = Nothing
    objConn.Close
    Set objConn = Nothing
    %>
    

I'd be interested in hearing from anyone that builds upon this and/or how they put it to use!

See Ya!
Larry Boggs

 
 Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
6/6/2000 11:40:19 AMGail Vaught

This code will be helping me in the near future with a project that I'm working on.
(If this comment was disrespectful, please report it.)

 
4/6/2001 2:47:38 AMNathan

I think there is a slight problem with the code with the statement InStr(1, str1,
(If this comment was disrespectful, please report it.)

 
4/6/2001 2:48:55 AMNathan Arendt

I think there is a slight problem with the code with the statement InStr(1, str1, "," & RndNumber & "," ). The problem is that you are looking for a string with a leading comma but in the first pass through the loop there is no leading comma. Say the first random number is 6 which is place into str1 so it now contains "6,". Now lets say the second pass through the loop has a random number of 6 again. The if statement is looking for the string ",6," but that string dose not exist. Because of this the very first random number chosen will always have the potential of repeating 1 time. This can be easily fixed by placing a comma at the beginning of str1 or by eliminating the test for the leading comma. Thanks for the code I found it useful.
(If this comment was disrespectful, please report it.)

 
4/6/2001 1:42:25 PMLarry Boggs

Actually there is there is no TRAILING comma as a leading comma is added to the str and str1 variables prior to entering the Do Loop. So in essence what you are doing is just dumping the first random number that is returned. I couldn't get it to work any other way. Have you figured out a way? I'm glad you found it useful!
(If this comment was disrespectful, please report it.)

 
4/7/2001 4:18:32 AMNathan Arendt

Sorry appearntly I did not understand the code as well as I thought.
(If this comment was disrespectful, please report it.)

 
4/7/2001 4:52:44 AMNathan Arendt

Anyway I uploaded my solution here: http://www.planetsourcecode.com/xq/ASP/txtCodeId.6577/lngWId.4/qx/vb/scripts/ShowCode.htm
(If this comment was disrespectful, please report it.)

 
6/30/2001 7:45:54 AMJoel

I´m have a problem with this line: sql = "SELECT * FROM tblQuestions WHERE (((InStr(1,'" & str & "',(',' & [id] & ',')))<>0)) " Im use the SQL Server 2000 database. Error is: SQL Server]'InStr' is not a recognized function name.
(If this comment was disrespectful, please report it.)

 
1/21/2002 2:58:13 AMvijay

fine
(If this comment was disrespectful, please report it.)

 
4/18/2003 1:46:48 PM

Was there ever a solution for users of SQL server? I get an error with the InStr() function.
(If this comment was disrespectful, please report it.)

 
7/10/2003 12:25:20 PM

why do you use objRs.Movelast? I keep getting an error saying that
(If this comment was disrespectful, please report it.)

 
5/17/2004 5:13:08 PM

I cannot figure out a portion of this code:
(If this comment was disrespectful, please report it.)

 
5/17/2004 5:15:17 PM

Hi, I have unsuccessfully tried to retrieve every column in my database to populate this section:
...DISPLAY THE RECORDS RETURNED...
I am stumped. Any thoughts would be appreciated.
Thanks,
Deb

(If this comment was disrespectful, please report it.)

 
5/19/2007 6:54:19 PMSantu Ghosh

very very good concept
(If this comment was disrespectful, please report it.)

 
9/13/2008 6:49:59 AMDawie

This code is Brilliant!!! Whoever says otherwise, needs to brush up their skills! Solution to the problems some of you have with: SELECT * FROM tblQuestions WHERE (((InStr(1,'" & str & "',(',' & [id] & ',')))<>0)) Chop off the First & last , from str and then just split str on the commmas(,) making it an Array and loop through it while selecting your records from the DB.
(If this comment was disrespectful, please report it.)

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author from the email account you registered on the site, so you can correspond directly.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
To post feedback, first please login.


 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | ASP/ VbScript Home | Site Home | Other Sites | Open Letter from Moderators | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997-2008 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.   Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.