Solved

ASP.NET  4 random rows from a query

Posted on 2004-03-23
13
930 Views
Last Modified: 2006-11-17
I'm looking for the easiest way to grab 4 random rows from an SQL query.   I guess I need to know how to extract individual rows from the dataset based on row index or something.
0
Comment
Question by:drew22
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 12

Expert Comment

by:dfiala13
ID: 10662593
How many records are you pulling from?  Might be worth doing in SQL and only returning 4 random rows.
0
 

Expert Comment

by:mkanik
ID: 10662646
you can use that code as a reference

<% Option Explicit %>

<!-- #include virtual="/adovbs.inc"--> <%
Dim objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "DRIVER=SQL Server;SERVER=OFFICEDNS;" & _
                           "UID=SSDB;PWD=;DATABASE=SSDB;"
objConn.Open
      
Dim objRS
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open "SELECT * FROM tblItem WHERE ParentID IS NULL", objConn, _
           adOpenStatic, adLockReadOnly

Dim rndMax
rndMax = CInt(objRS.RecordCount)
objRS.MoveFirst
      
Do While Not objRS.EOF
      Response.Write objRS("ID") & "<BR>"
      objRS.MoveNext
LOOP
      
objRS.MoveFirst
      
Dim rndNumber
Randomize Timer
rndNumber = Int(RND * rndMax)
      
objRS.Move rndNumber

Response.Write objRS("ID")


objRS.Close
Set objRS = Nothing
      
objConn.Close
Set objConn = Nothing

%>  

0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10662709
CREATE TABLE #ROWID(
 DummyID int IDENTITY,
 RealID int)

CREATE TABLE #RandomIDs(
 RealID int)

DECLARE @Total int
DECLARE @i int
DECLARE @iRandomID int
INSERT INTO #ROWID (RealID) SELECT MyID FROM MyTable
SELECT @Total = @@ROWCOUNT


SET @i = 1
WHILE (@i <= 4)
BEGIN
  SET @iRandomID = Convert(int, RAND()*@Total)
  INSERT INTO #RandomIDs(RealID) SELECT FROM #ROWID Where DummyID = @iRandomID

END

SELECT m.* FROM MyTable m Inner Join #RandomIDs r on r.RealID = m.myID
0
 
LVL 1

Author Comment

by:drew22
ID: 10662769
I don't know how to select 4 random rows using SQL on Oracle.
0
 
LVL 31

Expert Comment

by:alorentz
ID: 10663385
0
 
LVL 31

Expert Comment

by:alorentz
ID: 10663405
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 31

Expert Comment

by:alorentz
ID: 10663412
0
 
LVL 1

Author Comment

by:drew22
ID: 10663589
sample() doesn't work with multiple tables:
"ORA-30561: SAMPLE option not allowed in statement with multiple table references"


I got a "ORA-00920: invalid relational operator" from this example:
select empno,ename
from ( select * from emp where deptno = 20 order by dbms_random.random)
where rownum <= 3

What about just grabbing 4 random rows from an ASP.NET dataset?
0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10664107
Just means you have to move more data across the wire than you need, but still doable.

This assumes rows you want are in table 0 of the dataset...

DataTable dt =  ds.Tables[0];
int iTotal =dt.Rows.Count;
int iRandom = 0;
DataTable dtRandom = dt.Clone();
DataRow dr = null;
for(int i = 0; i < 4; i++){
   iRandom = (new Random().Next(iTotal));
  dr = dt.Rows[iRandom];
  dtRandom.Rows.Add(dr.ItemArray);

}
dg.DataSource = dtRandom;
0
 
LVL 1

Author Comment

by:drew22
ID: 10670513
dfiala13,

Is there a possibility that with small datasets you get duplicate random rows?  If the dataset contains 20 rows and you're grabbing 4 randoms,  could you get dupes?
0
 
LVL 12

Accepted Solution

by:
dfiala13 earned 500 total points
ID: 10670843
Sure,
You could, even in a large dataset.  You can solve this by adding a hashtable and adding an extra step:

DataTable dt =  ds.Tables[0];
int iTotal =dt.Rows.Count;
Hashtable ht = new Hashtable();
int iRandom = 0;
DataTable dtRandom = dt.Clone();
DataRow dr = null;
while(ht.Count < 4){
   iRandom = (new Random().Next(iTotal));
   if(!ht.ContainsValue(iRandom))
     ht.Add(i, iRandom);

}
for(int i = 0; i < ht.Count; i++){
  dr = dt.Rows[(int)ht[i]];
  dtRandom.Rows.Add(dr.ItemArray);
}
dg.DataSource = dtRandom;
0
 
LVL 1

Author Comment

by:drew22
ID: 10671501
dfiala,


this part was missing the i var incrementer for ht.Add(), but I added it and it worked.

while(ht.Count < 4){
   iRandom = (new Random().Next(iTotal));
   if(!ht.ContainsValue(iRandom))
     ht.Add(i, iRandom);

}





0
 
LVL 12

Expert Comment

by:dfiala13
ID: 10671552
oops.  sorry, should no better than to write code in these boxes.  Glad you got it to work.

If you start needing to pull from more than a few hundred records it would definitely be worth the time to figure out how to make Oracle do the dirty work for you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Leverage browser caching 2 55
Update Stored Procedure question 8 48
Query not working correctly? (or how i want it to... 6 48
Issues with Insert statement 12 6
I recently decide that I needed a way to make my pages scream on the net.   While searching around how I can accomplish this I stumbled across a great article that stated "minimize the server requests." I got to thinking, hey, I use more than one…
This demonstration started out as a follow up to some recently posted questions on the subject of logging in: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28634665.html and http://www.experts-exchange.com/Programming/…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now