Peter Larsson Blog

Patron Saint of Lost Yaks

Sweet and simple "first and last" weekday calculation

DECLARE @Year SMALLINT = 2011,
        @NumberOfYears TINYINT = 3
 
;WITH cteCalendar(FirstOfMonth, LastOfMonth)
AS (
        SELECT  DATEADD(MONTH, 12 * @Year + Number - 22801, 6) AS FirstOfMonth,
                DATEADD(MONTH, 12 * @Year + Number - 22800, -1) AS LastOfMonth
        FROM    master..spt_values
        WHERE   TYPE = 'P'
                AND number BETWEEN 1 AND 12 * @NumberOfYears
)
SELECT  DATEADD(DAY, DATEDIFF(DAY, 6, FirstOfMonth) / 7 * 7, 6) AS FirstSunday,
        DATEADD(DAY, DATEDIFF(DAY, 5, LastOfMonth) / 7 * 7, 5) AS LastSaturday
FROM    cteCalendar