分享

更新MYSQL生成日历表,支持跨年份 存储过程

 昵称21365845 2015-09-28
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=12then
                 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+1as char),'-01');
             set indexdate = date(step_year_month);
        end;
   end while;
end

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多