Search code examples
sqlms-accessvb6jet

How to convert String like "June 20, 2019" to Date format in order to Selct a date Range


I have a Access table which contains the Strings like the following:

  Date Created                Date Modified
  January 31, 2019            January 31, 2019
  March 08, 2019              March 09, 2019
  April 19, 2019              April 23, 2019

I want to be able to select a Date Range between 2 dates using a sql query.

I am using the Jet4.0 engine and VB6.

Any help is greatly appreciated

I have tried this:

But this does not delete any records.

Set cijb = DBEngine.Workspaces(0).OpenDatabase(PathCIJB())

   DELETE Job.* FROM Job WHERE(Job.DateModified >= 'January 03, 2019' ) AND 
   (Job.DateModified <= 'February 05, 2019' )

  Set rs = cijb.OpenRecordset(sql, dbOpenSnapshot)

I expect to delete all the records Modified for example from March 09, 2019 to April 23, 2019


Solution

  • You comparing strings with strings. And there is no conditions when 'J' comes before 'F', so WHERE is always false.

    Before compare you should do explicit convertation by CDate function:

    CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

    Also to run SQL command query you can not use OpenRecordset:

        Set cijb = DBEngine.Workspaces(0).OpenDatabase(PathCIJB())
    
        cijb.Execute "DELETE Job.* FROM Job " & _ 
                     "WHERE (CDate(Job.DateModified) >= CDate('January 03, 2019')) AND (CDate(Job.DateModified) <= CDate('February 05, 2019'));"