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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 how to scramble the order of a select result?

Author  Topic 

idontunderstand
Starting Member

1 Post

Posted - 2006-09-19 : 00:21:59
I've been fooled by sql books on line again.
in the Top-Clause section, they said

INSERT TOP n INTO table columns
SELECT * FROM othertable
ORDER BY someColumns

will insert randomly n rows from the select result in to the table.
Well, this is not the case.

I want to randomly select 3 rows from a ordered select result, what's the easiest way to do that? anyone knows? thanks in advance.

timmy
Master Smack Fu Yak Hacker

1242 Posts

Posted - 2006-09-19 : 00:29:20
You can use the random function (check BOL), but you need a unique numeric value in each row that can be used as a seed.

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-09-19 : 01:26:54
ORDER BY NEWID()

It takes longer time because NEWID() is a costsome operation, but it works.



Peter Larsson
Helsingborg, Sweden
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2006-09-19 : 01:34:10
costsome = CostPlenty
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2006-09-19 : 01:41:59
"I've been fooled by sql books on line again.
in the Top-Clause section, they said

INSERT TOP n INTO table columns
SELECT * FROM othertable
ORDER BY someColumns

will insert randomly n rows from the select result in to the table.
Well, this is not the case.
"

FWIW I can't find that anywhere in BoL ... and the syntax is wrong too, it would need to be:

INSERT INTO table (columns)
SELECT TOP n * FROM othertable
ORDER BY someColumns

and as the other have pointed out you would need to order by something which will randomise the ordering.

Kristen
Go to Top of Page

eyechart
Master Smack Fu Yak Hacker

3575 Posts

Posted - 2006-09-19 : 03:15:23
this question has come up frequently in the last couple of weeks. Is this some kind of test question?



-ec


Go to Top of Page
   

- Advertisement -