mysql中生成時間維度的存儲過程(存儲過程示例)

本文主要記錄在BI和數據分析過程當中碰到的生成時間維度的問題,另外也是一個mysql的存儲過程基礎示例
包含:存儲過程基本語法、變量定義、while循環、異常處理html

如下存儲過程生成了以當前日期爲基準先後3650天的日期記錄
sql以下:mysql

建立表:

CREATE TABLE `dim_date` (
  `id` int(8) NOT NULL DEFAULT '0',
  `key` date NOT NULL DEFAULT '0000-00-00',
  `year` int(4) NOT NULL,
  `quarter` int(1) NOT NULL,
  `month` int(2) NOT NULL,
  `week` int(1) NOT NULL COMMENT '星期',
  `weekofyear` int(2) NOT NULL COMMENT '一年中的第幾周',
  `day` int(2) NOT NULL COMMENT '日',
  `dayofyear` int(3) NOT NULL COMMENT '一年總的第幾天',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

存儲過程:

delimiter //
DROP PROCEDURE IF EXISTS getAllDate; 
CREATE PROCEDURE getAllDate()
BEGIN
    DECLARE count int default 0;
    DECLARE startDay DATE DEFAULT date(now());
    DECLARE endDay DATE DEFAULT DATE(NOW());
    -- 定義異常處理方式  http://www.cnblogs.com/cookiehu/p/4994278.html
    DECLARE out_status VARCHAR(200) DEFAULT 'OK';
    DECLARE CONTINUE HANDLER  
    FOR 1062
    SET out_status='Duplicate Entry';
    -- 異常處理方式完畢
    WHILE count<3650 DO
            INSERT INTO `dim_date`(`id`, `key`, `year`, `quarter`, `month`, `week`, `weekofyear`, `day`, `dayofyear`) VALUES (cast(DATE_FORMAT(startDay,'%Y%m%d') as UNSIGNED), startDay, YEAR(startDay), QUARTER(startDay), MONTH(startDay), WEEKDAY(startDay)+1, week(startDay,1), DAY(startDay), DAYOFYEAR(startDay));
            set count = count +1;
            set startDay = DATE_ADD(DATE(now()),INTERVAL count DAY);
            SET endDay = DATE_SUB(DATE(NOW()),INTERVAL count DAY);
            INSERT INTO `dim_date`(`id`, `key`, `year`, `quarter`, `month`, `week`, `weekofyear`, `day`, `dayofyear`) VALUES (cast(DATE_FORMAT(endDay,'%Y%m%d') as UNSIGNED), endDay, YEAR(endDay), QUARTER(endDay), MONTH(endDay), WEEKDAY(endDay)+1, week(endDay,1), DAY(endDay), DAYOFYEAR(endDay));
    END WHILE;
END//
delimiter ;

調用存儲過程

-- TRUNCATE table dim_date;
call getAllDate();
相關文章
相關標籤/搜索