這是博主用在一個項(xiàng)目上的源碼片斷,無論是速度、均衡性,還是隨機(jī)度都非常好,當(dāng)然這更不可能抽到重復(fù)記錄了。 一、在MS SQL Server 2000中生成隨機(jī)記錄的最好辦法: with tk_query do begin Close; sql.clear; sql.Add('select top '+inttostr(st_count)+' tk.ID,標(biāo)準(zhǔn)答案 from 題庫表 tk'); sql.Add('where pid is null and tk.題型='+quotedstr(tx)+' and tk.知識點(diǎn)='+quotedstr(zsd)); sql.add('and tk.難易度='+quotedstr(nyd)+' and tk.課程號='+quotedstr(kcdm)+' order by newid()'); Open; end; 注:關(guān)鍵就是 order by newid() 這條語句!隨機(jī)因子就是從這里產(chǎn)生的。 二、數(shù)據(jù)庫為Access2000時生成隨機(jī)記錄的最好辦法: 由于Access中沒有newid()這一隨機(jī)函數(shù),故要想在Access中直接由SQL語句生成我們所希望的隨機(jī)記錄不太可能,因此我們只好在開發(fā)語言中生成合適SQL語句,讓Access執(zhí)行了(博主的開發(fā)工具為Delphi)。 //獲取題庫表中的隨機(jī)ID,組成一個字符串,類似這樣 (3,8,2,25,49,1,7,10,6,83....) //kcdm:課程代碼,tx:題型,zsd:知識點(diǎn),nyd:難易度,t_count:某一題型某一知識點(diǎn)某一難度下的要抽取的題量 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 知識點(diǎn)='+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;//隨機(jī)因子 Randomize; ii := Random(kk); //取得隨機(jī)數(shù) if Result='' then Result := sl.Strings[ii] else Result := Result+','+sl.Strings[ii]; sl.Delete(ii); //為了避免有可能出現(xiàn)的重復(fù),此ID被抽取過后把它刪了 if sl.Count=0 then //如果無題可抽了退出循環(huán) Break; end; Result := '('+Result+')'; //給結(jié)果串前后加上(......),最終形成(24,36,5,89,72,3,6,1....)的串樣 finally sl.Free; end; end; //=============================================== 課程號,題型,知識點(diǎn),難易度,題量 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,標(biāo)準(zhǔn)答案 from 題庫表 tk where id in '+Result else Result := ' select top '+t_count+' tk.ID,標(biāo)準(zhǔn)答案 from 題庫表 tk where 1=1 '; end; //以下為調(diào)用上述函數(shù)生成隨機(jī)抽題的代碼片斷 ....... 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; |
免責(zé)聲明:本站部分文章和圖片均來自用戶投稿和網(wǎng)絡(luò)收集,旨在傳播知識,文章和圖片版權(quán)歸原作者及原出處所有,僅供學(xué)習(xí)與參考,請勿用于商業(yè)用途,如果損害了您的權(quán)利,請聯(lián)系我們及時修正或刪除。謝謝!
始終以前瞻性的眼光聚焦站長、創(chuàng)業(yè)、互聯(lián)網(wǎng)等領(lǐng)域,為您提供最新最全的互聯(lián)網(wǎng)資訊,幫助站長轉(zhuǎn)型升級,為互聯(lián)網(wǎng)創(chuàng)業(yè)者提供更加優(yōu)質(zhì)的創(chuàng)業(yè)信息和品牌營銷服務(wù),與站長一起進(jìn)步!讓互聯(lián)網(wǎng)創(chuàng)業(yè)者不再孤獨(dú)!
掃一掃,關(guān)注站長網(wǎng)微信