Oracle收集表的数据与统计信息差异

   有时候有这样的烦恼,由于dmp增量到数据库中,或是大批量数据操作后没有收集表的统计信息,导致数据库性能慢。要手工写脚本检查。

drop table gather_tcount;
create table gather_tcount
(
  TABLE_NAME  VARCHAR2(30) not null,
  gather_time date,
  num_rows    number,
  user_table_num_rows number
);
comment on table GATHER_TCOUNT
  is '统计表的数据量,差距太大的需要收集统计信息';
alter table GATHER_TCOUNT
  add constraint pk_gt_name_t primary key (TABLE_NAME, GATHER_TIME);

create or replace procedure p_gather_tcount
as
  --统计实际表中数据量和统计信息表中数据量差异
  --如果是重新统计,需要先清空gather_tcount的内容
  --如果是断点续统计,不需要清空gather_tcount的内容
  v_count number;
  v_temp number;
  v_tabname_temp varchar2(30);
begin
  for c_rows in(select s.table_name,s.num_rows 
     from user_tables s  where s.table_name not like '%BAK%' 
     and s.table_name not like 'BK%' and
       s.table_name not like '%TEMP')--过滤掉备份表
    loop
       v_tabname_temp := c_rows.table_name;
       select count(1) into v_temp from gather_tcount where table_name = c_rows.table_name;
       --如果是断点续统计,则不需要重新count表
       if(v_temp =0) then
          execute immediate 'select count(1) from '||c_rows.table_name into v_count;
          execute immediate 'insert into gather_tcount(TABLE_NAME,gather_time,
          num_rows,user_table_num_rows) values(:1,:2,:3,:4)' 
          using c_rows.table_name,sysdate,v_count,c_rows.num_rows;
         commit;
       end if;
    end loop;
  exception when others then
    execute immediate 'insert into gather_tcount(TABLE_NAME,gather_time,
          num_rows,user_table_num_rows) values(:1,:2,:3,:4)' 
          using v_tabname_temp,sysdate,sqlcode,sqlcode; --错误的先中断
     commit;
end;


call p_gather_tcount();

select * from gather_tcount;

你可能感兴趣的:(Oracle收集表的数据与统计信息差异)