如何在数据库随机取N条数据

我想到的是先取出所有行集,在rs.next()的时候 随机选取

不知道有没有SQL可以直接随机在数据库里选取N(是定值)条数据,不考虑字段匹配的方法
---------------------------------------------------------------

select top 200 IDENTITY(int,1,1) as rid,* into #jr from yourtable
declare @rindex int
set @rindex= ceiling( rand()*10)
select top 10 * from #jr where rid % @rindex =0
drop table #jr
---------------------------------------------------------------

declare @conut int,@IdStr varchar (8000),@intX int ,@ShoeCount int
select @ShoeCount=20
select @conut=(select count() from Table)
drop table #table1
select IDENTITY(int,1, 1) as iid,

into #table1
from Table
select @intX=0
while @intX<@ShoeCount
Begin
select @IdStr=@IdStr+''''+cast(cast(rand()*@conut as int)as varchar)+''''
select @intX=@intX+1
if @intX<@ShoeCount select @IdStr=@IdStr+','
End

select * from #table1 where Iid in (@IdStr)

---------------------------------------------------------------

你的用法不对:
select * from (
Select top n * from tablename order by newid()
) a order by 某字段
---------------------------------------------------------------

用我的方法引该可以满足你的要求.通过一个TEMPTABLE长生RANDOM()的SEED,在和原来的表关联查询.(这是MS推荐的方法!)给分吧!

use pubs
go
set nocount on
begin tran

select au_id,cast( null as float) as rnd into #RndAuthors
from Authors(TABLOCK SERIALIZABLE)
--SELECT * FROM #RndAuthors
create clustered index idx_ci_au_id on #RndAuthors(au_id)

declare @key as varchar(11)
select @key=min(au_id) from #RndAuthors

/create a loop that iterates through all the key values,and
for each key,invokes the RAND() function with no input,update
the float column with the random value generated.
/

while @key is not null
begin
update #RndAuthors set rnd=rand() where au_id=@key
select @key=min(au_id) from #RndAuthors where au_id>@key
end
--select * from #RndAuthors
set rowcount 10

select a.* from authors as a join #RndAuthors as R
on a.au_id=R.au_id
order by rnd

drop table #RndAuthors
commit tran

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus