ใน Acces ใช้ SQL อย่างไรให้ดึงข้อมูลแบบสุ่มขึ้นมา 3 record
กระทู้เก่าบอร์ด อ.สุภาพ ไชยา

 242   1
URL.หัวข้อ / URL
ใน Acces ใช้ SQL อย่างไรให้ดึงข้อมูลแบบสุ่มขึ้นมา 3 record

มีคนถามไว้ที่ 
http://pantip.inet.co.th/tech/developer/topic/DD962480.html 
ดังนี้ 
 
ใน Acces ใช้ SQL อย่างไรให้ดึงข้อมูลแบบสุ่มขึ้นมา 3 record  
 
จากคุณ : 3 [5 มิ.ย. 2545 - 05:15:13] 
 
มีคนตอบไว้หลายคำตอบเหมือนกัน 
 
ผมเลยลองมาทำดูโดยใช้โค้ดดังนี้ 
 
Sub Show5Records() 
Dim strSQL As String, strWhere As String 
Dim dbs As Database, qdf As QueryDef 
Set dbs = CurrentDb 
Set qdf = dbs.QueryDefs("Query3") 
strWhere = GetRandomRecords2() 
strSQL = "SELECT information001.*, information001.id " _ 
    & "FROM information001 " _ 
    & "WHERE information001.id In (" & strWhere & ");" 
qdf.SQL = strSQL 
DoCmd.OpenQuery "Query3" 
qdf.Close 
dbs.Close 
Set qdf = Nothing 
Set dbs = Nothing 
End Sub 
 
โดยจะต้องมีฟังก์ชันในการสุ่มเอา ID ของตารางขึ้นมาดังนี้ 
 
Function GetRandomRecords2() As String 
Dim intRec As Integer, I As Integer 
Dim dbs As Database, rst As Recordset 
Set dbs = CurrentDb 
Set rst = dbs.OpenRecordset("information001") 
intRec = rst.RecordCount 
If Not rst.EOF Then 
    For I = 1 To 5 
        rst.MoveFirst 
        rst.Move CInt((intRec - 0 + 1) * Rnd + 0) 
        GetRandomRecords2 = GetRandomRecords2 & "'" & rst(0) & "'," 
    Next I 
End If 
rst.Close 
dbs.Close 
GetRandomRecords2 = Left(GetRandomRecords2, Len(GetRandomRecords2) - 1) 
'Debug.Print GetRandomRecords2 
End Function 
 
ลองดูครับ *** Edited by Supap Chaiya *** 2/18/2004 11:40:48 AM

1 Reply in this Topic. Dispaly 1 pages and you are on page number 1

1 @R06528
   
@ ประกาศใช้งานเว็บบอร์ดใหม่ => บอร์ดเรียนรู้ Access สำหรับคนไทย
แล้วจะใส่ลิ้งอ้างอิงมาที่โพสต์เก่านี้หรือไม่ก็ตามสะดวกครับ
Time: 0.0511s