As described in the title this is a dynamic sql script that will populate a temp table with the day dates of the current month as outputted below:
To create a temporary calendar table for a greater period of time than just the current month:
Set @startDate to any historical date and @numberOfLoops to any number you like (365 being a year from the @startdate).
To make the table persistent:
Remove the # signs from the #calendarTable temp table referenced and rename the table accordingly.
You could also remove any columns you do not need.
IF OBJECT_ID('tempdb..#calendarTable') IS NOT NULL DROP TABLE #calendarTable; GO CREATE TABLE #calendarTable ( "DayID" INT ,"DayOfMonth" INT ,"DayOfQuarter" INT ,"DayOfYear" INT ,"MonthOfDate" INT ,"YearOfDate" INT ,"DayDate" DATE ,PRIMARY KEY (DayID) ) DECLARE @startDate AS DATE DECLARE @baseDate DATE ,@offSet INT ,@numberOfLoops INT /* To create a temporary calendar table: Set @startDate to any historical date and @numberOfLoops to any number you like (365 being a year from the @startdate) To make the table persistent remove the # signs from the #calendarTable temp table referenced */ SET @startDate = GETUTCDATE() /*'20150101'*/ SET @baseDate = DATEADD(MONTH, DATEDIFF(MONTH, 0, @startDate), 0) SET @offSet = 0 SET @numberOfLoops = DATEDIFF(DAY, @baseDate, DATEADD(MONTH, 1, @baseDate)) /*365*/ WHILE (@offSet < @numberOfLoops) BEGIN INSERT INTO #calendarTable ( "DayID" ,"DayOfMonth" ,"DayOfQuarter" ,"DayOfYear" ,"MonthOfDate" ,"YearOfDate" ,"DayDate" ) SELECT (@offSet + 1) ,DATEPART(DAY, DATEADD(DAY, @offSet, @baseDate)) ,DATEDIFF(D, DATEADD(QQ, DATEDIFF(QQ, 0, DATEADD(DAY, @offSet, @baseDate)), 0), DATEADD(DAY, @offSet, @baseDate)) + 1 ,DATEPART(DAYOFYEAR, DATEADD(DAY, @offSet, @baseDate)) ,DATEPART(MONTH, DATEADD(DAY, @offSet, @baseDate)) ,DATEPART(YEAR, DATEADD(DAY, @offSet, @baseDate)) ,DATEADD(DAY, @offSet, @baseDate) SET @offSet = @offSet + 1 END SELECT * FROM #calendarTable