ASP代碼實現(xiàn)access隨機顯示不重復記錄

字號:


    <%
    '-------------------------數(shù)據(jù)庫連接-----------------------
    Set objConn = Server.CreateObject("ADODB.Connection")
    objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" &_
    "Data Source=" & Server.MapPath("data.mdb")
    objConn.Open
    '-------------------------數(shù)據(jù)庫連接-----------------------
    '-------------------------檢索數(shù)據(jù)-----------------------
    strSQL = "SELECT id,DataColumn FROM DataTable"
    'Sql語句,檢索數(shù)據(jù)庫
    Set objRS = Server.CreateObject("ADODB.Recordset")
    '創(chuàng)建記錄集
    objRS.Open strSQL, objConn, 1, 1  
    '執(zhí)行檢索
    Count=objRS.RecordCount    
    '得到記錄總數(shù)
    Item=4                                  
    '顯示記錄數(shù)
    '-------------------------檢索數(shù)據(jù)-----------------------
    '-------------------------------------------------------------------------------
    redim a(Item, 2),t(Count)
    '定義2數(shù)組,數(shù)組a用來儲存記錄,數(shù)組t用來刪選記錄
    '---------------------------------------
    '初始數(shù)組數(shù)值,目的為了插入數(shù)據(jù)以后和此值做比較
    for each j in t
    j=0
    next
    '---------------------------------------
    '---------------------------------------
    ' 隨機抽取記錄號
    Randomize timer  '初始化隨機數(shù)生成器
    for j=1 to Item
    k=int(rnd*Count+1)'從總數(shù)里面隨機取一條記錄
    do while t(k)<>0          '判斷是否記錄是否已經(jīng)在數(shù)組中
    k=int(rnd*Item+1)
    loop
    t(k)=1     '第k條記錄被選中
    next
    '--------------------------------------
    j=1:i=1'定義下標
    '--------------------------------------
    ' 循環(huán)選取數(shù)據(jù)集objRS中的部分記錄存放到數(shù)組中
    Do While Not objRS.Eof
    if t(j)=1 then
    a(i,1)=objRS("id")      '記錄id
    a(i,2)=objRS("DataColumn") '記錄內(nèi)容
    i=i+1
    end if
    j=j+1
    objRS.MoveNext
    Loop
    '--------------------------------------
    '-------------------------------------------------------------------------------
    '----------------------------顯示內(nèi)容--------------------
    for i=1 to Item
    Response.write "序號"&a(i,1)&"<br>"
    Response.write "內(nèi)容"&a(i,2)&"<p>"
    next
    '----------------------------顯示內(nèi)容--------------------
    '---------------------------
    '釋放資源
    objRs.Close
    set objRs=nothing
    objConn.Close
    set objConn=nothing
    '---------------------------
    %>