--創建表
create table t_test
(s_id varchar2(30),
s_name varchar2(30),
dt_insert date
);
--插入測試數據
insert into t_test
(s_id, s_name, dt_insert)
select lpad(to_char(rownum + (select count(*) from t_test)), 10, '0'),
'2018-11-08-1000條',
date '2018-11-08'
from dual
connect by rownum <= 1000
union all
select lpad(to_char(rownum + (select count(*) from t_test)), 10, '0'),
'2018-11-09-1000條',
date '2018-11-09'
from dual
connect by rownum <= 1000
union all
select lpad(to_char(rownum + (select count(*) from t_test)), 10, '0'),
'2018-11-10-1000條',
date '2018-11-10'
from dual
connect by rownum <= 1000
union all
select lpad(to_char(rownum + (select count(*) from t_test)), 10, '0'),
'2018-11-11-1000條',
date '2018-11-11'
from dual
connect by rownum <= 1000;
commit;
create or replace procedure p_del_tab(str_in_tab in varchar2, --表名
dt_in_beg in date, --開始日期
dt_in_end in date, --結束日期
str_o_flag out varchar2, --成功/失敗標識
--返回數值 說明成功執行
--返回失敗 請查看異常信息
str_o_sqlcode out varchar2, --異常代碼
str_o_sqlerrm out varchar2 --異常信息
)
/******************************************************************************************
name:p_del_tab
purpose: 按開始、結束時間刪除指定表中的記錄
ver date author description
----- ----------- ---------- ----------------------
v1.0 2018-11-11 dayoff 1.創建存儲過程
notes: 1.符合條件每500條提交一次
*******************************************************************************************/
as
i_count number; --記錄數
i_delcount number := 0; --刪除量
s_p_sqldel varchar2(1000); --刪除sql
s_p_sqlcount varchar2(1000); --統計sql
begin
str_o_sqlcode := null;
str_o_sqlerrm := null;
s_p_sqlcount := 'select count(*) from ' || str_in_tab ||
' where dt_insert between ''' || dt_in_beg ||
''' and ''' || dt_in_end || ''' ';
-- dbms_output.put_line(s_p_sqlcount);
execute immediate s_p_sqlcount
into i_count;
--符合條件的數據刪除
if i_count > 0 then
--循環每500條刪除並提取
loop
s_p_sqldel := 'delete from ' || str_in_tab ||
' where dt_insert between ''' || dt_in_beg ||
''' and ''' || dt_in_end || ''' and rownum <=500';
-- dbms_output.put_line(s_p_sqldel);
execute immediate s_p_sqldel;
-- dbms_output.put_line(sql%rowcount);
i_delcount := i_delcount + sql%rowcount;
commit;
--統計當前符合條件的量
execute immediate s_p_sqlcount
into i_count;
--為0時退出
exit when i_count <= 0;
end loop;
end if;
str_o_flag := to_char(i_delcount);
commit;
--異常處理
exception
when others then
rollback;
str_o_flag := '失敗';
str_o_sqlcode := sqlcode;
str_o_sqlerrm := substr(sqlerrm, 1, 512);
end;