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


    更新MYSQL生成日历表,支持跨年

    代码
    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


  • 相关阅读:
    逆向工程IL指令集
    关于最近电话面试的体会
    推荐阅读《小就是大》(small is the new big)
    [ZZ]google v. microsoft, and the dev:test ratio debate
    我所用到的Google产品
    [ZZ]7 Useful Tools for Web Development Testing
    拼车新模式
    [ZZ]读《移山之道》后有感
    Google财经香港版上线,香港路演
    [ZZ]从Google到“谷歌”
  • 原文地址:https://www.cnblogs.com/upshania/p/1922712.html
Copyright © 2020-2023  润新知