Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Old Forums
 CLOSED - General SQL Server
 random record selection

Author  Topic 

berndh
Starting Member

6 Posts

Posted - 2006-01-19 : 17:41:48
Hi,

Have a problem here. I'm trying to retrieve 5 record that have a "1" in filrd "active". These record should be really random.

I created a script, but it does not really seem to work. It does return me 5 records, but they are not random, rather sequential, and it ignores the "1".

Your help pleaase.

here is
-----

SQL = "SELECT TOP 5 * " & _
"FROM books " & _
"WHERE " & _
"active =1"
CountSQL = "SELECT COUNT(*) FROM (" & "SELECT TOP 5 * " & _
"FROM books " & _
"WHERE " & _
"active =1" & ") cnt"
Order = "RAND((DATEPART(s,GETDATE())*book_id))"

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2006-01-19 : 17:57:13
When posting your queries here, please post them so that we can try them out in Query Analyzer. Your current format means we'd have to do a lot of work just to read it. Here's how to return a random row:

SELECT TOP 5 *
FROM YourTable
WHERE active = 1
ORDER BY NEWID()

Tara Kizer
aka tduggan
Go to Top of Page

berndh
Starting Member

6 Posts

Posted - 2006-01-20 : 14:09:29
Hi Tara,

Works like a dream !! Thanks.

Could you explain the logic behind this ?

I would have thought it to always return the "top 5" most records. How does it randomise things ?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2006-01-20 : 14:19:40
The ORDER BY NEWID() is the key.

http://www.sqlteam.com/item.asp?ItemID=8747

Tara Kizer
aka tduggan
Go to Top of Page
   

- Advertisement -