随机取出数据库n条记录

来源:互联网 发布:淘宝直播申请 编辑:程序博客网 时间:2024/05/01 02:10

ID不连续也可以用,本例取五条记录
<%
'字符串随机排列函数
Function RandomStr(str)
    dim Ar,chkstr,ID1,ID2,i,Max,temp,U
    Ar=split(str,",")
   chkstr=""
   i=0
   ID1=1
   U=UBound(AR)
   Max=(U+1)/2
   For i= 1 to Max
         randomize
       ID1=CLNG(Rnd()*U)
       randomize
       ID2=CLNG(Rnd()*U)
       temp=Ar(ID1)
       Ar(ID1)=Ar(ID2)
       Ar(ID2)=Temp
   Next
  For i=0 to Ubound(AR)
      RandomStr=RandomStr&Ar(i)&","
   Next
  RandomStr=Left(RandomStr,Len(RandomStr)-1)
End Function

 set rs = server.CreateObject("adodb.recordset")
 strSQL="select id from table"
  rs.Open strSQL,Cn, 1,1,1
 if rs.recordcount<5 then'记当录大于5才显示随机的数据,可不要的。防止数据库没有大于5条数据时,数组越界
   response.Write"<font size=5pt><b>记录小于5条</b></font>"
 else
   lngRnd=""
  commod=""
   while not rs.eof
           lngRnd=lngRnd&commod&rs("id")
           commod=","
           rs.movenext
   wend
   rs.close()
  set rs=nothing
     lngRnd=RandomStr(lngRnd)'随机排列字符串
   arrayA=split(lngRnd,",")
    '取得第五个逗号的位置
   position=len(arrayA(0))+1+len(arrayA(1))+1+len(arrayA(2))+1+len(arrayA(3))+1+len(arrayA(4)
RndID=mid(lngRnd,1,position)'取前五个id
   %>
<table width="100%" border="0" cellspacing="0" cellpadding="2">
<%
Set rs = Server.CreateObject("ADODB.Recordset")
abc="select top 5 * from table where id in ("&RndID&")"
rs.open abc,Cn,1,1
do while not rs.eof
%>
 <tr>
    <td width="96%"><%=rs("title")%></td>
  </tr>
<%
   rs.movenext
   loop
   rs.close
   set rs=nothing
   Cn.close
   set Cn=nothing
%>
</table>
<%end if%>