CREATE DEFINER = 'root'@'localhost' PROCEDURE `proc_ym`(IN sdate DATE, IN edate DATE) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '' begin #1.变量声明 declare sourcedate date; #开始时间 declare targetdate date; #结束时间 declare indexdate date; #当前时间,充当临时变量 declare index_month int; #循环体内的当前索引时间的月 declare index_year int; #循环体内的当前索引时间的年 declare step_year_month char(20); #2.创建临时表 #2.1创建一个存储时间日历的临时表 drop table if exists tmp_ym_tb; #如果存在临时表,先删除临时表 create temporary table tmp_ym_tb( #创建临时表,字段 rowid,ym rowid bigint auto_increment primary key, #临时表主键 ym varchar(10) #年月 ); #3.初始化变量 set sourcedate = sdate; #初始化开始日期 set targetdate = edate; #初始化结束日期 set indexdate = sourcedate; #当前索引从初始化日期开 set index_month = month(indexdate); #初始化当前索引的月份,后面会随着循环发生变化 set index_year = year(indexdate); #初始化当前索引的年份,后面会随着循环发生变化 /* select date_format(indexdate,"%Y-%m") as ym; 返回 2009-02 select date_format(indexdate,"%y-%m") as ym; 返回 09-02 */ #4.循环将某个时间段内的年月添加到前面创建的临时表 while indexdate <= targetdate do #如果当前索引时间小于等于结束时间,就将年和月记录到临时表去 begin set index_month = month(indexdate); set step_year_month = concat(cast(index_year as char) ,'-',cast(index_month as char),'-01'); insert tmp_ym_tb(ym) values(step_year_month); #将年月插入到临时表 if(index_month=12) then set index_year = index_year + 1; set index_month = 0; #重新从0开始 end if; set step_year_month = concat(cast(index_year as char) ,'-',cast((index_month+1) as char),'-01'); set indexdate = date(step_year_month); end; end while; end |
|
来自: 昵称21365845 > 《MySQL篇》