归档后如何删除记录?

时间:2014-03-11 06:01:07

标签: sql oracle

归档最近4到12个月的数据。以下查询完成了这项工作。

insert into process_state_archive
  select *
    from process_state
   where tstamp BETWEEN ADD_MONTHS(trunc(SYSDATE, 'MONTH'), -12) AND
         LAST_DAY(TRUNC(SYSDATE, 'MONTH') - 4);

现在我想在process_state表中删除4到12个月的数据。在上面的查询中添加此条件的位置?有人可以告诉我吗?

1 个答案:

答案 0 :(得分:2)

这里(未经测试)

DECLARE
  v_insert_count number;
  v_delete_count number;
BEGIN
  insert into process_state_archive 
  select * 
    from process_state 
    where tstamp BETWEEN ADD_MONTHS(trunc(SYSDATE,'MONTH'), -12) AND LAST_DAY(TRUNC(SYSDATE,  'MONTH') - 4);

  v_insert_count := sql%rowcount;

  delete process_state 
   where  tstamp BETWEEN ADD_MONTHS(trunc(SYSDATE,'MONTH'), -12) AND LAST_DAY(TRUNC(SYSDATE,  'MONTH') - 4);

  v_delete_count := sql%rowcount;

  if v_insert_count = v_delete_count then
    commit;
  else
    rollback;
  end if;

END;
/

sql%rowcount返回受上一个sql语句影响的行数。