Oracle重建所有表和索引

定义两个存储过程,先执行表移动,再执行索引重建。
(如果记录很多,执行时间可能会很长,几个小时也有可能,建议在系统空闲时运行):

create or replace procedure p_remove_all_table
 (tablespace_name in varchar2)--这里是表空间名,如果不改变表空间,可以传入null
as
  sqlt varchar(200);
begin
    --取所有非临时表
    for tab in (select table_name, tablespace_name from user_tables where temporary = 'N') loop
        if tablespace_name is null then
            --如果为null,则在本表空间下移动           
            sqlt := 'alter table ' || tab.table_name || ' move';
        elsif upper(tablespace_name) <> tab.tablespace_name then
            --如果目标表空间和现在的表空间不一致,则移动到新的表空间
            sqlt := 'alter table ' || tab.table_name || ' move tablespace ' || tablespace_name;
        else
            --如果目标表空间和现在的表空间要同,则跳过
            goto continue; 
        end if ;
      
        dbms_output.put_line(sqlt);
        EXECUTE IMMEDIATE sqlt;
      
        <<continue>>
        null;
     end loop;
end;
/*
功能:为数据表改变表空间,或在同一表空间下移动到不同的数据段。
说明:如果传入null,则把所有表在原表空间下移动到一个新的数据段
      如果传入的是一个表空间的名称,则所有表都移动到这个新的表空间下,如果
      某个表本来就在这个表空间下,则跳过。
作者:81,  2007年6月26日
*/

create or replace procedure p_rebuild_all_index
   (tablespace_name in varchar2,--这里是表空间名,如果不改变表空间,可以传入null
   only_unusable in boolean)    --是否仅对无效的索引操作                                                                                                      
as
   sqlt varchar(200);
begin
    --只取非临时索引
    for idx in (select index_name, tablespace_name, status from user_indexes where temporary = 'N') loop
        --如果是如重建无效的索引,且当索引不是无效时,则跳过
        if only_unusable = true and idx.status <> 'UNUSABLE' then
           goto continue;
        end if;
       
        if (tablespace_name is null) or idx.status = 'UNUSABLE' then
           --如果没有指定表空间,或索引无效,则在原表空间重建
           sqlt := 'alter index ' || idx.index_name || ' rebuild ';
        elsif upper(tablespace_name) <> idx.tablespace_name then
           --如果指定的不同的表空间,则在指定表空间待建索引
           sqlt := 'alter index ' || idx.index_name || ' rebuild tablespace ' || tablespace_name;
        else
           --如果表空间相同,则跳过
           goto continue;
        end if;
       
        dbms_output.put_line(idx.index_name);
        EXECUTE IMMEDIATE sqlt;
        <<continue>>
        null;
     end loop;
end;
/*
功能:重建索引。
说明:如果表空间参数传入null,则在原表空间内重建索引,否则在目标表空间重建索引。
      如果表空间相同,则跳过。
      only_unusable表示是否只对无效的索引进行重建
作者:81,   2007年6月26日
*/

posted @   81  阅读(2263)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示