在Oracle10g之前,優化SQL是個比較費力的技術活,不停的分析執行計劃,加hint,分析統計信息等等。
在10g中,Oracle推出了自己的SQL優化輔助工具: SQL優化器(SQL Tuning Advisor :STA),它可以給出優化建議。
使用STA一定要保證優化器是CBO模式下。
一 創建優化任務
可以通過傳入文本來獲取相應的優化建議,也可以通過sql_id方式獲取。
1.1 傳入文本方式
DECLARE
my_task_name VARCHAR2(30);
my_sqltext CLOB;
BEGIN
my_sqltext := 'select count(*) from bigtab a, smalltab b where a.object_name=b.table_name';
my_task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK(
sql_text => my_sqltext,
user_name => 'SCOTT', -- 表示該語句由哪個用戶執行,注意用戶名須大寫
scope => 'COMPREHENSIVE',
time_limit => 60,
task_name => 'tuning_sql_test',
description => 'Task to tune a query on a specified table');
DBMS_SQLTUNE.EXECUTE_TUNING_TASK( task_name => 'tuning_sql_test');
END;
/
1.2 傳入sql_id方式
#根據sql文本獲取sql_id:
select sql_id,sql_text from v$sqlarea where sql_text like '%bigtab%'
#傳入sql_id
DECLARE
my_task_name VARCHAR2(30);
sql_id VARCHAR2(30);
BEGIN
sql_id := '&sqlid';
my_task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK
(sql_id=> sql_id,
scope => 'comprehensive',
time_limit=>60,
task_name=>'tuning_sql_test',
description => 'Tuning Task');
DBMS_SQLTUNE.EXECUTE_TUNING_TASK('tuning_sql_test');
END;
/
二 執行優化任務
SQL> exec dbms_sqltune.execute_tuning_task('tuning_sql_test');
--檢查優化任務的狀態
SYS@PROD1>SELECT task_name,status FROM USER_ADVISOR_TASKS WHERE task_name ='tuning_sql_test';
TASK_NAME STATUS
------------------------------ -----------
tuning_sql_test COMPLETED
三 查看優化建議
SET LONG 999999
set serveroutput on size 999999
SET LINESIZE 1000
SELECT DBMS_SQLTUNE.REPORT_TUNING_TASK( 'tuning_sql_test') from DUAL;
優化建議如下:
……
The execution plan of this statement can be improved by creating one or more
indices.
Recommendation (estimated benefit: 99.57%)
------------------------------------------
- Consider running the Access Advisor to improve the physical schema design
or creating the recommended index.
DBMS_SQLTUNE.REPORT_TUNING_TASK('TUNING_SQL_TEST')
--------------------------------------------------------------------------------
create index SCOTT.IDX$$_0E4C0001 on SCOTT.BIGTAB("OBJECT_NAME");
- Consider running the Access Advisor to improve the physical schema design
or creating the recommended index.
create index SCOTT.IDX$$_0E4C0002 on SCOTT.SMALLTAB("TABLE_NAME");
……
四 刪除優化任務
exec dbms_sqltune.drop_tuning_task('tuning_sql_test');
--本篇文章主要參考自https://blog.csdn.net/tianlesoftware/article/details/5630888