I have a datetime field in my database(SQL Server) and I need to
retrieve records for between two dates using a filter query in my
visual basic code?
' dates from the user
Dim dateLower as Date
Dim dateUpper as Date
' a sql command and database objects: this is all
' DAO and Jet code. You need to change things for ADO
' or ODBC etc etc.
Dim jetSQL as String
Dim db as DAO.Database
Dim rst as DAO.Recordset
' this one is _not_ regionally-negotiable!!
Const fmtJetDate as String = "\#yyyy\-mm\-dd\#"
' you may have some other method of getting the
' limit dates
dateLower = GetDateFromUser("Start")
dateUpper = GetDateFromUser("Final ending date")
' Create the inline SQL command. Note correct method
' of getting date intervals depends on the values to be
' found. This will FAIL if the SomeDate field any time
' values.
jetSQL = "SELECT ALL Something " & vbNewLine & _
"FROM SomeTable " & vbNewLine & _
"WHERE " & Format(dateLower, fmtJetDate) & "<= SomeDate " & _
" AND SomeDate <= " & Format(dateUpper, fmtJetDate)" & vbNewLine & _
"ORDER BY Something ASC"
' always get to see what a mess you have made of the
' command, until you know it's right
Debug.Assert vbYes=MsgBox(jetSQL, vbYesNo, "Is this OK?")
' now you can pass the thing off to the database
Set db = CurrentDB()
Set rst = db.OpenRecordset(jetSQL, dbOpenSnapshot, dbForwardOnly)
' and do something with the recordset
Do While Not rst.EOF
Debug.Print rst!Something
rst.MoveNext
Loop
' tidy up
rst.Close
Hope that helps
Tim F