随机访问Recordset的一条记录

2016-01-29 18:28 6 1 收藏

随机访问Recordset的一条记录,随机访问Recordset的一条记录

【 tulaoshi.com - ASP 】

  假设这个数据表有一个唯一的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中。


 

来源:https://www.tulaoshi.com/n/20160129/1505915.html

延伸阅读
我们可以通过下述方法删除重复记录: 例:表名:dbo.品种描述$,字段包括:ID_PK,品种名称,性状标准编号,代码,首先创建一个和原表结构一样的表: 代码如下: select * into tmpA from dbo.品种描述$ where 1=2--创建完毕 在数据表中,品种名称,性状标准编号这两个字段不能有重复值,执行下述脚本: declare @VarietyName nvarchar(255), ...
数据库结构的脚本: if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TempA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[TempA] GO CREATE TABLE [dbo].[TempA] (  [id] [int] IDENTITY (1, 1) NOT NULL ,  [PositionName] [varchar] (256) COLLATE Chinese_PRC_CI_AS NULL , &nbs...
标签: ASP
  很久没用ACCESS了,只是看到经常碰到有人问如何返回随机记录的问题,所以就贴了上来,随便看看。 <!--#include virtual="/adovbs.inc"-- <%     Dim objConn     Dim objRst     Dim strSQL     Dim strConnection   &nbs...
其实表白是一个技术活,对于那些想不出大招的男人来说,可能只会说一句我爱你,但是这远远不能打动男人的心,而古人这些表白大招保准你看完都惊呆了,古人咋这么牛呢?那些表白的潜台词到底是啥呢?下面大家就跟着图老师小编一起来看看吧! 很多人抱怨自己表白失败,被无情地拒绝,被发好人卡其实归根结底还是因为人丑。 So...
标签: PS PS教程
下面是要用到的素材. screen.width-500)this.style.width=screen.width-500;" border=0 pop="按此在新窗口浏览图片"> screen.width-500)this.style.width=screen.width-500;" border=0> screen.width-500)this.style.width=screen.width-500;" border=0> screen.width-500)this.style.width=screen.width-500;" border=0> ...

经验教程

146

收藏

60
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部