Oracle批量rebuild所有索引的脚本

早期,项目的数据库没有搞分区表,rebuild索引的脚本很简单:

begin
  for c1 in (select t.index_name, t.partitioned from user_indexes t where t.index_type<>'LOB' and t.index_type <> 'IOT - TOP')
  loop
    execute immediate 'alter index ' || c1.index_name || ' rebuild ';
  end loop;
end;

因数据量越来越大,近来把有些大表改为分区表,有些索引也改成了分区索引。但分区索引不能整个rebuild,必须一个分区一个分区地进行,因此脚本也随之改变:

begin
  for c1 in (select t.index_name, t.partitioned from user_indexes t where t.index_type<>'LOB' and t.index_type <> 'IOT - TOP')
  loop
    if c1.partitioned='NO' then
      --对非分区索引直接rebuild
      execute immediate 'alter index ' || c1.index_name || ' rebuild';
    else
      --对分区索引,需对每个分区进行rebuild
      for c2 in (select partition_name from user_ind_partitions where index_name=c1.index_name)
      loop
        execute immediate 'alter index ' || c1.index_name || ' rebuild partition ' || c2.partition_name;
      end loop;
    end if;
  end loop;
end;

为提升性能,可进一步在rebuild时增加nologging、parallel 选项。

原文地址:https://www.cnblogs.com/wggj/p/6877367.html