sqlserver 如何实现数据随机显示
1、使用newid()函数生成随机系统唯一性id
查询分析器输入:select newid()

2、再次在查询分析器中输入
select newid()
select newid()
可以发现生成了两个不同的id了

3、按照newid()排序查询product表
select * from product order by newid()
其结果如下,我们得到了其随机查询的结果

4、如果需要查询固定数量的排序,可以加入top关键字
select top 5 * from product order by newid()
这样就随机查询了5行数据了

5、rand()这个函数也是一个随机函数是否也可以实现随机查询,查询分析器中输入两个同样的查询语句:select * from product order by rand()
如下其结果并没有排序,这是因为newid在查询的每一行都会生成唯一的id,而rand()只计算一次结果

6、要想实现rand的排序,我们需要对每一行进行处理
以下为使用rand函数进行随机查询的参考语句:
declare @count int
select @count=COUNT(*) from product
select * ,row_number()over(order by name) as rowid
into #temp
from product
create table #temp001(id int,name nvarchar(32),price float,rands float)
while 0<@count
begin
insert into #temp001(id,name,price,rands)
select id,name,price ,rand() from #temp where rowid=@count
set @count=@count-1
end
select id,name,price from #temp001 order by rands
drop table #temp
drop table #temp001
