Skip to content

Instantly share code, notes, and snippets.

@HeLiBloks
Forked from rudiv/generate_date.sql
Created January 11, 2016 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HeLiBloks/3d880856c02da1143ec0 to your computer and use it in GitHub Desktop.
Save HeLiBloks/3d880856c02da1143ec0 to your computer and use it in GitHub Desktop.
Generate Date Table SQL Server
-- 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