您可以使用存储过程来做到这一点:
DELIMITER $$
CREATE PROCEDURE createDatesTable()
BEGIN
DECLARE FullDate date;
DROP TABLE IF EXISTS dates;
CREATE TABLE dates(
date_key date NOT NULL,
calendarYear int NOT NULL,
calendarQuarter tinyint NOT NULL,
calendarMonthNo int NOT NULL,
calendarWeekNo tinyint NOT NULL,
dayNumberOfMonth tinyint NOT NULL,
dayNumberOfWeek tinyint NOT NULL,
PRIMARY KEY (date_key));
SET FullDate = '2012-01-01';
WHILE (FullDate <= '2012-12-31') DO
BEGIN
INSERT INTO dates(
date_key,
calendarYear,
calendarQuarter,
calendarMonthNo,
calendarWeekNo,
dayNumberOfMonth,
dayNumberOfWeek
)VALUES(
FullDate,
YEAR(FullDate),
QUARTER(FullDate),
MONTH(FullDate),
WEEK(FullDate, 1), /*Have a look at the WEEK() function in the manual!!!*/
DAYOFMONTH(FullDate),
DAYOFWEEK(FullDate)
);
SET FullDate = DATE_ADD(Fulldate, INTERVAL 1 DAY);
END;
END WHILE;
END ;
$$
DELIMITER ;
然后做一个call createDatesTable()
你的桌子就会被填满。
重要提示:ypercube 的评论是正确的。你必须考虑到这一点。因此,请查看WEEK() 函数及其支持的模式。相应地调整程序。