Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)归海一刀published in(发表于) 2014/2/3 6:34:09 MS SQL Server和Access分别取得随机记录(随机抽题)之完美篇_[SQL Server教程]
这是博主用在一个项目上的源码片断,无论是速度、均衡性,还是随机度都非常好,当然这更不可能抽到重复记录了。
一、在MS SQL Server 2000中生成随机记录的最好办法:
with tk_query do
begin
Close;
sql.clear;
sql.Add('select top '+inttostr(st_count)+' tk.ID,标准答案 from 题库表 tk');
sql.Add('where pid is null and tk.题型='+quotedstr(tx)+' and tk.知识点='+quotedstr(zsd));
sql.add('and tk.难易度='+quotedstr(nyd)+' and tk.课程号='+quotedstr(kcdm)+' order by newid()');
Open;
end;
注:关键就是 order by newid() 这条语句!随机因子就是从这里产生的。
二、数据库为Access 2000时生成随机记录的最好办法:
由于Access中没有newid()这一随机函数,故要想在Access中直接由SQL语句生成我们所希望的随机记录不太可能,因此我们只好在开发语言中生成合适SQL语句,让Access执行了(博主的开发工具为Delphi)。
//获取题库表中的随机ID,组成一个字符串,类似这样 (3,8,2,25,49,1,7,10,6,83....)
//kcdm:课程代码,tx:题型,zsd:知识点,nyd:难易度,t_count:某一题型某一知识点某一难度下的要抽取的题量
function TTest_Srv_RDataForm.Get_Random_ID(const kcdm,tx,zsd,nyd,t_count:string):string;
var
sl: TStrings;
i,ii,kk: integer;
try
Result := '';
sl := TStringList.Create;
with TADOQuery.Create(nil) do
Connection := Adoconnection1;
SQL.Text := ' select ID from 题库表 where pid is null and 题型='+quotedstr(tx)+
' and 知识点='+quotedstr(zsd)+' and 难易度='+quotedstr(nyd)+
' and 课程号='+quotedstr(Kcdm);
while not Eof do
sl.Add(Fields[0].AsString);
Next;
finally
Free;
end; //end with ....
if sl.Count=0 then
Exit;
for i := 0 to StrToIntDef(t_count,0)-1 do
kk := sl.Count;//随机因子
Randomize;
ii := Random(kk); //取得随机数
if Result='' then
Result := sl.Strings[ii]
else
Result := Result+','+sl.Strings[ii];
sl.Delete(ii); //为了避免有可能出现的重复,此ID被抽取过后把它删了
if sl.Count=0 then //如果无题可抽了退出循环
Break;
Result := '('+Result+')'; //给结果串前后加上(......),最终形成(24,36,5,89,72,3,6,1....)的串样
sl.Free;
//=============================================== 课程号,题型,知识点,难易度,题量
function TTest_Srv_RDataForm.Get_Random_Sql(const kcdm,tx,zsd,nyd,t_count:string):string;
Result := Get_Random_ID(kcdm,tx,zsd,nyd,t_count);
if Result <> '' then
Result := ' select top '+t_count+' tk.ID,标准答案 from 题库表 tk where id in '+Result
Result := ' select top '+t_count+' tk.ID,标准答案 from 题库表 tk where 1=1 ';
//以下为调用上述函数生成随机抽题的代码片断
.......
sql.Clear;
sql.Text := Get_Random_Sql(Kcdm,tx_str,zsd_str,nyd_str,txzsd_count_str);
来源:网络
赞