Solved

ASP.NET  4 random rows from a query

Posted on 2004-03-23
13
966 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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
 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Button function on table is in trouble 3 39
JQuery Autocomplete Tag AJAX (Need nice script) 11 72
2012 SQL to JSON Select 5 42
JQuery Data Table Default Sort 2 28
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…
I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

738 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