Today a user asked me how to automatically select the prior month’s transactions from the database. The transactions didn’t have dates, but instead had two numeric fields for Period (month) and Year. They were using a formula to convert these two numbers into a date and then using that formula as part of the selection formula. That approach will work but it is usually slow. This is because the database (or the SQL Query) doesn’t know anything about the date formula in the report, so it can’t apply any date criteria before sending back the data. Crystal gets all years and periods and then has to apply the criteria in the report.
A more efficient approach is to start at the other end. Instead of converting the DB fields to match the criteria values, we convert the criteria values to match the the database fields and let the database do the heavy lifting. In this case created three formulas:
// Prior Pd End Date
Maximum (LastFullMonth)
This gives us the last date of the prior month. From there I created two formulas that extract the year and the month from that date:
// Prior Pd Month
Month ({@Prior Pd End Date})
// Prior Pd Year
Year ({@Prior Pd End Date})
Then the selection formula can use these values to filter the DB fields, something like this:
….
and {Trans.Year} = {@Prior Pd Year}
and {Trans.Period} = {@Prior Pd Month}
This should allow the criteria to be passed to the WHERE clause of the SQL, and maybe even hit an index to make short work of finding the correct records.
The principle works the same if you are using a Date Range parameter. You could use formulas to convert the parameter values so they match the database fields. I wrote about this a few years ago in a similar case where the dates were stored as strings.
(For examples of my most popular formulas, please visit the FORMULAS page on my website.)