2015-08-14 53 views
0

我使用下面提到的代碼從Access數據庫中選擇最近一天未選中的記錄ID,並將其添加到數組中。訪問SQL隨機數發生器不按預期工作

總體目標是,只要記錄從未被選擇或在最近2天內沒有選擇記錄,就會檢索與初始「難度」標準相匹配的記錄。循環完成後,我應該擁有唯一記錄ID的數量並將其添加到數組中以供其他處理。

Private Function RetrieveQuestionID(questionCount As Integer) 

    ' We're using this retrieve the question id's from the database that fit our arrangements. 
    Dim intQuestArray(0 To questionCount) As Integer 
    Dim QuestionConnection As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = |DataDirectory|\Database\MillionaireDB.accdb;") 

    QuestionConnection.Open() 

    For i As Integer = 1 To intNoOfQuestions 
     'TODO: If there are no valid questions, pull up any of them that meets the difficulty requirement.... 

     Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) AND (((Questions.LastDateRevealed) Is Null)) OR (Questions.LastDateRevealed >= DateAdd('d',-2,Date())) ORDER BY Rnd((Questions.QuestionID) * Time());", QuestionConnection) 
     QuestionConnectionQuery.Parameters.AddWithValue("?", intQuestionDifficulty(i - 1).ToString) 
     Dim QuestionDataAdapter As New OleDb.OleDbDataAdapter(QuestionConnectionQuery) 
     Dim QuestionDataSet As New DataSet 

     QuestionDataAdapter.Fill(QuestionDataSet, "Questions") 
     intQuestArray(i - 1) = QuestionDataSet.Tables("Questions").Rows(0).Item(0) 

     Dim QuestionConnectionUpdateQuery As New OleDb.OleDbCommand("UPDATE Questions SET Questions.LastDateRevealed = NOW() WHERE Questions.QuestionID = [?]", QuestionConnection) 
     QuestionConnectionUpdateQuery.Parameters.AddWithValue("?", intQuestArray(i - 1).ToString) 
     QuestionConnectionUpdateQuery.ExecuteNonQuery() 

    Next 

    QuestionConnection.Close() 
    Return intQuestArray 
End Function 

然而,通過數組循環將表明,有以某種方式被重複,即使在循環過程的記錄更新記錄。

是否有另一種方式來循環訪問數據庫並提取這些記錄?我甚至試圖將.Open().Close()語句移到For...Next循環中,我得到的結果比以前糟糕。

+2

_OR在最近2天內沒有選擇該記錄_嚴格審視**> = ** – Steve

回答

1

正如史蒂夫寫道,> =應該是<。

此外,您的WHERE子句缺少OR部分周圍的括號。 它應該是(沒有所有不必要的括號內):

SELECT Questions.QuestionID 
FROM Questions 
WHERE Questions.QuestionDifficulty=[?] 
    AND (Questions.LastDateRevealed Is Null 
    OR Questions.LastDateRevealed < DateAdd('d',-2,Date())) 
    ORDER BY Rnd(Questions.QuestionID * Time()); 

也看看How to get random record from MS Access database - 它建議使用負值作爲參數Rnd()