绑定执行计划sql_plan_baseline

时间:2022-07-22 04:31:32

--由于生产环境执行的sql变化较快,版本发布比较频繁,造成sql的执行计划不是很稳定,经常会有一些性能很查的sql出现
--对于这些sql,我们可以使用sql_plan_baseline对执行计划进行绑定,从而使执行计划固定下来
--前提是sql最好使用绑定变量,就算有的没有绑定变量,确定字段的值不会改变才行,因为是针对sql_id进行的绑定,如果sql文本改变,绑定也就无意义了

具体步骤:
--1、找到问题sql,如果查询sql的执行计划,如果有合适的执行计划,直接进行绑定
--查询sql执行计划对应的PLAN_HASH_VALUE
SELECT DISTINCT(PLAN_HASH_VALUE) FROM V$SQL_PLAN t WHERE SQL_ID = '010cv4dvf6swv' and child_number='0'
--绑定好的执行计划:
declare
  l_pls number;
begin
  l_pls := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(sql_id  => '524wzct86gu1d',
                                                 plan_hash_value => 2554538542,
                                                 enabled         => 'YES');
end;
/


2、如果没有合适的执行计划,就要通过自己分析,运用一些hint让sql产生比较好的执行计划
--需要绑定的sql
--oldSQL(id PLAN_HASH_VALUE)
524wzct86gu1d
2554538542

--新的sql
--newSQL(id PLAN_HASH_VALUE)
010cv4dvf6swv
756701203
--查询新的执行计划的sql_id
select * from v$sql where sql_text like '%zhruoyu%' --通过在hint中加一下特殊字符来查找

---新建制定SQLID的BASELINE根据old_sql id,PLAN_HASH_VALUE
declare
  l_pls number;
begin
  l_pls := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(sql_id    => '524wzct86gu1d',
                                                 plan_hash_value => 2554538542,
                                                 enabled         => 'NO');  --注意这里是no
end;
/

---确定原始执行计划的 sql_handle
select sql_handle, plan_name, origin, enabled, accepted,fixed,creator,optimizer_cost,sql_text
from dba_sql_plan_baselines where origin = 'MANUAL-LOAD' order by created desc
 
SQL_HANDLE:SQL_66108ad9595208fc                                     
PLAN_NAME:SQL_PLAN_6c44av5cp427w65e519aa


---与正确的执行计划做关联
declare
  l_pls number;
begin
  l_pls := DBMS_SPM.load_plans_from_cursor_cache(sql_id          => '010cv4dvf6swv', -- new_SQL_ID'
                                                 plan_hash_value => 756701203, --new_plan_hash_value
                                                 sql_handle      => 'SQL_66108ad9595208fc' --OLD_handle
                                                 );
end;
/

---删除错误的执行计划
declare
  l_pls number;
begin
  l_pls := DBMS_SPM.DROP_SQL_PLAN_BASELINE(sql_handle => 'SQL_66108ad9595208fc', --sql_handle_for_original
                                           plan_name  => 'SQL_PLAN_6c44av5cp427w65e519aa' --sql_plan_name_for_original                                       
                                           );
end;
/

--检查一下
select sql_handle, plan_name, origin, enabled, accepted,fixed,creator,optimizer_cost,sql_text
from dba_sql_plan_baselines where origin = 'MANUAL-LOAD' and sql_handle='SQL_66108ad9595208fc'

--完成