当前位置:网站首页>SQL tuning guide notes 18:analyzing statistics using optimizer statistics Advisor

SQL tuning guide notes 18:analyzing statistics using optimizer statistics Advisor

2022-06-12 21:41:00 dingdingfish

This paper is about SQL Tuning Guide The first 18 Chapter “Analyzing Statistics Using Optimizer Statistics Advisor” The notes .

Optimizer Statistics Advisor Analyze how optimizer statistics are collected , And then make suggestions .

18.1 About Optimizer Statistics Advisor

Optimizer Statistics Advisor Is a built-in diagnostic software , Analyze the quality of statistics and tasks related to statistics .

The consultant task runs automatically in the maintenance window , But you can also run on demand . Then you can view the consultant report . If the consultant makes recommendations , So in some cases , You can run system generated scripts to implement them .

The following figure provides Optimizer Statistics Advisor Conceptual overview of .

 Insert picture description here

18.1.1 Purpose of Optimizer Statistics Advisor

Optimizer Statistics Advisor Check how optimizer statistics are collected .

The consultant will automatically diagnose problems in the existing practice of collecting statistics . The advisor does not collect new or replacement optimizer statistics sets . The consultant's output is a report of findings and recommendations , Helps you follow best practices for collecting statistics .

Optimizer statistics play an important role in determining the execution plan of a query . therefore , It is essential that the optimizer collect and maintain accurate and up-to-date statistics . So , The optimizer provides DBMS_STATS package , The package evolves from one version to another . Usually , Users will develop their own strategies for collecting statistics according to specific workloads , Then use local scripts to implement these policies .

18.1.1.1 Problems with a Traditional Script-Based Approach

The advantage of the scripted approach is that scripts are often tested and reviewed . however , The owner of the suboptimal legacy scripts may not change them , For fear of causing a change in the plan .

The traditional method has the following problems :

  • Old scripts may not keep up with new best practices , New best practices may vary by version .
    Usually , Subsequent versions will enhance the histogram 、 sampling 、 Workload monitoring 、 Concurrency and other optimizer related features . for example , from Oracle Database 12c Start ,Oracle It is recommended to set AUTO_SAMPLE_SIZE Not the percentage . however , Legacy scripts typically specify a sampling percentage , This may lead to an unsatisfactory implementation plan .
  • Resources are wasted on unnecessary statistical data collection .
    A script may collect statistics on the same table multiple times a day .
  • Automatic statistics collection does not guarantee accurate and up-to-date statistics .
    for example , Sometimes the automatic statistics collection job is not running , Because the initialization parameter combination disables it , Or the job is terminated . Besides , Sometimes due to resource constraints , Or because too many objects need to be collected , Insufficient automatic job maintenance window . A job that stops running before all statistics are collected will cause some objects to have no or outdated statistics , This, in turn, leads to poor planning .
  • Statistics can sometimes be lost 、 Outdated or incorrect .
    for example , Statistics may be inconsistent between a table and its index , Or have a primary key - Statistics may be inconsistent between tables of foreign key relationships . perhaps , The statistics collection job may have been unexpectedly disabled , Or you may not know that the script has failed .
  • Lack of understanding of the problem can cost a lot of time and resources .
    for example , The service request may seek a solution to the problem , Without realizing that the problem is caused by suboptimal Statistics . Diagnostics can take a lot of time to email scripts for problem queries 、 Enable tracking and survey tracking .
  • The recommended fix may not be feasible .
    Performance engineers may suggest changes to the application code that maintains statistics . In some organizations , This requirement may be difficult or impossible to meet .

18.1.1.2 Advantages of Optimizer Statistics Advisor

Compared with the traditional method , A consultant based approach provides better scalability and maintainability .

If the best practices in the new release change , that Optimizer Statistics Advisor Will code these practices into their rules . In this way , Consultants always provide up-to-date advice .

The consultant analyzes how you currently collect statistics ( Use manual scripts 、 Explicitly set parameters, etc )、 Effectiveness of existing statistical information collection operations and quality of collected statistical information . Optimizer Statistics Advisor No new or replacement optimizer statistics sets are collected , So it doesn't affect the workload . contrary ,Optimizer Statistics Advisor Analyze the information stored in the data dictionary , The results and recommendations are then stored in the database .

Optimizer Statistics Advisor Compared with traditional methods, it has the following advantages :

  • Provide easy to understand reports
    Consultants apply rules to generate results 、 Recommendations and actions .
  • Provide scripts to implement the necessary fixes , Without changing the application code
    When you implement the recommended actions , Every time you execute an improved statement, you benefit . for example , If you set global preferences , So that the sample size is AUTO_SAMPLE_SIZE Not the suboptimal percentage , Then every plan based on improved statistics can benefit from this change .
  • Run once a day in the maintenance window called AUTO_STATS_ADVISOR_TASK Predefined tasks for
    To run an automated job , Must be STATISTICS_LEVEL The initialization parameter is set to TYPICAL or ALL.
  • stay DBMS_STATS Provided in the package API, Enables you to manually create and run tasks , Store findings and recommendations in the data dictionary view , Generate reports for tasks , And make corrections if necessary
  • Integrate with existing tools
    The consultant and SQL Tuning Advisor and AWR Integrate , The latter summarizes Optimizer Statistics Advisor result .

18.1.2 Optimizer Statistics Advisor Concepts

Optimizer statistics advisor uses an automated database diagnostic monitor (ADDM)、SQL The performance analyzer has the same consultant framework as other consultants .

18.1.2.1 Components of Optimizer Statistics Advisor

Optimizer Statistics Advisor The framework stores its metadata in data dictionaries and dynamic performance views .

The following Venn diagram shows Optimizer Statistics Advisor The rules of 、 result 、 The relationship between recommendations and actions . for example , All the findings come from rules , But not all rules generate discovery .
 Insert picture description here

18.1.2.1.1 Rules for Optimizer Statistics Advisor

Optimizer Statistics Advisor The rule is Oracle Standards provided ,Optimizer Statistics Advisor Carry out its inspection through this standard .

These rules represent the... Based on the current feature set Oracle Best practices . If best practices vary by version , that Optimizer Statistics Advisor The rules will also change .

The consultant divides the rules into the following categories :

  • System
    Preferences for collection of such inspection statistics 、 Automatic statistics collection job status 、SQL Use of planning instructions, etc . The rules in this class are in V$STATS_ADVISOR_RULES.RULE_TYPE Has a value in SYSTEM.

  • Operation
    This class checks whether statistics collection uses default values , Whether to use SET_*_STATS Process create test statistics , wait . The rules in this class are in V$STATS_ADVISOR_RULES.RULE_TYPE Has a value in OPERATION.

  • Object
    This checks the quality of the statistics 、 Obsolescence of statistical information 、 Unnecessary statistical information collection, etc . The rules in this class are in V$STATS_ADVISOR_RULES.RULE_TYPE Has a value in OBJECT.

The rule checks the following questions :

  • How to collect statistics
    for example , A rule may specify recommended settings for initialization parameters . Another rule might specify that statistics should be collected at the schema level .

  • When to collect statistics
    for example , The consultant may suggest that the maintenance window for automatic statistics collection jobs should be enabled , Or the window should be extended .

  • How to improve the efficiency of statistical collection
    for example , A rule may be specified in DBMS_STATS Default parameters should be used in , Or statistics should not be set manually .

stay V$STATS_ADVISOR_RULES in , Each rule has a unique string ID, Can be used for DBMS_STATS Process and reporting . You can use rule filters to specify Optimizer Statistics Advisor Rules to check . however , You cannot write new rules .

The following query has sample output , Lists V$STATS_ADVISOR_RULES Subset of rules in . Rules may vary by version .

SET LINESIZE 208
SET PAGESIZE 100
COL ID FORMAT 99
COL NAME FORMAT a33
COL DESCRIPTION FORMAT a62

SELECT RULE_ID AS ID, NAME, RULE_TYPE, DESCRIPTION 
FROM   V$STATS_ADVISOR_RULES 
WHERE  RULE_ID BETWEEN 1 AND 12
ORDER BY RULE_ID;

 ID NAME                              RULE_TYPE DESCRIPTION                                                   
--- --------------------------------- --------- --------------------------------------------------------------
  1 UseAutoJob                        SYSTEM    Use Auto Job for Statistics Collection                        
  2 CompleteAutoJob                   SYSTEM    Auto Statistics Gather Job should complete successfully       
  3 MaintainStatsHistory              SYSTEM    Maintain Statistics History                                   
  4 UseConcurrent                     SYSTEM    Use Concurrent preference for Statistics Collection           
  5 UseDefaultPreference              SYSTEM    Use Default Preference for Stats Collection                   
  6 TurnOnSQLPlanDirective            SYSTEM    SQL Plan Directives should not be disabled                    
  7 AvoidSetProcedures                OPERATION Avoid Set Statistics Procedures                               
  8 UseDefaultParams                  OPERATION Use Default Parameters in Statistics Collection Procedures    
  9 UseGatherSchemaStats              OPERATION Use gather_schema_stats procedure                             
 10 AvoidInefficientStatsOprSeq       OPERATION Avoid inefficient statistics operation sequences              
 11 AvoidUnnecessaryStatsCollection   OBJECT    Avoid unnecessary statistics collection                       
 12 AvoidStaleStats                   OBJECT    Avoid objects with stale or no statistics                     

12 rows selected. 
18.1.2.1.2 Findings for Optimizer Statistics Advisor

When Optimizer Statistics Advisor When checking the evidence stored in the database and concluding that the rules have not been followed , Will come to a conclusion .

To generate results ,Optimizer Statistics Advisor Perform a task , This task can be invoked automatically or manually . This task analyzes the statistical history stored in the data dictionary 、 Statistics of operation logs and SYSAUX Current statistical footprints present in . for example , Consultant program query DBA_TAB_STATISTICS and DBA_IND_STATISTICS To determine if the statistics are out of date , Or whether there is a difference in the number of rows .

Usually , Optimizer statistics advisor generates results when certain rules are not followed or violated , Although some results ( For example, the object is obsolete ) Information only . for example , Discovery may show DBMS_STATS.GATHER_TABLE_STATS Used ESTIMATE_PERCENT=>0.01, This is against the law. ESTIMATE_PERCENT=>AUTO_SAMPLE_SIZE The rules .

A discovery corresponds to a rule . however , A rule can produce many results .

18.1.2.1.3 Recommendations for Optimizer Statistics Advisor

According to each discovery , The optimizer statistics consultant will make suggestions on how to get better statistics .

for example ,advisor You may find that the rule of not using sampling is violated when collecting statistics , It is suggested to specify AUTO_SAMPLE_SIZE. Consultants store recommendations in DBA_ADVISOR_RECOMMENDATIONS in .

There may be multiple suggestions for a single discovery . under these circumstances , You must investigate to determine the recommendations to follow . Each recommendation contains one or more basic principles , These basic principles explain Optimizer Statistics Advisor The reason for his suggestion . In some cases , The findings may not produce recommendations .

18.1.2.1.4 Actions for Optimizer Statistics Advisor

Optimizer Statistics Advisor The action is to implement the recommendations SQL or PL/SQL Script . Where possible , It is suggested that there should be corresponding actions . Consultants store operations in DBA_ADVISOR_ACTIONS in .

for example ,Optimizer Statistics Advisor Perform a task , This task performs the following steps :

  • Check the rules
    The consultant checks for compliance with the rule that outdated statistics should be avoided .

  • Generate results
    The consultant found that many objects do not have statistical information .

  • Generate recommendations
    The consultant recommends collecting statistics of the object without statistics .

  • Generate action
    The advisor program generates an execution DBMS_STATS.GATHER_DATABASE_STATS Of PL/SQL Script , Provide a list of objects that need to collect statistics .

18.1.2.2 Operational Modes for Optimizer Statistics Advisor

Optimizer Statistics Advisor Support automatic and manual modes .

  • Automatically
    Predefined tasks AUTO_STATS_ADVISOR_TASK Automatically run once a day in the maintenance window . This task runs as part of the automatic optimizer statistics collection client . Automated tasks generate findings and recommendations , But the operation will not be performed automatically .
    For any other task , You can configure automated tasks and generate reports . If the report recommends an action , Then you can perform these operations manually .

  • Manual
    You can use DBMS_STATS.CREATE_ADVISOR_TASK Function to create your own task , And then use EXECUTE_ADVISOR_TASK The process runs it at any time .
    Unlike automated tasks , Manual tasks can perform actions automatically . perhaps , You can configure tasks to generate PL/SQL Script , You can then run the script manually .

18.1.3 Command-Line Interface to Optimizer Statistics Advisor

Use DBMS_STATS PL/SQL The package performs the optimizer statistics advisor task .

surface 18-1 For creating and deleting tasks DBMS_STATS API

PL/SQL Procedure or function describe
CREATE_ADVISOR_TASK by Optimizer Statistics Advisor Create a consultant task . If a task name has been specified , The consultant uses the assigned task name ; otherwise , The consultant will automatically generate a new task name .
DROP_ADVISOR_TASK Delete Optimizer Statistics Advisor Task and all its result data .

surface 18-2 For task execution DBMS_STATS API

PL/SQL Procedure or function describe
EXECUTE_ADVISOR_TASK Execute the Optimizer Statistics Advisor Mission .
INTERRUPT_ADVISOR_TASK Interrupt the currently executing optimizer statistics advisor task . The task will end its operation as if it were in a normal exit , Enables you to access intermediate results . You can resume the task later .
CANCEL_ADVISOR_TASK Cancel the optimizer statistics advisor task execution , And delete all intermediate results currently executed .
RESET_ADVISOR_TASK take Optimizer Statistics Advisor Task execution is reset to its initial state . Call this procedure on the currently unexecuted task .
RESUME_ADVISOR_TASK Restore recently interrupted Optimizer Statistics Advisor Task execution .

surface 18-3 Of the consultant's report DBMS_STATS API

PL/SQL Procedure or function describe
REPORT_STATS_ADVISOR_TASK Report the results of the optimizer statistics advisor task .
GET_ADVISOR_RECS Generate a recommendation report for a given project .

surface 18-4 For task and filter configuration DBMS_STATS API

PL/SQL Procedure or function describe
CONFIGURE_ADVISOR_TASK For the implementation of the consultant's tasks 、 The report 、 Script generation and implementation configuration optimizer statistics advisor list .
GET_ADVISOR_OPR_FILTER Create operation filters for statistical operations .
CONFIGURE_ADVISOR_RULE_FILTER by Optimizer Statistics Advisor Task configuration rule filter .
CONFIGURE_ADVISOR_OPR_FILTER by Optimizer Statistics Advisor Task configuration action filter .
CONFIGURE_ADVISOR_OBJ_FILTER by Optimizer Statistics Advisor Task configuration object filter .
SET_ADVISOR_TASK_PARAMETER to update Optimizer Statistics Advisor The value of the task parameter . Valid parameters are TIME_LIMIT and OP_START_TIME.

surface 18-5 For implementing recommended actions DBMS_STATS API

PL/SQL Procedure or function describe
SCRIPT_ADVISOR_TASK Get scripts that implement recommended actions for problems found by consultants . You can check this script , Then select the action to perform .
IMPLEMENT_ADVISOR_TASK According to the specified Optimizer Statistics Advisor The results of implementation implement the actions recommended by the consultant .

18.2 Basic Tasks for Optimizer Statistics Advisor

This section describes the use of Optimizer Statistics Advisor Basic workflow . All procedures and functions are in DBMS_STATS In bag .

The following figure shows the automatic and manual paths in the workflow . If AUTO_STATS_ADVISOR_TASK Automatic operation during maintenance period , Then your workflow starts with the query report . In a manual workflow , You must use PL/SQL To create and execute tasks .
 Insert picture description here
Usually , You perform the optimizer statistics advisor steps in the order shown in the following table .

  1. Use DBMS_STATS.CREATE_ADVISOR_TASK( Manual workflows only ) Create optimizer advisor task .
  2. perhaps , By inquiring DBA_ADVISOR_EXECUTIONS List the implementation of the consultant's tasks .
  3. perhaps , Use DBMS_STATS.CONFIGURE_ADVISOR_*_FILTER The process configures filters for tasks .
  4. Use DBMS_STATS.EXECUTE_ADVISOR_TASK Perform consulting tasks ( Manual workflows only ).
  5. Generate consultant reports .
  6. Implement the recommendation in any of the following ways :
    • Use DBMS_STATS.IMPLEMENT_ADVISOR_TASK Automatically implement all recommendations .
    • Generate a use DBMS_STATS.SCRIPT_ADVISOR_TASK Implement the proposed PL/SQL Script , Edit this script , And then run it manually .
set serveroutput on

DECLARE
  v_tname   VARCHAR2(128) := 'my_task';
  v_ename   VARCHAR2(128) := NULL;
  v_report  CLOB := null;
  v_script  CLOB := null;
  v_implementation_result CLOB;
BEGIN
  dbms_stats.drop_advisor_task(v_tname);

  -- create a task
  v_tname := DBMS_STATS.CREATE_ADVISOR_TASK(v_tname);

  -- execute the task
  v_ename := DBMS_STATS.EXECUTE_ADVISOR_TASK(v_tname);

  -- view the task report
  v_report := DBMS_STATS.REPORT_ADVISOR_TASK(v_tname);
  DBMS_OUTPUT.PUT_LINE(v_report);

  -- implement all recommendations
  v_implementation_result := DBMS_STATS.IMPLEMENT_ADVISOR_TASK(v_tname);
END;

Output is as follows :

GENERAL INFORMATION
-------------------------------------------------------------------------------

 Task Name       : MY_TASK           
 Execution Name  : EXEC_95           
 Created         : 06-12-22 09:24:27 
 Last Modified   : 06-12-22 09:24:39 
-------------------------------------------------------------------------------
SUMMARY
-------------------------------------------------------------------------------
 For execution EXEC_95 of task MY_TASK, the Statistics Advisor has 4            
 finding(s). The findings are related to the following rules:                   
 AVOIDSETPROCEDURES, USEDEFAULTPARAMS, USEGATHERSCHEMASTATS, AVOIDANALYZETABLE. 
 Please refer to the finding section for detailed information.                  
-------------------------------------------------------------------------------
FINDINGS
-------------------------------------------------------------------------------
 Rule Name:         AvoidSetProcedures                                          
 Rule Description:  Avoid Set Statistics Procedures                             
 Finding:  There are 2 SET_[COLUMN|INDEX|TABLE|SYSTEM]_STATS procedures being   
           used for statistics gathering.                                       
 Operation:                                                                          
 set_index_stats(ownname=>'SH', indname=>'SALARY_IX', numrows=>2000);                
 set_table_stats(ownname=>'SH', tabname=>'CONTRACTORS', numrows=>2000, numblks=>10); 

 Recommendation:  Do not use SET_[COLUMN|INDEX|TABLE|SYSTEM]_STATS procedures.  
                  Gather statistics instead of setting them.                    
 Rationale:  SET_[COLUMN|INDEX|TABLE|SYSTEM]_STATS will cause bad plans due to  
             wrong or inconsistent statistics.                                  
----------------------------------------------------
 Rule Name:         UseDefaultParams                                            
 Rule Description:  Use Default Parameters in Statistics Collection Procedures  
 Finding:  There are 25 statistics operation(s) using nondefault parameters.    
 Operation:                                                                                                                                                       
 gather_table_stats(ownname=>'sh', tabname=>'customers', method_opt=>'FOR ALL COLUMNS SIZE SKEWONLY FOR COLUMNS (LOWER(cust_state_province)) SIZE SKEWONLY');     
 gather_table_stats(ownname=>'sh', tabname=>'customers', method_opt=>'FOR ALL COLUMNS SIZE SKEWONLY FOR COLUMNS (LOWER(cust_state_province)) SIZE SKEWONLY');     
 gather_table_stats(ownname=>'sh', tabname=>'customers', method_opt=>'FOR ALL COLUMNS SIZE SKEWONLY FOR COLUMNS SIZE SKEWONLY (cust_state_province,country_id)'); 
 gather_schema_stats(ownname=>'SYS', no_invalidate=>FALSE, gather_temp=>FALSE, gather_fixed=>FALSE);                                                              
 gather_schema_stats(ownname=>'SYS', no_invalidate=>FALSE, gather_temp=>FALSE, gather_fixed=>FALSE);                                                              
 unlock_table_stats(ownname=>'OE', tabname=>'ORDERS', stattype=>'ALL');                                                                                           
 lock_table_stats(ownname=>'OE', tabname=>'ORDERS', stattype=>'ALL');                                                                                             
 delete_table_stats(ownname=>'OE', tabname=>'ORDERS', cascade_parts=>TRUE, cascade_columns=>TRUE, cascade_indexes=>TRUE, stattype=>'ALL');                        
 gather_database_stats_model();                                                                                                                                   
 gather_database_stats_model();                                                                                                                                   

 Recommendation:  Use default parameters for statistics operations.             
 Example:                                                                       
 -- Gathering statistics for 'SH' schema using all default parameter values: 
 BEGIN dbms_stats.gather_schema_stats('SH'); END;                               
 -- Also the non default parameters can be overriden by setting 
 'PREFERENCE_OVERRIDES_PARAMETER' preference.                                   
 -- Overriding non default parameters and preferences for all tables in the 
 system and to use dbms_stats for gathering statistics:                         
 begin dbms_stats.set_global_prefs('PREFERENCE_OVERRIDES_PARAMETER', 'TRUE');   
 end;                                                                           
 -- Overriding non default parameters and preferences for 'SH.SALES': 
 begin dbms_stats.set_table_prefs('SH','SALES',                                 
 'PREFERENCE_OVERRIDES_PARAMETER', 'TRUE'); end;                                
 Rationale:  Using default parameter values for statistics gathering operations 
             is more efficient.                                                 
----------------------------------------------------
 Rule Name:         UseGatherSchemaStats                                        
 Rule Description:  Use gather_schema_stats procedure                           
 Finding:  There are 9 uses of GATHER_TABLE_STATS.                              
 Operation:                                                                                                                                                         
 gather_table_stats(ownname=>'SH', tabname=>'CONTRACTORS');                                                                                                         
 gather_table_stats(ownname=>'sh', tabname=>'customers');                                                                                                           
 gather_table_stats(ownname=>'SH', tabname=>'customers_test');                                                                                                      
 gather_table_stats(ownname=>'sh', tabname=>'SALES');                                                                                                               
 gather_table_stats(ownname=>'sh', tabname=>'costs', estimate_percent=>100);                                                                                        
 gather_table_stats(ownname=>'SH', tabname=>'PRODUCTS', method_opt=>'FOR COLUMNS PROD_SUBCATEGORY_ID SIZE 10');                                                     
 gather_table_stats(ownname=>'SH', tabname=>'COUNTRIES', estimate_percent=>100, method_opt=>'FOR COLUMNS COUNTRY_SUBREGION_ID SIZE 7');                             
 gather_table_stats(ownname=>'SH', tabname=>'SALES2');                                                                                                              
 gather_table_stats(ownname=>'SH', tabname=>'SALES_TRANSACTIONS_EXT', block_sample=>TRUE, method_opt=>'FOR ALL COLUMNS SIZE 1', granularity=>'ALL', cascade=>TRUE); 

 Recommendation:  Use GATHER_SCHEMA_STATS instead of GATHER_TABLE_STATS.        
 Example:                                                                       
 -- Gather statistics for 'SH' schema: 
 BEGIN dbms_stats.gather_schema_stats('SH'); END;                               
 Rationale:  GATHER_SCHEMA_STATS has more options available, including checking 
             for staleness and gathering statistics concurrently. Also it is    
             more maintainable for new tables added to the schema. If you only  
             want to gather statistics for certain tables in the schema,        
             specify them in the obj_filter_list parameter of                   
             GATHER_SCHEMA_STATS.                                               
----------------------------------------------------
 Rule Name:         AvoidAnalyzeTable                                           
 Rule Description:  Avoid using analyze table commands for statistics           
                    collection                                                  
 Finding:  There are 5 object(s) using "ANALYZE TABLE <table_name> [COMPUTE | ESTIMATE] STATISTICS" to gather statistics.                          
 Schema:                        
 OE                             
 Objects:                       
 CATEGORIES_TAB                 
 PRODUCT_REF_LIST_NESTEDTAB     
 PURCHASEORDER                  
 SUBCATEGORY_REF_LIST_NESTEDTAB 
 Schema:                        
 PM                             
 Objects:                       
 TEXTDOCS_NESTEDTAB             

 Recommendation:  Use GATHER_SCHEMA_STATS instead of ANALYZE TABLE statements   
                  to gather statistics.                                         
 Example:                                                                       
 -- Gathering statistics for tables with stale or no statistics in schema, SH: 
 exec dbms_stats.gather_schema_stats('SH', options => 'GATHER AUTO')            
 -- Also analyze can be redirected to use dbms_stats by setting 
 'PREFERENCE_OVERRIDES_PARAMETER' preference.                                   
 -- Overriding non default parameters and preferences for all tables in the 
 system and to use dbms_stats for gathering statistics:                         
 begin dbms_stats.set_global_prefs('PREFERENCE_OVERRIDES_PARAMETER', 'TRUE');   
 end;                                                                           
 -- Overriding non default parameters and preferences for 'SH.SALES': 
 begin dbms_stats.set_table_prefs('SH','SALES',                                 
 'PREFERENCE_OVERRIDES_PARAMETER', 'TRUE'); end;                                
 Rationale:  "ANALYZE TABLE <table_name> [COMPUTE | ESTIMATE] STATISTICS" is    
             obsolete and no longer supported.                                  
----------------------------------------------------
-------------------------------------------------------------------------------


PL/SQL procedure successfully completed.

18.2.1 Creating an Optimizer Statistics Advisor Task

DBMS_STATS.CREATE_ADVISOR_TASK Function is Optimizer Statistics Advisor Create a task . If you do not specify a task name , that Optimizer Statistics Advisor It will automatically generate a .

precondition : To execute this subroutine , You must have ADVISOR jurisdiction .

Be careful : This subroutine is executed with the privileges of the caller .

DECLARE
  v_tname VARCHAR2(32767);
  v_ret   VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  v_ret := DBMS_STATS.CREATE_ADVISOR_TASK(v_tname);
END;
/

Query created tasks :

col task_name for a20
col advisor_name for a30
SELECT TASK_NAME, ADVISOR_NAME, CREATED, STATUS FROM USER_ADVISOR_TASKS;
-- where task_name = 'OPT_ADV_TASK1';
TASK_NAME            ADVISOR_NAME                   CREATED   STATUS     
-------------------- ------------------------------ --------- -----------
OPT_ADV_TASK1        Statistics Advisor             12-JUN-22 INITIAL     

18.2.2 Listing Optimizer Statistics Advisor Tasks

DBA_ADVISOR_EXECUTIONS The view lists the execution of the optimizer statistics advisor task .

COL EXECUTION_NAME FORMAT a14

SELECT EXECUTION_NAME, EXECUTION_END, STATUS
FROM   DBA_ADVISOR_EXECUTIONS
WHERE  TASK_NAME = 'AUTO_STATS_ADVISOR_TASK'
ORDER BY 2;

EXECUTION_NAME EXECUTION STATUS     
-------------- --------- -----------
EXEC_1         27-JUL-21 COMPLETED  
EXEC_21        04-JUN-22 COMPLETED  
EXEC_42        05-JUN-22 COMPLETED  
EXEC_53        07-JUN-22 COMPLETED  
EXEC_73        09-JUN-22 COMPLETED  
EXEC_84        11-JUN-22 COMPLETED  

6 rows selected. 

18.2.3 Creating Filters for an Optimizer Advisor Task

Filters enable you to Optimizer Statistics Advisor Include or exclude objects from the task 、 Rules and actions .

18.2.3.1 About Filters for Optimizer Statistics Advisor

The filter is to use DBMS_STATS Restrict the optimizer statistics advisor task to a set of rules specified by the user 、 Mode or operation .

Filters are useful for including or excluding a specific set of results . for example , You can configure a consultant task to contain only sh Suggestions for patterns . Besides , You can exclude all violations of stale statistics rules . The main advantage of filters is the ability to ignore suggestions that you are not interested in , And reduce the cost of consulting tasks .

The easiest way to create a filter is to use the following... Alone or in combination DBMS_STATS The process :

  • CONFIGURE_ADVISOR_OBJ_FILTER
    Use this procedure to include or exclude a specified database schema or object . Object filters accept owner names and object names , Support for wildcards (%).

  • CONFIGURE_ADVISOR_RULE_FILTER
    Use this procedure to include or exclude specified rules . By inquiring V$STATS_ADVISOR_RULES Get rule name .

  • CONFIGURE_ADVISOR_OPR_FILTER
    Use this procedure to include or exclude specified DBMS_STATS operation . By inquiring DBA_OPTSTAT_OPERATIONS Get the of the operation ID And name .

For the above functions , You can specify the type of operation to apply the filter :EXECUTE、REPORT、SCRIPT and IMPLEMENT. You can also combine types , Such as EXECUTE + REPORT. Null Indicates that the filter is applicable to all types of consultant operations .

18.2.3.2 Creating an Object Filter for an Optimizer Advisor Task

DBMS_STATS.CONFIGURE_ADVISOR_OBJ_FILTER Function to create a rule filter for the specified optimizer statistics advisor task . This function returns a that contains the filter update value CLOB.

You can use any of the following basic strategies :

  • Include the results of all objects ( By default , Consider all objects ), Then exclude the result of the specified object .
  • The result of excluding all objects , Then include only the results of the specified object .

Use DBMS_STATS.CONFIGURE_ADVISOR_OBJ_FILTER function , You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .

Be careful : This subroutine is executed with the privileges of the caller .

Delete existing tasks :

DECLARE
  v_tname VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  DBMS_STATS.DROP_ADVISOR_TASK(v_tname);
END;
/

Create a file called sh_obj_filter The process of , Restrict specified tasks to sh Patterns in objects .

CREATE OR REPLACE PROCEDURE sh_obj_filter(p_tname IN VARCHAR2) IS
   v_retc CLOB;
BEGIN
   -- Filter out all objects that are not in the sh schema
   v_retc := DBMS_STATS.CONFIGURE_ADVISOR_OBJ_FILTER(
               task_name          => p_tname
             , stats_adv_opr_type => 'EXECUTE'
             , rule_name          => NULL
             , ownname            => NULL
             , tabname            => NULL
             , action             => 'DISABLE' );

   v_retc := DBMS_STATS.CONFIGURE_ADVISOR_OBJ_FILTER(
               task_name          => p_tname
             , stats_adv_opr_type => 'EXECUTE'
             , rule_name          => NULL
             , ownname            => 'SH'
             , tabname            => NULL
             , action             => 'ENABLE' );
END;
/
SHOW ERRORS

This is done by first excluding all , Then add SH Pattern implementation .

Create a file called opt_adv_task1 The task of , Then perform... For this task sh_obj_filter The process .

DECLARE
  v_tname VARCHAR2(32767);
  v_ret VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  v_ret   := DBMS_STATS.CREATE_ADVISOR_TASK(v_tname);
  sh_obj_filter(v_tname);
END;
/

DECLARE
  v_tname VARCHAR2(32767);
  v_ret   VARCHAR2(32767);
begin
  v_tname := 'opt_adv_task1';
  v_ret   := DBMS_STATS.EXECUTE_ADVISOR_TASK(v_tname);
END;
/

18.2.3.3 Creating a Rule Filter for an Optimizer Advisor Task

DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER Function to create a rule filter for the specified optimizer statistics advisor task . This function returns a that contains the filter update value CLOB.

You can use any of the following basic strategies :

  • Enable all rules ( All rules are enabled by default ), Then disable the specified rule .
  • Disable all rules , Then only the specified rules are enabled .

Use DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER function , You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .

Be careful : This subroutine is executed with the privileges of the caller .

By inquiring V$STATS_ADVISOR_RULES Get the name of the advisor rule .

SET LINESIZE 200
SET PAGESIZE 100
COL ID FORMAT 99
COL NAME FORMAT a35
COL DESCRIPTION FORMAT a80

SELECT RULE_ID AS ID, NAME, RULE_TYPE, DESCRIPTION 
FROM   V$STATS_ADVISOR_RULES
ORDER BY RULE_ID;

 ID NAME                                RULE_TYPE DESCRIPTION                                                                     
--- ----------------------------------- --------- --------------------------------------------------------------------------------
  0                                     SYSTEM                                                                                    
  1 UseAutoJob                          SYSTEM    Use Auto Job for Statistics Collection                                          
  2 CompleteAutoJob                     SYSTEM    Auto Statistics Gather Job should complete successfully                         
  3 MaintainStatsHistory                SYSTEM    Maintain Statistics History                                                     
  4 UseConcurrent                       SYSTEM    Use Concurrent preference for Statistics Collection                             
  5 UseDefaultPreference                SYSTEM    Use Default Preference for Stats Collection                                     
  6 TurnOnSQLPlanDirective              SYSTEM    SQL Plan Directives should not be disabled                                      
  7 AvoidSetProcedures                  OPERATION Avoid Set Statistics Procedures                                                 
  8 UseDefaultParams                    OPERATION Use Default Parameters in Statistics Collection Procedures                      
  9 UseGatherSchemaStats                OPERATION Use gather_schema_stats procedure                                               
 10 AvoidInefficientStatsOprSeq         OPERATION Avoid inefficient statistics operation sequences                                
 11 AvoidUnnecessaryStatsCollection     OBJECT    Avoid unnecessary statistics collection                                         
 12 AvoidStaleStats                     OBJECT    Avoid objects with stale or no statistics                                       
 13 GatherStatsAfterBulkDML             OBJECT    Do not gather statistics right before bulk DML                                  
 14 LockVolatileTable                   OBJECT    Statistics for objects with volatile data should be locked                      
 15 UnlockNonVolatileTable              OBJECT    Statistics for objects with non-volatile should not be locked                   
 16 MaintainStatsConsistency            OBJECT    Statistics of dependent objects should be consistent                            
 17 AvoidDropRecreate                   OBJECT    Avoid drop and recreate object seqauences                                       
 18 UseIncremental                      OBJECT    Statistics should be maintained incrementally when it is beneficial             
 19 NotUseIncremental                   OBJECT    Statistics should not be maintained incrementally when it is not beneficial     
 20 AvoidOutOfRange                     OBJECT    Avoid Out of Range Histogram endpoints                                          
 21 UseAutoDegree                       OBJECT    Use Auto Degree for statistics collection                                       
 22 UseDefaultObjectPreference          OBJECT    Use Default Object Preference for statistics collection                         
 23 AvoidAnalyzeTable                   OBJECT    Avoid using analyze table commands for statistics collection                    

24 rows selected. 

In this example , You know the statistics are out of date , Because the auto statistics job is not running . You wish to be named opt_adv_task1 Task to generate a report , But you don't want to confuse the recommendations about outdated Statistics .

COL NAME FORMAT a15
SELECT RULE_ID AS ID, NAME, RULE_TYPE, DESCRIPTION 
FROM   V$STATS_ADVISOR_RULES
WHERE  DESCRIPTION LIKE '%tale%'
ORDER BY RULE_ID;

 ID NAME            RULE_TYPE DESCRIPTION
--- --------------- --------- -----------------------------------------
 12 AvoidStaleStats OBJECT    Avoid objects with stale or no statistics

You use CONFIGURE_ADVISOR_RULE_FILTER Configure filters , Specify that task execution should exclude rules AvoidStaleStats, But follow all other rules :

VARIABLE b_ret CLOB
BEGIN
   :b_ret := DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER(
     task_name          => 'opt_adv_task1'
,    stats_adv_opr_type => 'EXECUTE'
,    rule_name          => 'AvoidStaleStats'
,    action             => 'DISABLE' );
END;
/

This example is the opposite of the previous example . You would like to name opt_adv_task1 Task generation report for , But just want to see suggestions about outdated Statistics .

VARIABLE b_ret CLOB
BEGIN
   :b_ret := DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER(
     task_name          => 'opt_adv_task1'
,    stats_adv_opr_type => 'EXECUTE'
,    rule_name          => null
,    action             => 'DISABLE' );
END;
/

BEGIN
   :b_ret := DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER(
     task_name          => 'opt_adv_task1'
,    stats_adv_opr_type => 'EXECUTE'
,    rule_name          => 'AvoidStaleStats'
,    action             => 'ENABLE' );
END;
/

18.2.3.4 Creating an Operation Filter for an Optimizer Advisor Task

DBMS_STATS.CONFIGURE_ADVISOR_OPR_FILTER Function to create an action filter for the specified optimizer statistics advisor task . This function returns a that contains the filter update value CLOB.

You can use any of the following basic strategies :

  • Disable all operations , Then only the specified actions are enabled .
  • Enable all actions ( All operations are enabled by default ), Then disable the specified operation .

DBA_OPTSTAT_OPERATIONS The view contains... For statistics related operations ID.

To use DBMS_STATS.CONFIGURE_ADVISOR_OPR_FILTER function , You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
    Be careful : This subroutine is executed with the privileges of the caller .
  • You must be the owner of the task .
  • To query DBA_OPTSTAT_OPERATIONS View , You must have SELECT ANY TABLE jurisdiction .

Query operation type .

SELECT DISTINCT(OPERATION) FROM DBA_OPTSTAT_OPERATIONS ORDER BY OPERATION;

OPERATION                                                       
----------------------------------------------------------------
create_extended_stats
delete_pending_stats
delete_table_stats
drop_extended_stats
gather_database_stats
gather_database_stats (auto)
gather_database_stats_model
gather_index_stats
gather_schema_stats
gather_table_stats
lock_table_stats
publish_pending_stats
purge_stats
restore_table_stats
set_index_stats
set_schema_prefs
set_table_prefs
set_table_stats
unlock_table_stats

19 rows selected. 

for example , To get SYS and sh All statistics collection operations for tables and indexes in the schema ID, Please use the following query :

SELECT ID 
FROM   DBA_OPTSTAT_OPERATIONS
WHERE  (  OPERATION = 'gather_table_stats'
          OR OPERATION = 'gather_index_stats')
AND    (  TARGET LIKE 'SH.%'
          OR TARGET LIKE 'SYS.%');

In this example , Your goal is to exclude hr Collection of table statistics in schema . User account stats Has been awarded DBA role 、ADVISOR Authority and SELECT ON DBA_OPTSTAT_OPERATIONS jurisdiction . You can perform the following steps :

--  Delete any named  opt_adv_task1  Existing tasks .
DECLARE
  v_tname VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  DBMS_STATS.DROP_ADVISOR_TASK(v_tname);
END;
/

--  Create a file called  opr_filter  The process of , This process configures a task to suggest all actions , Except for those who  hr  The operation of collecting statistics from tables in the schema .
CREATE OR REPLACE PROCEDURE opr_filter(p_tname IN VARCHAR2) IS
   v_retc CLOB;
BEGIN
   -- For all rules, prevent the advisor from operating 
   -- on the operations selected in the following query
   FOR rec IN 
     (SELECT ID FROM DBA_OPTSTAT_OPERATIONS WHERE OPERATION = 'gather_table_stats' AND TARGET LIKE 'HR.%')
   LOOP
     v_retc := DBMS_STATS.CONFIGURE_ADVISOR_OPR_FILTER(
                 task_name          => p_tname
               , stats_adv_opr_type => NULL
               , rule_name          => NULL
               , operation_id       => rec.id
               , action             => 'DISABLE');
   END LOOP;
END;
/
SHOW ERRORS

--  Create a file called  opt_adv_task1  The task of , Then perform... For this task  opr_filter  The process .
DECLARE
  v_tname VARCHAR2(32767);
  v_ret VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  v_ret   := DBMS_STATS.CREATE_ADVISOR_TASK(v_tname);
  opr_filter(v_tname);
END;
/

--  Perform tasks  opt_adv_task1.
DECLARE
  v_tname VARCHAR2(32767);
  v_ret   VARCHAR2(32767);
begin
  v_tname := 'opt_adv_task1';
  v_ret   := DBMS_STATS.EXECUTE_ADVISOR_TASK(v_tname);
END;
/

--  Print report 
SET LONG 1000000
COLUMN report FORMAT A200
SET LINESIZE 250
SET PAGESIZE 1000

SELECT DBMS_STATS.REPORT_ADVISOR_TASK(
         task_name      => 'opt_adv_task1'
       , execution_name => NULL
       , type           => 'TEXT'
       , section        => 'ALL' 
       ) AS report
FROM   DUAL;

18.2.4 Executing an Optimizer Statistics Advisor Task

DBMS_STATS.EXECUTE_ADVISOR_TASK Function is Optimizer Statistics Advisor Perform tasks . If you do not specify an execution name , that Optimizer Statistics Advisor It will automatically generate a .

The result of executing this task depends on the permissions of the executing user :

  • SYSTEM level
    Only with ANALYZE ANY and ANALYZE ANY DICTIONARY Only users with permissions can perform this task on system level rules .

  • Operation level
    The result depends on the following permissions :

    • At the same time ANALYZE ANY and ANALYZE ANY DICTIONARY Users with permission can perform this task for all statistical operations .
    • have ANALYZE ANY Permission but not ANALYZE ANY DICTIONARY Users with permissions can set and divide SYS Perform this task for any mode related statistical operations other than .
    • have ANALYZE ANY DICTIONARY Permission but no ANALYZE ANY Users with permissions can be targeted with their own patterns and SYS The mode related statistical operations perform this task .
    • Neither ANALYZE ANY either ANALYZE ANY DICTIONARY Users with permissions can only perform this operation on statistical operations related to their own schema .
  • Object level
    Users can perform this task on any object for which they have permission to collect statistics .

This task has the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .
  • If you specify an execution name , Then this name must not conflict with the existing execution .
    Be careful : This subroutine is executed with the privileges of the caller .

for example :

DECLARE
  v_tname VARCHAR2(32767);
  v_ret   VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  v_ret := DBMS_STATS.EXECUTE_ADVISOR_TASK(v_tname);
END;
/

COL TASK_NAME FOR A30
COL TYPE FOR A12
SELECT TASK_NAME, EXECUTION_NAME,
       EXECUTION_END, EXECUTION_TYPE AS TYPE, STATUS 
FROM   USER_ADVISOR_EXECUTIONS;

TASK_NAME                      EXECUTION_NAME EXECUTION TYPE         STATUS     
------------------------------ -------------- --------- ------------ -----------
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_61        08-JUN-22 SPM EVOLVE   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_71        09-JUN-22 SPM EVOLVE   COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_84        11-JUN-22 STATISTICS   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_11        04-JUN-22 SPM EVOLVE   COMPLETED  
SYS_AUTO_SPCADV103050809062022 EXEC_72        09-JUN-22              COMPLETED  
SYS_AUTO_SPCADV259261511062022 EXEC_76        11-JUN-22              COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_106       12-JUN-22 SPM EVOLVE   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_41        05-JUN-22 SPM EVOLVE   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_51        07-JUN-22 SPM EVOLVE   COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_53        07-JUN-22 STATISTICS   COMPLETED  
OPT_ADV_TASK1                  EXEC_109       12-JUN-22 STATISTICS   COMPLETED  
MY_TASK                        EXEC_95        12-JUN-22 STATISTICS   COMPLETED  
OPT_ADV_TASK1                  EXEC_105       12-JUN-22 STATISTICS   COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_21        04-JUN-22 STATISTICS   COMPLETED  
SYS_AUTO_SPCADV256451504062022 EXEC_32        04-JUN-22              COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_73        09-JUN-22 STATISTICS   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_75        11-JUN-22 SPM EVOLVE   COMPLETED  
SYS_AUTO_SPCADV116051812062022 EXEC_107       12-JUN-22              COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_108       12-JUN-22 STATISTICS   COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_1         27-JUL-21 STATISTICS   COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_31        04-JUN-22 SPM EVOLVE   COMPLETED  
AUTO_STATS_ADVISOR_TASK        EXEC_42        05-JUN-22 STATISTICS   COMPLETED  
SYS_AUTO_SPCADV108210807062022 EXEC_52        07-JUN-22              COMPLETED  
SYS_AUTO_SPCADV149200608062022 EXEC_62        08-JUN-22              COMPLETED  
SYS_AUTO_SPM_EVOLVE_TASK       EXEC_74        11-JUN-22 SPM EVOLVE   INTERRUPTED

25 rows selected. 

18.2.5 Generating a Report for an Optimizer Statistics Advisor Task

DBMS_STATS.REPORT_ADVISOR_TASK Function to generate a report for the optimizer statistics advisor task .

The report contains the following sections :

  • General information
    This section describes the task name 、 Execution name 、 Creation date and modification date .
  • General information
    This section summarizes the findings and the rules that the findings violate .
  • Find out
    Each result section lists the relevant rules and results . If the consultant has a recommendation , Describe and recommend . In some cases , There are reasons for the suggestion .

automation Optimizer Statistics Advisor The name of the task is AUTO_STATS_ADVISOR_TASK. If you follow an automated workflow , Then you only need to query the automatically generated report .

To use DBMS_STATS.REPORT_ADVISOR_TASK Function to generate a report , You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .
    Be careful : This subroutine is executed with the privileges of the caller .

The result of executing this task depends on the permissions of the executing user :

  • SYSTEM Level
    Only with ANALYZE ANY and ANALYZE ANY DICTIONARY Only users with permissions can perform this task on system level rules .

  • Operation level
    The result depends on the following permissions :

    • At the same time ANALYZE ANY and ANALYZE ANY DICTIONARY Users with permission can perform this task for all statistical operations .
    • have ANALYZE ANY Permission but not ANALYZE ANY DICTIONARY Users with permissions can set and divide SYS Perform this task for any mode related statistical operations other than .
    • have ANALYZE ANY DICTIONARY Permission but no ANALYZE ANY Users with permissions can be targeted with their own patterns and SYS The mode related statistical operations perform this task .
    • Neither ANALYZE ANY either ANALYZE ANY DICTIONARY Users with permissions can only perform this operation on statistical operations related to their own schema .
  • Object level
    Users can perform this task on any object for which they have permission to collect statistics .

for example :

SET LINESIZE 3000
SET LONG 500000
SET PAGESIZE 0
SET LONGCHUNKSIZE 100000
SELECT DBMS_STATS.REPORT_ADVISOR_TASK('AUTO_STATS_ADVISOR_TASK', NULL,
       'TEXT', 'ALL', 'ALL') AS REPORT 
FROM   DUAL;

18.2.6 Implementing Optimizer Statistics Advisor Recommendations

You can use DBMS_STATS.IMPLEMENT_ADVISOR_TASK Automatically implement all recommendations , Or use DBMS_STATS.SCRIPT_ADVISOR_TASK Generate editable scripts .

18.2.6.1 Implementing Actions Recommended by Optimizer Statistics Advisor

DBMS_STATS.IMPLEMENT_ADVISOR_TASK Function to implement recommendations for the specified optimizer statistics advisor task . If you do not specify an execution name , that Optimizer Statistics Advisor The most recent execution will be used .

The easiest way to implement the recommendations is to use DBMS_STATS.IMPLEMENT_ADVISOR_TASK. under these circumstances , No need to generate scripts . You can specify that consultants ignore existing filters (level=>‘ALL’) Or use default values , It respects existing filters (level=>‘TYPICAL’).

To use DBMS_STATS.IMPLEMENT_ADVISOR_TASK, You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .
    Be careful : This subroutine is executed with the privileges of the caller .

The permission here is omitted .

VARIABLE b_ret CLOB
DECLARE
  v_tname VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  :b_ret := DBMS_STATS.IMPLEMENT_ADVISOR_TASK(v_tname);
END;
/


--  perhaps , Print  XML  Output to confirm the implemented operation .
SET LONG 10000
SELECT XMLType(:b_ret) AS imp_results FROM DUAL;

<implementation_results><rule NAME="AVOIDSETPROCEDURES"><implemented>yes</implemented></rule><rule NAME="USEDEFAULTPARAMS"><implemented>yes</implemented></rule><rule NAME="USEGATHERSCHEMASTATS"><implemented>yes</implemented></rule><rule NAME="AVOIDANALYZETABLE"><implemented>yes</implemented></rule><rule NAME="AVOIDSETPROCEDURES"><implemented>yes</implemented></rule><rule NAME="USEDEFAULTPARAMS"><implemented>yes</implemented></rule><rule NAME="USEGATHERSCHEMASTATS"><implemented>yes</implemented></rule><rule NAME="AVOIDANALYZETABLE"><implemented>yes</implemented></rule><rule NAME="AVOIDSETPROCEDURES"><implemented>yes</implemented></rule><rule NAME="USEDEFAULTPARAMS"><implemented>yes</implemented></rule><rule NAME="USEGATHERSCHEMASTATS"><implemented>yes</implemented></rule><rule NAME="AVOIDANALYZETABLE"><implemented>yes</implemented></rule></implementation_results>


18.2.6.2 Generating a Script Using Optimizer Statistics Advisor

DBMS_STATS.SCRIPT_ADVISOR_TASK Function to generate an editable script , It contains recommendations for specifying optimizer statistics advisor tasks .

And IMPLEMENT_ADVISOR_TASK Different ,SCRIPT_ADVISOR_TASK Generate a script , You can edit it before execution . The output script contains comments and executable code . And IMPLEMENT_ADVISOR_TASK equally , You can specify that consultants ignore existing filters (level=>‘ALL’) Or use default values , It respects existing filters (level=>‘TYPICAL’). You can specify that this function treats the script as CLOB And file return , Or just return CLOB.

To use DBMS_STATS.SCRIPT_ADVISOR_TASK function , You must meet the following prerequisites :

  • To execute this subroutine , You must have ADVISOR jurisdiction .
  • You must be the owner of the task .
    Be careful : This subroutine is executed with the privileges of the caller .

The permission here is omitted .

for example :

VARIABLE b_script CLOB
DECLARE
  v_tname VARCHAR2(32767);
BEGIN
  v_tname := 'opt_adv_task1';
  :b_script := DBMS_STATS.SCRIPT_ADVISOR_TASK(v_tname);
END;
/

DECLARE
  v_len    NUMBER(10);
  v_offset NUMBER(10) :=1;
  v_amount NUMBER(10) :=10000;
BEGIN
  v_len := DBMS_LOB.getlength(:b_script);
  WHILE (v_offset < v_len)
  LOOP
    DBMS_OUTPUT.PUT_LINE(DBMS_LOB.SUBSTR(:b_script,v_amount,v_offset));
    v_offset := v_offset + v_amount;
  END LOOP;
END;
/
原网站

版权声明
本文为[dingdingfish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122129527290.html