尊重作者,原文链接:https://blog.csdn.net/liminghui4321/article/details/102763052

原始数据表:

需要将上面的时间段转成每一天的记录:

 在原文的基础上作了一些更改:

1、在表sales上增加一个字段bj:alter table sales add column bj int DEFAULT 0 null;
2、存储过程基础上增加了一些更改:

drop PROCEDURE if EXISTS p4;
create procedure p4()
begin
declare id1,gt,it,bjj int;
declare brand varchar(15);
declare sdate,edate,mdate date;
declare flag int default 0;
— 声明游标
declare cur cursor for select *,datediff(enddate,startdate) from sales where bj =0;
declare continue handler for not found set flag = 1;
— select *,datediff(enddate,startdate) from sales where bj=0;

— 打开游标
open cur;
— 获取结果
l2:loop

  fetch cur into id1,brand,sdate,edate,bjj,gt;
  if flag=1 then — 当无法fetch会触发handler continue
     select ‘flag=1 not found’;
     leave l2;
  end if;
  — 逻辑处理,拆解跨天
  IF(gt>=0) THEN
    set it=0;
    select id1,brand,sdate,edate,bjj,gt;
    while it<=gt DO
        insert into sales2(id,brand,tdate) values(id1, brand,date_add(sdate,interval it day));
        set it=it+1;
    end while;
    update sales set bj=1 where id = id1;
  end if;
  — 关闭游标
end loop;
close cur;
end;

call p4();

—-

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。