hakimkal
hakimkal

Reputation: 90

VB.NET Access Datetime Querying Issue

I have a bunch of records in an Access db table with a datetime fields

e.g of records (2/2/2015 3:34:21 PM,2/2/2015 8:29:13 AM )

Problem is I need to run a query where I need all records for displayed to be ones that occurred on the same day regardless of the time. How to best structure this query?

I used 'Select * from table where thetime = 2/2/2015' and there was no result returned. I switched the date format to start with the year, no luck.

Any tips as to sql query syntax for Access will be appreciated. Thanks.

Upvotes: 1

Views: 1045

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123409

Date/Time values in Access always have both a date and time component, so a date literal like 2015-02-02 is equivalent to 2015-02-02 00:00:00. If you want all rows for that date, regardless of the time, you need to use a WHERE clause like

... WHERE thetime >= {that date} AND thetime < {the following day}

The proper way to do that in VB.NET is to use a parameterized query like this:

Using cmd As New OleDbCommand()
    cmd.Connection = con  ' an open OleDbConnection
    cmd.CommandText =
            "SELECT * FROM thetable " &
            "WHERE thetime >= ? AND thetime < ?"
    Dim targetDate As New DateTime(2015, 2, 2)  ' example data
    cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate
    cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate.AddDays(1)
    Using rdr As OleDbDataReader = cmd.ExecuteReader
        Do While rdr.Read()
            Console.WriteLine(rdr("thetime"))
        Loop
    End Using
End Using

Upvotes: 1

Related Questions