When I have columns that have a time along with the date and I need a query to filter by a day, that usually means that:
If filter date = 1/3/2006 then records with a date of 1/3/2006 should be included regardless of time.
I usually use the following approach:
Get your compare variable to have only a date (strip off the time)
Set the compare variable to one day GREATER than what you want to include
Use a "<" check instead of "<="
For your sample, that means using something like:
Code:
DECLARE @FilterDate datetime
-- Set the @FilterDate to be 29 days in the past, minus any time portion
-- The varchar convert strips off the time while the outside convert puts it back to date/time
-- The outside convert isnt necessary as SQL will convert the varchar into a datetime automatically
SET @FilterDate = CONVERT(datetime, CONVERT(varchar, DATEADD(d, -29, getdate()), 101))
-- Add an extra day so an "inclusive" check will work easier
SET FilterDate = DATEADD(d, 1, @FilterDate)
SELECT ...
FROM ...
WHERE EntryDate < @FilterDate
You could also shortcut that into the following although I prefer to be verbose in the code to make it more readable 6 months later:
Code:
SET @FilterDate = CONVERT(datetime, CONVERT(varchar, DATEADD(d, -29, getdate()), 101))
-- Add an extra day so an "inclusive" check will work easier
SET FilterDate = DATEADD(d, 1, @FilterDate)
SELECT ...
FROM ...
WHERE EntryDate < CONVERT(datetime, CONVERT(varchar, DATEADD(d, -28, @FilterDate), 101))
In the second example I inlined the code and subtracted 28 instead of 29 to save the extra "one more day" check. Here the extra CONVERT back to datetime is necessary - if you dont use it, the SQL analyzer will try to CONVERT the column to a varchar and hurt performance. You can test in query analyzer by using the command "set statistics profile on".
I hate fudging hard-code numbers like 29 for 28 to make the code "leaner". If the business rule says "include records that are 29 days or older" then I want the code to have a "29" somewhere - just makes things easier later on.
-ner