create or replace procedure p_clear_expired_data
-- 根据指定的表名和字段名清理过期数据, 可配置为job运行
-- author: zhaohuihua
(
i_tablename in varchar2, -- 表名
i_timefield in varchar2, -- 时间字段名
i_howlong in integer -- 清理多久以前的数据(单位:天)
)
as
fmt constant varchar2(100) := 'yyyy-mm-dd'; -- 日期格式常量
max_loop constant integer := 20; -- 每次最大循环次数
max_count constant integer := 5000; -- 每次最大删除行数
v_sql varchar2(1000);
v_time varchar2(100);
v_loop integer;
v_count integer;
begin
if i_timefield is null or i_tablename is null
or i_howlong is null or i_howlong < 0 then
return;
end if;
-- 计算时间
v_time := to_char(sysdate - i_howlong, fmt);
-- 构造删除数据的sql语句
v_sql := 'delete ' || i_tablename
|| ' where ' || i_timefield
|| ' < to_date(''' || v_time || ''', ''' || fmt || ''')'
|| ' and rownum <= ' || max_count;
for v_loop in 1 .. max_loop loop
execute immediate v_sql; -- 删除数据
v_count := sql%rowcount; -- 影响行数
commit;
if v_count < max_count then
exit; -- 没有数据可删除则退出
end if;
end loop;
exception
when others then
rollback;
end p_clear_expired_data;
清理过期数据的存储过程
最新推荐文章于 2023-12-24 18:01:42 发布