Monday, November 3, 2008

SQL Tip: SQL to Get dates between given range

SQL statement to get the dates in between the given date range. for (e.g) to get the Dates between 1/1/2007 to Today:

DECLARE @MinDate DATETIME
DECLARE @MaxDate DATETIME

SET @MinDate = '2007-01-01'
SET @MaxDate = getdate()
;
With Dates(Date)
AS
(
Select @MinDate Date
UNION ALL
SELECT (Date+1) Date
FROM Dates
WHERE
Date < @MaxDate ) SELECT Date, Datename(Month, Date) Month, Year(Date) Year FROM Dates OPTION(MAXRECURSION 0)

No comments:

Post a Comment