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函数进行随机查询的参考语句:de艘早祓胂clare @count intselect @count=COUNT(*) from productselect * ,row_number()over(order by name) as rowidinto #tempfrom productcreate table #temp001(id int,name nvarchar(32),price float,rands float)while 0<@countbegininsert into #temp001(id,name,price,rands)select id,name,price ,rand() from #temp where rowid=@countset @count=@count-1endselect id,name,price from #temp001 order by randsdrop table #tempdrop table #temp001