Created
December 13, 2011 12:06
-
-
Save rudiv/1471903 to your computer and use it in GitHub Desktop.
Generate Date Table SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This will insert X years worth of data into a Date table. All fields are INT apart from DayName and DateTime (NVARCHAR(10) and DATE respectively) | |
-- Update 19/12 now uses ISO Week Number | |
-- Define start (base) and end dates | |
DECLARE @basedate DATETIME = '20111101', @enddate DATETIME = '20150101'; | |
DECLARE @days INT = 0, @date DATETIME = '20110101', @maxdays INT = DATEDIFF(dd, @basedate, @enddate); | |
WHILE @days <= @maxdays | |
BEGIN | |
SET @date = DATEADD(dd, @days, @basedate); | |
SET @days = @days + 1; | |
INSERT INTO [Timesheet].[dbo].[Date] ([Date], [Year], [Month], [Day], [DayName], [WeekDay], | |
[WeekNumber], [YearQuarter], [YearDay]) | |
VALUES (@date, DATEPART(yyyy, @date), DATEPART(mm, @date), DATEPART(dd, @date), DATENAME(dw, @date), | |
DATEPART(dw, @date), DATEPART(isoww, @date), DATEPART(qq, @date), DATEPART(dy, @date)); | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment