Login

Latest postings for ASP/ VbScript.
Daily Code Email
|
|
| | |
| | | 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 | | | | | Your Vote! | |
See Voting Log | | | | Other User Comments |
6/6/2000 11:40:19 AM: Gail 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 AM: Nathan
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 AM: Nathan 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 PM: Larry 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 AM: Nathan 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 AM: Nathan 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 AM: Joel
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 AM: vijay
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 PM: Santu Ghosh
very very good concept (If this comment was disrespectful, please report it.)
|
9/13/2008 6:49:59 AM: Dawie
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. | |
|