MYSQL

mysql实现创建动态表的存储过程

作者:本站 2017-08-08 浏览:1159 标签: mysql    存储过程    

  设计需求。需要对后台数据定期做数据归档任务,把一张表的是数据在每天半夜将前n(可配置)天的数据进行归档,至于归档到哪一张表需要根据当天属于哪一个月来确定表的名字.  drop procedure if exists dataFile; 

  设计需求。需要对后台数据定期做数据归档任务,把一张表的是数据在每天半夜将前n(可配置)天的数据进行归档,至于归档到哪一张表需要根据当天属于哪一个月来确定表的名字.

  drop procedure if exists dataFile;

  create procedure dataFile()

  BEGIN

  declare tableName varchar(100);

  declare total int default 0 ;

  declare intervalDay int default 7;

  select pmt_val into intervalDay from postmail.dim_sys_pmt where pmt_name='DATA_FILE_INTERVAL' ;

  set tableName=concat('dim_mailsendback_', year(now()),month(now()));

  set @sql1=concat("select count(*) into @total from information_schema.tables where table_name ='",tableName,"' ");

  set @sql2=concat('insert into postmail_back. ', tableName, ' select * from postmail.dim_mailsendback where (dayofyear(now())-dayofyear(sendtime)<=',intervalDay,')');

  set @sql3=concat('create table postmail_back. ', tableName, ' select * from postmail.dim_mailsendback where (dayofyear(now())-dayofyear(sendtime)<=',intervalDay,')');

  prepare stmt1 from @sql1;

  execute stmt1;

  deallocate prepare stmt1;

  set total=@total;

  if total=0 then

  prepare stmt3 from @sql3;

  execute stmt3;

  deallocate prepare stmt3;

  end if;

  if total=1 then

  prepare stmt2 from @sql2;

  execute stmt2;

  deallocate prepare stmt2;

  end if;

  END


  • 0

  • 0

  • 1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.如有文章有版权争议,请给我们留言或者邮件告知我们,邮箱地址:028mw@126.com。