当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL数据篇(九)--存储过程实现定时每天清理过期数据

MySQL数据篇(九)--存储过程实现定时每天清理过期数据

2019年11月20日  | 移动技术网IT编程  | 我要评论
需求:有一个活动记录表 t_ad ,商家每次发起一个活动,就会在 t_shake_devices_relation 表里面生成一些关联记录。现在写一个存储过程实现,如果活动过期,就将关联表里面的数据标记删除。 1、代码如下: BEGIN /* 用途:每天23:00执行一次,处理“开屏广告”和“门店主 ...

需求:有一个活动记录表 t_ad ,商家每次发起一个活动,就会在 t_shake_devices_relation 表里面生成一些关联记录。现在写一个存储过程实现,如果活动过期,就将关联表里面的数据标记删除。

1、代码如下:

begin
    /*
        用途:每天23:00执行一次,处理“开屏广告”和“门店主页”关联设备信息,如果当前时间活动已过期,及将表下关联记录标记为已删除状态
    */
    
    #定义变量
    declare done int;#游标标记
    declare timestamptmp int;#当前时间戳
    declare ad_id int;#需要清除的广告活动id
    declare ad_ad_type int;#广告类型1
    declare ad_ad_location int;#广告类型2
    declare devices_ad int;#设备关联表需要清除的广告活动id
    declare err int; #是否有sql错误
    
    

    #创建游标,并且存储数据,获取未处理,已结束的广告活动id
    declare cur_ad cursor
                    for
                    select id,ad_type,ad_location from t_ad where is_handle = 0 and end_time < timestamptmp limit 500;
    
    #游标中的内容执行完后将done设置为1
    declare continue handler for not found set done = 1;
    #检查sql是否有错
    declare continue handler for sqlexception set err=1; 

    #赋值当前时间
    set timestamptmp = unix_timestamp();

    #打开游标
    open cur_ad;

    #执行循环
    posloop:loop
            
                #游标结束或者sql错误,结束循环
                if done = 1 or err = 1 then
                        leave    posloop;
                end if;

                #取游标中的值
                fetch    cur_ad into    ad_id,ad_ad_type,ad_ad_location;

                #查询数据,判断是否需要修改
                select    count(1) into    devices_ad from t_shake_devices_relation where    relation_id = ad_id and is_deleted = 0;
                
                #存在即修改
                if devices_ad > 0 then
                        update t_shake_devices_relation set is_deleted = 1 where relation_id = ad_id;
                        
                        #修改成功后标记t_ad表为已处理
                        if row_count() > 0 then
                                update t_ad set is_handle = 1 where id = ad_id;
                        end if;

                end if;
    
    #结束循环
    end    loop posloop;

    #释放游标
    close    cur_ad;
end

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网