Oracle9以后假如你想用基于成本的优化器,需要定期(每周)对数据库里的表和索引做analyze分析。 数据库参数文件initorasid.ora里默认的优化器 optimizer_mode = choose 你要改成 optimizer_mode = first_rows (OLTP系统)
optimizer_mode = all_rows (DSS 系统) 下面是一个可以在UNIX环境自动生成分析表和索引的脚本analyze.sh (sys用户的密码passWord要根据情况修改。) --------------------------------------------------------------------------------------- su - oracle -c "sqlplus sys/password"< set pages 9999 set heading off set echo off set feedback off spool /oracle_backup/bin/analyze.sql; select 'analyze table 'owner'.'table_name' estimate statistics sample 5000 rows;' from dba_tables where owner not in ('SYS','SYSTEM','PERFSTAT'); select 'analyze index 'owner'.'index_name' compute statistics;' from dba_indexes where owner not in ('SYS','SYSTEM','PERFSTAT'); spool off; set echo on set feedback on spool /oracle_backup/log/analyze.log; @/oracle_backup/bin/analyze.sql spool off; exit; --------------------------------------------------------------------------------------- 假如你经常变动的表和索引只属于某个特定的用户(假如是test)可以把上面的 owner not in ('SYS','SYSTEM','PERFSTAT') 改成 owner in ('TEST') 来进行定期的分析。 注重事项:假如你使用的是默认的优化器(choose),一定不要定期使用上面那个analyze.sh脚本。 因为这时优化器可能更倾向于全表扫描。 假如统计分析资料不全,SQL运行时会对缺少统计资料的表进行数据采集。会大大降低SQL的执行速度。 我们要用下面这个del_analyze.sh脚本定期删除可能产生的分析结果, 保证优化器按规则(rule)执行。 --------------------------------------------------------------------------------------- su - oracle -c "sqlplus sys/password"< set pagesize 9999; set linesize 120; set heading off; set echo off; set feedback off; spool /oracle_backup/bin/del_analyze.sql; select 'analyze table 'owner'.'table_name' delete statistics;' from dba_tables where owner not in ('SYS','SYSTEM','PERFSTAT'); select 'analyze index 'owner'.'index_name' delete statistics;' from dba_indexes where owner not in ('SYS','SYSTEM','PERFSTAT'); spool off; set echo on; set feedback on; spool /oracle_backup/log/del_analyze.log; @/oracle_backup/bin/del_analyze.sql spool off; exit;
|