I am currently writing a Delphi application that runs queries over a DB2 database using ADO.
One of the requirements is that the user should be able to define queries using dates, for example "show me all data from the last 60 days" or "show me all data between November 20th 2009 and January 18th 2010". This wouldn't be an issue, except for two facts:
- Dates are stored in the database using different fields for day, month and year.
- The databases have been in use at several customer sites for a number of years and cannot be changed, and the application therefore has to run over the existing databases (so no changing the database to store dates in one field, which would make the task much simpler).
What I need to know is whether there is an efficient algorithm for constructing the SQL required to extract the specified information from the database. For example, today is January 18th, so to extract all information from November 20th to today, I would need an SQL statement that goes something like this:
SELECT data WHERE
((day >= 20) AND (month = 11) AND (year = 2009)) OR
((month = 12) AND (year = 2009)) OR
((day <= 18) AND (month = 1) AND (year = 2010))
Obviously this is a trivial and relatively straightforward example, but if the user wanted to retrieve data from November 2008 instead of 2009, the query would get a lot bigger.
Is this the only way that I can construct the SQL statement, or is there a more efficient way to do this?