一个sql,通过spm固定它的执行计划,可以通过dbms_spm.load_plans_from_cursor_cache实现。也可以通地此功能在不修改原sql的情况下对其加hint来固定执行计划。
db version:oracle 11.2.0.4
os:centos 6.6
例如:
原sql走索引:
select * from scott.tb_spm where object_id=10;
想通过加hint让其走全表扫描:
select /*+full(tb_spm)*/* from scott.tb_spm where object_id=10;
在v$sql中查询出,原sql的sql_id=064qcdmgt6thw,加hint的sql的sql_id=ahdtbgvsd3bht,plan_hash_value=970476072。
执行以下:
declare
cnt number;
v_sql clob;
begin
–得到原语句sql文本
select sql_fulltext into v_sql from v$sql where sql_id = ‘064qcdmgt6thw’ and rownum=1;
–用加hint的sql的sql_id和plan_hash_value,来固定原语句的sql
cnt := dbms_spm.load_plans_from_cursor_cache(sql_id => ‘ahdtbgvsd3bht’,
plan_hash_value => 970476072,
sql_text => v_sql);
end;
这样就将加hint的执行计划固定在原语句上。执行原语句,在v$sql的plan_hash_value列和sql_plan_baseline列来确认是否固定。
测试中发现,一些含有绑定变量的sql,用常量的sql的sql_id和plan_hash_value无法固定,此时可以尝试使用execute immediate来生成含有绑定变量的sql。
例如:
declare
v_sql varchar2(3000);
begin
v_sql := ‘select /*+full(tb_spm)*/* from scott.tb_spm where object_id=:1’;
execute immediate v_sql
using 10;
end;
或
var v number;
exec :v :=10
select /*+full(tb_spm)*/* from scott.tb_spm where object_id=:v;