ASP:隨機訪問Recordset的一條記錄

來源:互聯網
上載者:User

   假設這個資料表有一個唯一的ID欄位,並至少有一條記錄。隨機存取其中一條記錄的方法是非常簡單的,可以分為四步:

  1、取得記錄總數n。

  2、把所有的ID號儲存到一個數組中

  3、產生一個不大於n的隨機數m

  4、從數組中取出第m個ID號,查詢資料表,取得記錄資料。

  下面是部分代碼:

  $#@60;%

  set conn = Server.CreateObject(‘ADODB.Connection‘)

  conn.open ‘$#@60;conn string$#@62;‘

  ‘ ***** (step 1) *****

  set rs = conn.execute(‘Select count(id) from someTable‘)

  rCount = rs(0)

  ‘ ***** (step 2) *****

  set rs = conn.execute(“select id from someTable”)

  cnt = 1

  dim RRs

  redim RRs(rCount)

  do while not rs.eof

  RRs(cnt) = rs(0)

  cnt = cnt + 1

  rs.movenext

  loop

  ‘ ***** (step 3) *****

  randomize

  currentRR = cLng(rnd*rCount+0.5)

  ID = RRs(currentRR)

  ‘ ***** (step 4) *****

  sql = “select otherfield from someTable where id=” & ID

  set rs = conn.execute(sql)

  response.write “ID # ” & ID & “ = ” & rs(0)

  rs.close: set rs = nothing

  conn.close: set conn = nothing

  %$#@62;

  對於SQL Server,還有更加有效率的方法。比如設計兩個預存程序。我這裡只是闡明一些思路,並希望這種思路可以同時用在Access和SQL Server中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.