标题: MS SQL Server和Access分别取得随机记录(随机抽题)之完美篇
ljjk5
元帅
Rank: 1


荣誉会员奖章
UID 46706
精华 1
积分 99426
帖子 49690
威望 554
金币 48489
热心 505
阅读权限 100
注册 2007-2-25
状态 离线
MS SQL Server和Access分别取得随机记录(随机抽题)之完美篇

这是博主用在一个项目上的源码片断,无论是速度、均衡性,还是随机度都非常好,当然这更不可能抽到重复记录了。一、在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;
begin
  try
    Result := '';
    sl := TStringList.Create;
    with TADOQuery.Create(nil) do
    begin
      try
        Connection := Adoconnection1;
        SQL.Text := ' select ID from 题库表 where pid is null and 题型='+quotedstr(tx)+
                    ' and 知识点='+quotedstr(zsd)+' and 难易度='+quotedstr(nyd)+
                    ' and 课程号='+quotedstr(Kcdm);
        Open;
        while not Eof do
        begin
          sl.Add(Fields[0].AsString);
          Next;
        end;
        Close;
      finally
        Free;
      end;
    end; //end with ....
    if sl.Count=0 then
       Exit;
    for i := 0 to StrToIntDef(t_count,0)-1 do
    begin
      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;
    end;
    Result := '('+Result+')'; //给结果串前后加上(......),最终形成(24,36,5,89,72,3,6,1....)的串样
  finally
    sl.Free;

end;
end;
//=============================================== 课程号,题型,知识点,难易度,题量
function TTest_Srv_RDataForm.Get_Random_Sql(const kcdm,tx,zsd,nyd,t_count:string):string;
begin
  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
  else
     Result := ' select top '+t_count+' tk.ID,标准答案 from 题库表 tk where 1=1 ';
end;
  //以下为调用上述函数生成随机抽题的代码片断
  .......
  with tk_query do
  begin
    Close;
    sql.Clear;
    sql.Text := Get_Random_Sql(Kcdm,tx_str,zsd_str,nyd_str,txzsd_count_str);
    Open;

end;

网友 ljjk5 签名 - 网友社区 ===
顶部
[广告] 免费域名(Free Subdomain) 免费空间(Free hosting) PR查询(Google Pagerank)



当前时区 GMT+8, 现在时间是 2008-10-12 12:18
信产部ICP备案:京ICP备05066424号 北京市公安局网监备案:1101050648号

Powered by Discuz! 5.5.0
清除 Cookies - 联系我们 - 网友俱乐部 - Archiver - WAP