I need to make a date table to use for a search criteria for a query. I'm basically trying to make a table that gets the last Sunday of the previous year, to the last Saturday of the current year. I also need to combine the rows.
Example:
"1", "12/27/2015", "1/2/2016"
"2", "1/3/2016", "1/10/2016"
...
Here is my current code that is getting all Saturdays and Sundays of the current year. Can anyone suggest an easy approach to this?
DECLARE
@Year AS INT,
@FirstDateOfYear AS DATETIME,
@LastDateOfYear AS DATETIME
SELECT @year = 2016
SELECT @FirstDateOfYear = DATEADD(yyyy, @Year - 1900, 0)
SELECT @LastDateOfYear = DATEADD(yyyy, @Year - 1900 + 1, 0);
WITH cte AS (
SELECT
1 AS DayID,
@FirstDateOfYear AS FromDate,
DATENAME(dw, @FirstDateOfYear) AS Dayname
UNION ALL
SELECT
cte.DayID + 1 AS DayID,
DATEADD(d, 1 ,cte.FromDate),
DATENAME(dw, DATEADD(d, 1 ,cte.FromDate)) AS Dayname
FROM cte
WHERE DATEADD(d,1,cte.FromDate) < @LastDateOfYear
)
SELECT FromDate, Dayname
FROM CTE
WHERE DayName IN ('Saturday', 'Sunday')
OPTION (MaxRecursion 370)