Advertisement
jchaven

Create calendar table in T-SQL

Feb 26th, 2014
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.54 KB | None | 0 0
  1. -- taken from: http://blog.jontav.com/post/9380766884/calendar-tables-are-incredibly-useful-in-sql
  2. declare @start_dt as date = '1/1/2000';     -- Date from which the calendar table will be created.
  3. declare @end_dt as date = '1/1/2030';       -- Calendar table will be created up to this date (not including).
  4.  
  5. CREATE TABLE dbo.calendar (
  6.  date_id date primary key,
  7.  date_year smallint,
  8.  date_month tinyint,
  9.  date_day tinyint,
  10.  weekday_id tinyint,
  11.  weekday_name varchar(10),
  12.  month_name varchar(10),
  13.  day_of_year smallint,
  14.  quarter_id tinyint,
  15.  first_day_of_month date,
  16.  last_day_of_month date,
  17.  start_dts datetime,
  18.  end_dts datetime
  19. )
  20.  
  21. while @start_dt < @end_dt
  22. begin
  23.     insert into dbo.calendar(
  24.         date_id, date_year, date_month, date_day,
  25.         weekday_id, weekday_name, month_name, day_of_year, quarter_id,
  26.         first_day_of_month, last_day_of_month,
  27.         start_dts, end_dts
  28.     )  
  29.     values(
  30.         @start_dt, year(@start_dt), month(@start_dt), day(@start_dt),
  31.         datepart(weekday, @start_dt), datename(weekday, @start_dt), datename(month, @start_dt), datepart(dayofyear, @start_dt), datepart(quarter, @start_dt),
  32.         dateadd(day,-(day(@start_dt)-1),@start_dt), dateadd(day,-(day(dateadd(month,1,@start_dt))),dateadd(month,1,@start_dt)),
  33.         cast(@start_dt as datetime), dateadd(second,-1,cast(dateadd(day, 1, @start_dt) as datetime))
  34.     )
  35.     set @start_dt = dateadd(day, 1, @start_dt)
  36. end
  37.  
  38.  
  39. -- sample of the data
  40. select top 50 *
  41. from dbo.calendar
  42. --order by newid()
  43. order by date_id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement