Sunday, February 19, 2012

Best way to return records in a date range using where clause?

Say I want to return only records with dates that fall within the next 6 months. Is there some straight-forward, simple way of doing so?

As of now, I'm explicitly giving it a date 6 months in the future, but I'd like to replace it with some sort of function.

SELECT DateField1
WHERE (DateField1 < CONVERT(DATETIME, '2008-06-03 00:00:00', 102))

Any help is greatly appreciated... btw I'm using SQL 2005.

You can use the BETWEEN syntax and also make use of the function GETDATE (returns the current date) and DATEADD (that ... adds days/months/years/time to a date experssion)
SELECT *FROM YourTableWHERE DateFieldBETWEENGETDATE()ANDDATEADD(m, 6,GETDATE())

No comments:

Post a Comment