| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Classic ASP/VBScript - Random recorset when IDs are not consequtive
It`s very often that records are deleted from a table and IDs are not consequetive. I modified Memnochs' code slightly. It works, but might be not the best optimized, so gurus help in optimization would be very valuable
1. It does not care of frequency of display 2. It does not care about repetitions. Just pure randomizing. Code:
'CODE TO GET RANDOM ID FROM DATABASE STARTS HERE
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open connectstr
' FIRST START: get random ID beween min & max IDs stored in database
qry = "SELECT MAX(ID) As MaxID FROM Yourtablename"
Set oRS = oConn.Execute(qry)
If IsNull(oRS("MaxID")) Then
MaxID = 1
Else
MaxID = oRS("MaxID")
End If
LowNum = 1
HighNum = MaxID
oRS.close
Set oRs = nothing
' FIRST ENDS
' SECOND START: avoid missed IDs and define constant RandomIDfromDB
Do Until CheckRandomID<>""
Randomize()
RandomID = Int((HighNum - LowNum + 1)*Rnd() + LowNum)
qry = "SELECT ID FROM Yourtablename WHERE ID=" & RandomID & " "
Set oRS = oConn.Execute(qry)
if not oRS.EOF then
while not oRS.EOF
CheckRandomID = oRs.Fields("ID")
oRS.movenext
wend
oRS.close
end if
Set oRs = nothing
Loop
if CheckRandomID<>"" then
RandomIDfromDB=CheckRandomID
End If
' SECOND ENDS
Set oConn = nothing
'CODE TO GET RANDOM ID FROM DATABASE ENDS HERE
Now we can use RandomIDfromDB to select random record. |
|
#2
|
||||
|
||||
|
Is this code working properly? If not it should be here if yes then thanks for sharing.
![]() |
|
#3
|
|||
|
|||
|
Yes, it works on my website.
Yes, it works on my website. I use it to show random images, which are stored in DB as OLEobjects and called from DB by their IDs.
|
![]() |
| Viewing: ASP Free Forums > Programming > Code Bank > Classic ASP/VBScript - Random recorset when IDs are not consequtive |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|