473,772 Members | 2,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to choose a random record from a database

ill have a database with 1 table and 3 fields:

ID FIRSTNAME LASTNAME

(the ID field will be the auto incrementing index)

there might be 10 records in the DB, there might be 10,000.
i need to open the DB and randomly select a record (and then display the
name, which i dont have a problem with)
how can i randomly select a record? im guessing id have to open a recordset
and check the count to get the number of records, so lets say there were 100
records. i imagine i would have to generate a random number between 1 and
100....

anyone have a small example?
Sep 8 '06
26 3160
Access for now....
can i use the same kind of query? would you be so kind as to show me an
example based on what i have already shown you?

"Aaron Bertrand [SQL Server MVP]" <te*****@dnartr eb.noraawrote in message
news:ug******** ******@TK2MSFTN GP06.phx.gbl...
this opens up the table, gets a count of num records, generates a random
number between 0 and numrecords-1, then moves to that record, and displays
a random email address.

seems like it works perfectly... do you see any issues?
>>

I suppose you haven't read any of my comments about why the suggested
route is better. For example, you don't need to pull the whole table to
the client in order to pick a random row.

If you are going to be using SQL Server Express, then you can say it as
simply as

SELECT TOP 1 Email_Address FROM Table1 ORDER BY NEWID();

(As the link suggested way back at the start of this thread, but I still
suppose you haven't read it (at least not in full).)

A

Sep 8 '06 #21
Access for now....
can i use the same kind of query? would you be so kind as to show me an
example based on what i have already shown you?
Can you use what I already showed you? Or do I need to create an Access
database and attach everything for you?

<%
Randomize()
randNum = (CInt(1000 * Rnd) + 1) * -1

set conn = CreateObject("A DODB.Connection ")
' create connection string here

sql = "SELECT TOP 1 EmailAddress," & _
"r = Rnd(" & randNum & ")" & _
"FROM Table1 " & _
"ORDER BY r"

set rs = conn.execute(sq l)

response.write rs("EmailAddres s")

' ...
rs.close: set rs = nothing
conn.close: set conn = nothing
%>

Have you tried this at all? STOP WORRYING ABOUT THE SIZE OF THE RANDOM
NUMBER POOL AND HOW MANY ROWS ARE IN THE TABLE. JUST TRY IT, PLEASE. This
thread has gone about 40 messages longer than it should have.

Of course, you are more than free to use what 'seems like it works
perfectly' if you like slicing bread with a chainsaw or flossing with a
bungee cable.

A
Sep 8 '06 #22
Look. Just change your code to this and try it:

<%
Dim oConn, oRS, randNum, sql
Randomize()
randNum = (CInt(1000 * Rnd) + 1) * -1
sql = "SELECT TOP 1 EMAIL_ADDRESS, " & _
"r = Rnd(" & randNum & ") " & _
"FROM TABLE1"
Set oConn=Server.Cr eateObject("ADO DB.Connection")
oConn.Provider= "Microsoft.Jet. OLEDB.4.0"
oConn.Open Server.MapPath( "temp.mdb")
Set oRS=oconn.Execu te(sql, , 1)

Response.Write oRS("EMAIL_ADDR ESS")

oRS.close
oConn.close
Set oConn = nothing
Set oRS = nothing
%>
Jimmy wrote:
ok i got ya...
so is there a way to "oRS.Move" to a particular record without having
to do it this way?
ie, can i open the DB to get a record count without SELECTing
anything?

"Bob Barrows [MVP]" <re******@NOyah oo.SPAMcomwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
>Jimmy wrote:
>>this is what i have working so far... tell me what you think:
oRS.Open "SELECT EMAIL_ADDRESS FROM TABLE1", oConn, adOpenStatic,
adLockReadOnl y
Randomize()
randNum = CInt((oRS.Recor dCount - 1) * Rnd)

Response.Writ e("RecordCoun t: " & oRS.RecordCount & "<br><br>")

oRS.Move randNum
>>>
seems like it works perfectly... do you see any issues?

Yes. You're retrieving all the records from the database when you
only need one of them. Not a very efficient use of network or server
resources.

--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get
a quicker response by posting to the newsgroup.
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.
Sep 8 '06 #23
<shudder>

Can't wait to see what happens here when we graduate to a CRUD interface
(create/retrieve/update/delete)...
Sep 8 '06 #24
Aaron Bertrand [SQL Server MVP] wrote:
<shudder>

Can't wait to see what happens here when we graduate to a CRUD
interface (create/retrieve/update/delete)...
?
That sound you hear is the sound of that statement whizzing over my
head. :-)
Shall we take this offline?

--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.
Sep 8 '06 #25
it doesnt like your code.... missing parameter here:

Set oRS=oconn.Execu te(sql, , 1)

"Bob Barrows [MVP]" <re******@NOyah oo.SPAMcomwrote in message
news:eA******** ******@TK2MSFTN GP06.phx.gbl...
Look. Just change your code to this and try it:

<%
Dim oConn, oRS, randNum, sql
Randomize()
randNum = (CInt(1000 * Rnd) + 1) * -1
sql = "SELECT TOP 1 EMAIL_ADDRESS, " & _
"r = Rnd(" & randNum & ") " & _
"FROM TABLE1"
Set oConn=Server.Cr eateObject("ADO DB.Connection")
oConn.Provider= "Microsoft.Jet. OLEDB.4.0"
oConn.Open Server.MapPath( "temp.mdb")
Set oRS=oconn.Execu te(sql, , 1)

Response.Write oRS("EMAIL_ADDR ESS")

oRS.close
oConn.close
Set oConn = nothing
Set oRS = nothing
%>
Jimmy wrote:
>ok i got ya...
so is there a way to "oRS.Move" to a particular record without having
to do it this way?
ie, can i open the DB to get a record count without SELECTing
anything?

"Bob Barrows [MVP]" <re******@NOyah oo.SPAMcomwrote in message
news:%2******* *********@TK2MS FTNGP05.phx.gbl ...
>>Jimmy wrote:
this is what i have working so far... tell me what you think:
oRS.Open "SELECT EMAIL_ADDRESS FROM TABLE1", oConn, adOpenStatic,
adLockReadOn ly
Randomize( )
randNum = CInt((oRS.Recor dCount - 1) * Rnd)

Response.Wri te("RecordCount : " & oRS.RecordCount & "<br><br>")

oRS.Move randNum
seems like it works perfectly... do you see any issues?
Yes. You're retrieving all the records from the database when you
only need one of them. Not a very efficient use of network or server
resources.

--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get
a quicker response by posting to the newsgroup.

--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.


Sep 8 '06 #26
Look, the best way to see if anything works is to try it out. If, when
trying something out you get an error message, copy and paste the
meaningful part of the message into google, where you will more than
likely find that the earliest results either point you to a thread in
this or another similar group, or to aspfaq.com. If you can't make
sense of the answer, or don't get any meaningful results, post a new
topic here.

If it seems to work ok, try it a few times to make sure it always
works. If you get odd results, come back here and show the code you
are using with a description of the issues.

In addition, most of the SQL statements you are likely to run (at this
stage) against SQL server 2005 can be run against Access without
modification and vice versa. And anyway, if your SQL statement causes
an error while trying something out, google that too. Causing errors
to be raised during development and testing don't reduce your life
expectancy or anything. If they did, I'd be long gone from this world.

So, to summarise, if you want to know if the TOP 1 will run against
Access, try it and see.

--
Mike Brind
Jimmy wrote:
no, the confusion was because i had SQL Express at first but then was forced to go with Access. so i didnt know what would still work. it has been pointed out that this code is bad:

<%
Dim oConn, oRS, randNum

Set oConn=Server.Cr eateObject("ADO DB.Connection")
Set oRS=Server.Crea teObject("ADODB .recordset")

oConn.Provider= "Microsoft.Jet. OLEDB.4.0"
oConn.Open Server.MapPath( "temp.mdb")

oRS.Open "SELECT EMAIL_ADDRESS FROM TABLE1", oConn, adOpenStatic, adLockReadOnly
Randomize()
randNum = CInt((oRS.Recor dCount - 1) * Rnd)

Response.Write( "RecordCoun t: " & oRS.RecordCount & "<br><br>")

oRS.Move randNum
Response.Write oRS("EMAIL_ADDR ESS")

oRS.close
oConn.close
Set oConn = nothing
Set oRS = nothing
%>

so i wanted to know if the "TOP 1" method could be done in access, and maybe see an example based on what i have here.

"Aaron Bertrand [SQL Server MVP]" <te*****@dnartr eb.noraawrote in message news:OD******** *****@TK2MSFTNG P06.phx.gbl...
What, this?
>randNum = (CInt((recordco unt-1) * Rnd) + 1)
Again, you need to show us what you are doing with randNum before we can
comment.

But yes, as we've already suggested, there are issues.

My guess is you are going to say

sql = "SELECT EmailAddress FROM Table1 WHERE PK = " & RandNum

And like I already commented, this won't work reliably. Never mind the
unnecessary roundtrip to count the number of rows in the table.

I think you need to stop theorizing code and deal with this when you can
actually test it against a real database and understand the differences and
what we are talking about. Until then it seems you are hellbent on just
doing it your way and ignoring our advice.

A


"Jimmy" <j@j.jwrote in message
news:Od******** ********@TK2MSF TNGP06.phx.gbl. ..
thank you.
im currently testing with an access db. do you see any issues with my
previous random record generating code?
------=_NextPart_000_ 0049_01C6D359.C 5231A80
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
X-Google-AttachSize: 4297

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<META content="MSHTML 6.00.2900.2963" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY>
<DIV><FONT face=Arial size=2></FONT><FONT face=Arial size=2>no, the confusion
was because i had SQL Express at first but then was forced to go with Access. so
i didnt know what would still work. it has been pointed out that this code is
bad:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>
<DIV><FONT face=Arial size=2></FONT><FONT face=Arial color=#0000ff
size=1><STRONG> &lt;%<BR>Dim oConn, oRS, randNum</STRONG></FONT></DIV><FONT
face=Arial color=#0000ff size=1><STRONG>
<DIV><BR>Set oConn=Server.Cr eateObject("ADO DB.Connection") <BR>Set
oRS=Server.Crea teObject("ADODB .recordset")</DIV>
<DIV><BR>oConn. Provider="Micro soft.Jet.OLEDB. 4.0"<BR>oConn.O pen
Server.MapPath( "temp.mdb") </STRONG></FONT></DIV>
<DIV><STRONG><F ONT color=#0000ff size=1></FONT></STRONG>&nbsp;</DIV>
<DIV><FONT face=Arial color=#0000ff size=1><STRONG> oRS.Open "SELECT
EMAIL_ADDRESS FROM TABLE1", oConn, adOpenStatic,
adLockReadOnly< BR>Randomize()< BR>randNum = CInt((oRS.Recor dCount - 1) *
Rnd)</STRONG></FONT></DIV>
<DIV><FONT face=Arial color=#0000ff
size=1><STRONG> <BR>Response.Wr ite("RecordCoun t: " &amp; oRS.RecordCount &amp;
"&lt;br&gt;&lt; br&gt;")</STRONG></FONT></DIV>
<DIV><STRONG><F ONT color=#0000ff size=1></FONT></STRONG>&nbsp;</DIV>
<DIV><FONT face=Arial color=#0000ff size=1><STRONG> oRS.Move
randNum<BR>Resp onse.Write oRS("EMAIL_ADDR ESS")</STRONG></FONT></DIV>
<DIV><STRONG><F ONT color=#0000ff size=1></FONT></STRONG>&nbsp;</DIV>
<DIV><FONT face=Arial color=#0000ff
size=1><STRONG> oRS.close<BR>oC onn.close<BR>Se t oConn = nothing<BR>Set oRS =
nothing<BR>%&gt ;</STRONG></FONT></DIV>
<DIV><STRONG><F ONT color=#0000ff size=1></FONT></STRONG>&nbsp;</DIV>
<DIV>so i wanted to know if the "TOP 1" method could be done in access, and
maybe see an example based on what i have here.</DIV></FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>"Aaron Bertrand [SQL Server MVP]" &lt;</FONT><A
href="mailto:te *****@dnartreb. noraa"><FONT face=Arial
size=2>te*****@ dnartreb.noraa</FONT></A><FONT face=Arial size=2>&gt; wrote in
message </FONT><A href="news:OD** ***********@TK2 MSFTNGP06.phx.g bl"><FONT
face=Arial size=2>news:OD* ************@TK 2MSFTNGP06.phx. gbl</FONT></A><FONT
face=Arial size=2>...</FONT></DIV><FONT face=Arial size=2>&gt; What,
this?<BR>&gt; <BR>&gt;&gt;&gt ; randNum = (CInt((recordco unt-1) * Rnd) +
1)<BR>&gt; <BR>&gt; Again, you need to show us what you are doing with randNum
before we can <BR>&gt; comment.<BR>&gt ; <BR>&gt; But yes, as we've already
suggested, there are issues.<BR>&gt; <BR>&gt; My guess is you are going to
say<BR>&gt; <BR>&gt; sql = "SELECT EmailAddress FROM Table1 WHERE PK = " &amp;
RandNum<BR>&gt; <BR>&gt; And like I already commented, this won't work
reliably.&nbsp; Never mind the <BR>&gt; unnecessary roundtrip to count the
number of rows in the table.<BR>&gt; <BR>&gt; I think you need to stop
theorizing code and deal with this when you can <BR>&gt; actually test it
against a real database and understand the differences and <BR>&gt; what we are
talking about.&nbsp; Until then it seems you are hellbent on just <BR>&gt; doing
it your way and ignoring our advice.<BR>&gt; <BR>&gt; A<BR>&gt; <BR>&gt;
<BR>&gt; <BR>&gt; <BR>&gt; "Jimmy" &lt;</FONT><A href="mailto:j@ j.j"><FONT
face=Arial size=2>j@j.j</FONT></A><FONT face=Arial size=2>&gt; wrote in message
<BR>&gt; </FONT><A href="news:Od** **************@ TK2MSFTNGP06.ph x.gbl"><FONT
face=Arial size=2>news:Od* *************** @TK2MSFTNGP06.p hx.gbl</FONT></A><FONT
face=Arial size=2>...<BR>& gt;&gt; thank you.<BR>&gt;&gt ; im currently testing
with an access db. do you see any issues with my <BR>&gt;&gt; previous random
record generating code?<BR>&gt; <BR>&gt;</FONT></BODY></HTML>

------=_NextPart_000_ 0049_01C6D359.C 5231A80--
Sep 8 '06 #27

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6291
by: Keith Griffiths | last post by:
I'm trying to do a search under a set criteria followed by a selection of random entries meeting this criteria. But I don't seem to be able to achieve this. The idea being to search on say subject and then select a random set of records meeting that subject. Any ideas or thought would be helpful. I'm using Access XP to try this out. TIA
7
6941
by: Bill | last post by:
Hello, I am trying to use a SQL Query to return a random record from an Access 2000 Database. I am using: SELECT TOP 1 Example FROM TABLE ORDER BY Rnd;
4
5168
by: yf | last post by:
A KB article "http://support.microsoft.com/default.aspx?scid=kb;en-us;209599" tells that the maximum number of records that a table may hold if the PRIMARY key data type is set to AUTONUMBER is 4,294,967,295. Suppose the PRIMARY key data type is set to "RANDOM" AutoNumber. Suppose an application (a) successfully INSERTS "X" records, then (b) successfully DELETES "Y" records (X >= Y), then
2
2514
by: sugaray | last post by:
I want to write a school computer billing system, one of the function is to distribute machine id using rand() for each student log on, suppose there's 100 machines, when each person log on, the system will store user's info such as name, student id number, log on time, log out time into a database file, when the next student log on, the function loads the database, and compare the random generated machine id with the existing ids store...
21
3813
by: Gary Bond | last post by:
Hi All, I am a bit stuck with a project: Specifically, when making a database like engine in 'the old days', I would have wrapped a record class with a stream class, so I could have a file of records on disc, such that I could always jump straight to the record number I wanted. Simple random file access. Maybe they were fixed length records and I knew the n'th record was (n*length of record) into the file. I could therefore jump...
48
4273
by: Jimmy | last post by:
thanks to everyone that helped, unfortunately the code samples people gave me don't work. here is what i have so far: <% Dim oConn, oRS, randNum Randomize() randNum = (CInt(1000 * Rnd) + 1) * -1 Set oConn=Server.CreateObject("ADODB.Connection") Set oRS=Server.CreateObject("ADODB.recordset") oConn.Provider="Microsoft.Jet.OLEDB.4.0" oConn.Open Server.MapPath("temp.mdb")
3
3885
by: John Fairhurst | last post by:
Hi, The following code should select the specified number of records randomly from the database <% .... query = "SELECT FROM " Set RS = Server.CreateObject("ADODB.Recordset")
15
2732
by: caca | last post by:
Hello, This is a question for the best method (in terms of performance only) to choose a random element from a list among those that satisfy a certain property. This is the setting: I need to pick from a list a random element that satisfies a given property. All or none of the elements may have the property. Most of the time, many of the elements will satisfy the property, and the property is a bit expensive to evaluate. Chance of...
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.