Skip to content

Instantly share code, notes, and snippets.

@marciuz
Created April 5, 2016 22:17
Show Gist options
  • Save marciuz/535abffd6b0f177a09cada7dac26cb94 to your computer and use it in GitHub Desktop.
Save marciuz/535abffd6b0f177a09cada7dac26cb94 to your computer and use it in GitHub Desktop.
The script create a calendar table, a useful tool for many databases. It is useful and quicker then create on the fly dates.
--
-- See https://www.brianshowalter.com/blog/calendar_tables
-- With 300 kb of
--
--
-- Create the table
--
CREATE TABLE calendar_table (
dt DATE NOT NULL PRIMARY KEY,
y SMALLINT NULL,
q tinyint NULL,
m tinyint NULL,
d tinyint NULL,
dw tinyint NULL,
monthName VARCHAR(9) NULL,
dayName VARCHAR(9) NULL,
w tinyint NULL,
isWeekday BINARY(1) NULL,
isHoliday BINARY(1) NULL,
holidayDescr VARCHAR(32) NULL,
isPayday BINARY(1) NULL
);
--
-- Create work table ints
CREATE TABLE ints ( i tinyint );
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
--
-- Populate the calendar table until the from 2010 to 2040.
-- SELECT datediff('2040-12-31','2010-01-01'); -> 11322 days
--
INSERT INTO calendar_table (dt)
SELECT DATE('2010-01-01') + INTERVAL a.i*10000 + b.i*1000 + c.i*100 + d.i*10 + e.i DAY
FROM ints a JOIN ints b JOIN ints c JOIN ints d JOIN ints e
WHERE (a.i*10000 + b.i*1000 + c.i*100 + d.i*10 + e.i) <= 11322
ORDER BY 1;
--
-- Add the details
--
UPDATE calendar_table
SET isWeekday = CASE WHEN dayofweek(dt) IN (1,7) THEN 0 ELSE 1 END,
isHoliday = 0,
isPayday = 0,
y = YEAR(dt),
q = quarter(dt),
m = MONTH(dt),
d = dayofmonth(dt),
dw = dayofweek(dt),
monthname = monthname(dt),
dayname = dayname(dt),
w = week(dt),
holidayDescr = '';
--
-- Start to add holidays...
--
-- Delete the ints table
DROP TABLE ints;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment