假如你管理的Oracle數據庫下某些應用項目有大量的修改刪除操作, 數據索引是需要週期性的重建的。 它不僅可以提高查詢性能, 還能增加索引表空間空閒空間大小。在Oracle裏大量刪除記錄後, 表和索引裏佔用的數據塊空間並沒有釋放。
通過重建索引可以釋放已刪除記錄索引佔用的數據塊空間來轉移數據, 重命名的方法可以重新組織表裏的數據。
Oracle按用戶名重建索引的SQL腳本
SET ECHO OFF; SET FEEDBACK OFF; SET VERIFY OFF; SET PAGESIZE 0; SET TERMOUT ON; SET HEADING OFF; ACCEPT username CHAR PROMPT 'Enter the index username: '; spool /oracle/rebuild_&username.sql; SELECT 'REM +-----------------------------------------------+' || chr(10) || 'REM | INDEX NAME : ' || owner || '.' || segment_name || lpad('|', 33 - (length(owner) + length(segment_name)) ) || chr(10) || 'REM | BYTES : ' || bytes || lpad ('|', 34-(length(bytes)) ) || chr(10) || 'REM | EXTENTS : ' || extents || lpad ('|', 34-(length(extents)) ) || chr(10) || 'REM +-----------------------------------------------+' || chr(10) || 'ALTER INDEX ' || owner || '.' || segment_name || chr(10) || 'REBUILD ' || chr(10) || 'TABLESPACE ' || tablespace_name || chr(10) || 'STORAGE ( ' || chr(10) || ' INITIAL ' || initial_extent || chr(10) || ' NEXT ' || next_extent || chr(10) || ' MINEXTENTS ' || min_extents || chr(10) || ' MAXEXTENTS ' || max_extents || chr(10) || ' PCTINCREASE ' || pct_increase || chr(10) || ');' || chr(10) || chr(10) FROM dba_segments WHERE segment_type = 'INDEX' AND owner='&username' ORDER BY owner, bytes DESC; spool off; |
假如你用的是WINDOWS系統, 想改變輸出文件的存放目錄, 修改spool後面的路徑成:
spool c:/oracle/rebuild_&username.sql;
如果你只想對大於max_bytes的索引重建索引, 可以修改上面的SQL語句:
在AND owner='&username' 後面加個限制條件 AND bytes> &max_bytes
如果你想修改索引的存儲參數, 在重建索引rebuild_&username.sql裏改也可以。
比如把pctincrease不等於零的值改成是零。
生成的rebuild_&username.sql文件我們需要來分析一下, 它們是否到了需要重建的程度:
分析索引,觀察一下是否碎片特別嚴重。
SQL>ANALYZE INDEX &index_name VALIDATE STRUCTURE; col name heading 'Index Name' format a30 col del_lf_rows heading 'Deleted|Leaf Rows' format 99999999 col lf_rows_used heading 'Used|Leaf Rows' format 99999999 col ratio heading '% Deleted|Leaf Rows' format 999.99999 SELECT name, del_lf_rows, lf_rows - del_lf_rows lf_rows_used, to_char(del_lf_rows / (lf_rows)*100,'999.99999') ratio FROM index_stats where name = upper('&index_name'); |
當刪除的比率大於15 - 20% 時,肯定是需要索引重建的。
經過刪改後的rebuild_&username.sql文件我們可以放到Oracle的定時作業裏:
比如一個月或者兩個月在非繁忙時間運行。
如果遇到ORA-00054錯誤, 表示索引在的表上有鎖信息, 不能重建索引。
那就忽略這個錯誤, 觀察下次是否成功。
對於那些特別忙的表要不能用這裏上面介紹的方法, 我們需要將它們的索引從rebuild_&username.sql裏刪去。