---
title: "【转】SQL Profiles"
author: "jayghost"
date: "2013-12-12T16:13:10Z"
tags: []
categories: ["数据库"]
slug: "sql-profiles"
draft: false
lastmod: "2013-12-12T16:13:10Z"
id: 1988637
url: "https://wujay.iteye.com/blog/1988637"
---

转自：[http://www.laoxiong.net/sql-profiles-part.html](http://www.laoxiong.net/sql-profiles-part.html)

 

Oracle 11g从发布到现在，也有几个年头了。而在国内来说，Oracle 10g仍然是主流，甚至一些电信运营商的核心系统仍然在使用9i。作为Oracle 10g的一项新特性，SQL Profiles被使用得并不太多。不管是在论坛、个人的BLOG还是其他一些地方，SQL Profiles的介绍也相对较少。对我个人来说，已经在多个优化场合中使用SQL Profiles，在这里向大家介绍SQL Profiles，就是希望能够了解Oracle数据库的这一功能。

SQL Profiles可以说是Outlines的进化。Outlines能够实现的功能SQL Profiles也完全能够实现，而SQL Profiles具有Outlines不具备的优化，个人认为最重要的有2点：

- SQL Profiles更容易生成、更改和控制。
- SQL Profiles在对SQL语句的支持上做得更好，也就是适用范围更广。

关于这2方面的优点，我后面会详细地阐述。

现在我在使用Outlines的场合，均使用SQL Profiles来替代。有一次准备对1条SQL语句使用Outline进行执行计划的稳定，结果使用Outline之后，系统出现大量的library cache latch的争用，不得不关闭Outline的使用，但是改用SQL Profiles不再有这个问题。这或许是个BUG，不过既然能用SQL Profiles代替，也就没再深入去研究这个问题。

使用SQL Profiles无非是两个目的：

- 锁定或者说是稳定执行计划。
- 在不能修改应用中的SQL的情况下使SQL语句按指定的执行计划运行。

那么SQL Profile到底是什么？在我看来，SQL Profile就是为某一SQL语句提供除了系统统计信息、对象（表和索引等）统计信息之外的其他信息，比如运行环境、额外的更准确的统计信息，以帮助优化器为SQL语句选择更适合的执行计划。这些说法显得比较枯燥，还是来看看下面的测试。

首先建2个测试表：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; create table t1 as select object\_id,object\_name from dba\_objects where rownum&lt;=50000;
02. 表已创建。
03. SQL&gt; create table t2 as select * from dba\_objects;
04. 表已创建。
05. SQL&gt; create index t2\_idx on t2(object\_id);
06. 索引已创建。
07. SQL&gt; exec dbms\_stats.gather\_table\_stats(user,'t1',cascade=&gt;true,method\_opt=&gt;'for all columns size 1');
08. PL/SQL 过程已成功完成。
09. SQL&gt; exec dbms\_stats.gather\_table\_stats(user,'t2',cascade=&gt;true,method\_opt=&gt;'for all columns size 1');
10. PL/SQL 过程已成功完成。

然后看看下面这一条SQL：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; select t1.\*,t2.owner from t1,t2 where t1.object\_name like '%T1%' and t1.object\_id=t2.object\_id;
02. 已选择29行。
03. 执行计划
04. \----------------------------------------------------------
05. Plan hash value: 1838229974
06. \---------------------------------------------------------------------------
07. | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
08. \---------------------------------------------------------------------------
09. |   0 | SELECT STATEMENT   |      |  2498 | 99920 |   219   (4)| 00:00:03 |
10. |*  1 |  HASH JOIN         |      |  2498 | 99920 |   219   (4)| 00:00:03 |
11. |*  2 |   TABLE ACCESS FULL| T1   |  2498 | 72442 |    59   (6)| 00:00:01 |
12. |   3 |   TABLE ACCESS FULL| T2   | 49954 |   536K|   159   (2)| 00:00:02 |
13. \---------------------------------------------------------------------------
14. Predicate Information (identified by operation id):
15. \---------------------------------------------------
16. 1 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
17. 2 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
18. 统计信息
19. \----------------------------------------------------------
20. 0  recursive calls
21. 0  db block gets
22. 932  consistent gets
23. 0  physical reads
24. 0  redo size
25. 1352  bytes sent via SQL\*Net to client
26. 385  bytes received via SQL\*Net from client
27. 2  SQL\*Net roundtrips to/from client
28. 0  sorts (memory)
29. 0  sorts (disk)
30. 29  rows processed

这里省略了SELECT出来的具体数据，但是我们关心的是返回的结果行数、执行计划以及逻辑读这些信息。  
首先从执行计划可以看到，这条SQL语句在2个表上都是全表扫描。在第1个表T1上，有 like ‘%T1%’这样的条件，导致只能全表扫描，这没有问题。但是第2个表，也是全表扫描，这里有没有问题呢？或者说是有没有优化的余地，答案显然是肯定的。  
这里的问题在于执行计划ID=1的那一行，Oracle优化器评估T1 like ‘%T1%’返回的结果行数为2498行，即T1表总行数的5%，如果2个表采用index range scan+nested loop连接，oracle评估的成本会高于full table scan+hash join。下面可以看到Oracle优化器评估的index range\_scan+nested loop的成本：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; explain plan for select /\*+ use\_nl(t1 t2) index(t2) \*/ t1.\*,t2.owner
02. from t1,t2
03. where t1.object\_name like '%T1%'
04. and t1.object\_id=t2.object\_id;
05. 已解释。
06. SQL&gt; @showplan
07. PLAN\_TABLE\_OUTPUT
08. \--------------------------------------------------------------------------------------
09. Plan hash value: 3787413387
10. \--------------------------------------------------------------------------------------
11. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
12. \--------------------------------------------------------------------------------------
13. |   0 | SELECT STATEMENT            |        |  2498 | 99920 |  5061   (1)| 00:01:01 |
14. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
15. |   2 |   NESTED LOOPS              |        |  2498 | 99920 |  5061   (1)| 00:01:01 |
16. |*  3 |    TABLE ACCESS FULL        | T1     |  2498 | 72442 |    59   (6)| 00:00:01 |
17. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
18. \--------------------------------------------------------------------------------------
19. Predicate Information (identified by operation id):
20. \---------------------------------------------------
21. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
22. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")

从执行计划可以看到Oracle优化器评估的成本为5061，远远高于原来的219。  
但是实际的逻辑读是多少呢？

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. 统计信息
02. \----------------------------------------------------------
03. 0  recursive calls
04. 0  db block gets
05. 290  consistent gets
06. 0  physical reads
07. 0  redo size
08. 1352  bytes sent via SQL\*Net to client
09. 385  bytes received via SQL\*Net from client
10. 2  SQL\*Net roundtrips to/from client
11. 0  sorts (memory)
12. 0  sorts (disk)
13. 29  rows processed

加了HINT之后实际的逻辑读只有290，低于原始SQL的932。所以这里可以看出来，由于Oracle优化器过高地估计了T1表经过like操作过滤返回的行数，也就过高地估计了nest loop的成本，最终也就选择了不是最优的执行计划。

下面我们用Oracle的SQL Tuning Advisor来尝试这条SQL：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; var tuning\_task varchar2(100);
02. SQL&gt; DECLARE
03. 2    l\_sql\_id v$session.prev\_sql\_id%TYPE;
04. 3    l\_tuning\_task VARCHAR2(30);
05. 4  BEGIN
06. 5    l\_sql\_id:='4zbqykx89yc8v';
07. 6    l\_tuning\_task := dbms\_sqltune.create\_tuning\_task(sql\_id =&gt; l\_sql\_id);
08. 7    :tuning\_task:=l\_tuning\_task;
09. 8    dbms\_sqltune.execute\_tuning\_task(l\_tuning\_task);
10. 9    dbms\_output.put\_line(l\_tuning\_task);
11. 10  END;
12. 11  /
13. 任务\_74
14. PL/SQL 过程已成功完成。
15. SQL&gt; print tuning\_task;
16. TUNING\_TASK
17. \---------------------------------------------------------------------------------------------------------
18. 任务\_74
19. SQL&gt; SELECT dbms\_sqltune.report\_tuning\_task(:tuning\_task) FROM dual;
20. DBMS\_SQLTUNE.REPORT\_TUNING\_TASK(:TUNING\_TASK)
21. \--------------------------------------------------------------------------------
22. GENERAL INFORMATION SECTION
23. \-------------------------------------------------------------------------------
24. Tuning Task Name                  : 任务\_74
25. Tuning Task Owner                 : TEST1
26. Scope                             : COMPREHENSIVE
27. Time Limit(seconds)               : 1800
28. Completion Status                 : COMPLETED
29. Started at                        : 12/15/2010 09:56:02
30. Completed at                      : 12/15/2010 09:56:03
31. Number of SQL Profile Findings    : 1
32. \-------------------------------------------------------------------------------
33. Schema Name: TEST1
34. SQL ID     : 4zbqykx89yc8v
35. SQL Text   : select t1.\*,t2.owner from t1,t2 where t1.object\_name like '%T1%'
36. and t1.object\_id=t2.object\_id
37. \-------------------------------------------------------------------------------
38. FINDINGS SECTION (1 finding)
39. \-------------------------------------------------------------------------------
40. 1- SQL Profile Finding (see explain plans section below)
41. \--------------------------------------------------------
42. 为此语句找到了性能
43. Recommendation (estimated benefit: 46.62%)
44. \------------------------------------------
45. -考虑接受推荐的 SQL
46. executedbms\_sqltune.accept\_sql\_profile(task\_name =&gt; '任务\_74', replace =
47. TRUE);
48. \-------------------------------------------------------------------------------
49. EXPLAIN PLANS SECTION
50. \-------------------------------------------------------------------------------
51. 1- Original With Adjusted Cost
52. \------------------------------
53. Plan hash value: 1838229974
54. \---------------------------------------------------------------------------
55. | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
56. \---------------------------------------------------------------------------
57. |   0 | SELECT STATEMENT   |      |    29 |  1160 |   219   (4)| 00:00:03 |
58. |*  1 |  HASH JOIN         |      |    29 |  1160 |   219   (4)| 00:00:03 |
59. |*  2 |   TABLE ACCESS FULL| T1   |    29 |   841 |    59   (6)| 00:00:01 |
60. |   3 |   TABLE ACCESS FULL| T2   | 49954 |   536K|   159   (2)| 00:00:02 |
61. \---------------------------------------------------------------------------
62. Predicate Information (identified by operation id):
63. \---------------------------------------------------
64. 1 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
65. 2 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
66. 2- Using SQL Profile
67. \--------------------
68. Plan hash value: 3787413387
69. \--------------------------------------------------------------------------------------
70. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
71. \--------------------------------------------------------------------------------------
72. |   0 | SELECT STATEMENT            |        |    29 |  1160 |   117   (3)| 00:00:02 |
73. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
74. |   2 |   NESTED LOOPS              |        |    29 |  1160 |   117   (3)| 00:00:02
75. |
76. |*  3 |    TABLE ACCESS FULL        | T1     |    29 |   841 |    59   (6)| 00:00:01 |
77. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
78. \--------------------------------------------------------------------------------------
79. Predicate Information (identified by operation id):
80. \---------------------------------------------------
81. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
82. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
83. \-------------------------------------------------------------------------------

上面代码中的sql\_id是从v$sql来，对应的是没有加hint的SQL。  
结果看起来非常棒，SQL Tuning Advisor为我们找到了理想的执行计划，T1表上经过谓词过滤后返回的行数评估为29，相当地精确。我们要做的就是Accept SQL Profile，接受这个SQL Profile。

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

1. SQL&gt; execute dbms\_sqltune.accept\_sql\_profile(task\_name =&gt; :tuning\_task,replace =&gt; TRUE,force\_match=&gt;true);
2. PL/SQL 过程已成功完成。

那么我们再执行其他的类似SQL看看：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; select t1.\*,t2.owner from t1,t2 where t1.object\_name like '%T2%' and t1.object\_id=t2.object\_id;
02. 已选择77行。
03. 执行计划
04. \----------------------------------------------------------
05. Plan hash value: 3787413387
06. \--------------------------------------------------------------------------------------
07. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
08. \--------------------------------------------------------------------------------------
09. |   0 | SELECT STATEMENT            |        |    29 |  1160 |   117   (3)| 00:00:02 |
10. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
11. |   2 |   NESTED LOOPS              |        |    29 |  1160 |   117   (3)| 00:00:02 |
12. |*  3 |    TABLE ACCESS FULL        | T1     |    29 |   841 |    59   (6)| 00:00:01 |
13. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
14. \--------------------------------------------------------------------------------------
15. Predicate Information (identified by operation id):
16. \---------------------------------------------------
17. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T2%')
18. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
19. Note
20. \-----
21. - SQL profile "SYS\_SQLPROF\_014b39f084c88000" used for this statement
22. 统计信息
23. \----------------------------------------------------------
24. 1  recursive calls
25. 0  db block gets
26. 343  consistent gets
27. 0  physical reads
28. 0  redo size
29. 2840  bytes sent via SQL\*Net to client
30. 385  bytes received via SQL\*Net from client
31. 2  SQL\*Net roundtrips to/from client
32. 0  sorts (memory)
33. 0  sorts (disk)
34. 77  rows processed

这一次，尽管我们更改了LIKE 后面的值，但是执行计划与SQL Tuning Advisor产生的执行计划完全一样。从执行计划的”Note“一节也可以看到，SQL Profile起作用了。SQL Profile的名字为”SYS\_SQLPROF\_014b39f084c88000″。

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

1. SQL&gt; select name,category,signature,type,status,force\_matching from dba\_sql\_profiles;
2. NAME                           CATEGORY                                   SIGNATURE TYPE      STATUS  FOR
3. ------------------------------ ------------------------------ --------------------- --------- ---------- ---
4. SYS\_SQLPROF\_014b39f084c88000   DEFAULT                          3960696072677096522 MANUAL    ENABLED    YES

一些复杂的SQL，我经常会先通过SQL Tuning Advisor来分析一下，看能不能让Oracle自已找出一个更好的执行计划。

我们来看看，SQL Profiles实际上是些什么：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

1. SQL&lt; select * from sys.sqlprof$attr;
2. SIGNATURE CATEGORY                            ATTR# ATTR\_VAL
3. --------------------- ------------------------------ ---------- ----------------------------------------
4. 3960696072677096522 DEFAULT                                 1 OPT\_ESTIMATE(@"SEL$1", TABLE, "T1"@"SEL$
5. 1", SCALE\_ROWS=0.01161091426)

从sys.sqlprof$attr这个数字字典里面，我们可以看到两样东西：signature和attr。  
signature是什么？可以理解为与sql\_id、sql\_hash\_value类似的值，用来标识SQL。在10g以上的版本中，查看v$sql的定义就可以发现2列：exact\_matching\_signature、force\_matching\_signature。通过下面的数据可以看出区别：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; select rownum,a.* from
02. (select exact\_matching\_signature,force\_matching\_signature,plan\_hash\_value,sql\_text
03. from v$sql where sql\_text like '%/\*%xjs%' and sql\_text not like '%v$sql%' order by 1) a;
04. ROWNUM EXACT\_MATCHING\_SIGNATURE FORCE\_MATCHING\_SIGNATURE PLAN\_HASH\_VALUE SQL\_TEXT
05. ---------- ------------------------ ------------------------ --------------- --------------------------------------------------
06. 1      3939730931515200254     17443893418101517951      3617692013 select /* xjs \*/ object\_name    from T1 where obje
07. ct\_name='t1'
08. 2     10964210455693560558     11097449316038436385      3836375644 select /* xjs \*/ object\_name    from T1 where rown
09. um&lt;=3
10. 3     10964210455693560558     11097449316038436385      3836375644 select /* xjs   \*/ object\_name    from T1 where ro
11. wnum&lt;=3
12. 4     11217690300719901571       354482119692997204      3836375644 select /* xjs \*/ 2 from t1 where rownum&lt;=1
13. 5     11974975582747367847       354482119692997204      3836375644 select /* xjs \*/ 1 from t1 where rownum&lt;=1
14. 6     12941882703651921406     17443893418101517951      3617692013 select /* xjs \*/ object\_name    from T1 where obje
15. ct\_name='T1'
16. 7     17986178357953662359     11097449316038436385      3836375644 select /* xjs \*/ object\_name    from T1 where rown
17. um&lt;=1
18. 8     17986178357953662359     11097449316038436385      3836375644 select /* xjs \*/ OBJECT\_NAME from T1 where rownum&lt;
19. =1
20. 9     17986178357953662359     11097449316038436385      3836375644 SELECT /* xjs \*/ object\_name    from T1 where rown
21. um&lt;=1
22. 10     17986178357953662359     11097449316038436385      3836375644 select /* xjs \*/ object\_name from t1 where rownum&lt;
23. =1

从上面的数据可以看出：

- 第2、3条SQL的exact\_matching\_signature相同，第7、8、9、10条SQL的exact\_matching\_signature相同。
- 第2、3条SQL的force\_matching\_signature相同，第4、5条SQL的force\_matching\_signature相同，第7、8、9、10条的SQL的force\_matching\_signature相同。第1、6条SQL的force\_matching\_signature相同

有如下的结论：**对SQL语句，去掉重复的空格（不包括字符常量），将大小写转换成相同，比如均为大写（不包括字符常量）后，如果SQL相同，那么SQL语句的exact\_matching\_signature就是相同的。对SQL语句，去掉重复的空格（不包括字符常量），将大小写转换成相同，比如均为大写（不包括字符常量），然后去掉SQL中的常量，如果SQL相同，那么SQL语句的force\_matching\_signature就是相同的。**但是例外的情况是：如果SQL中有绑定变量，force\_matching\_signature就会与exact\_matching\_signature一样的生成标准。

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; select rownum,a.* from
02. (select exact\_matching\_signature,force\_matching\_signature,plan\_hash\_value,sql\_text
03. from v$sql where sql\_text like '%/\*%xjs2%' and sql\_text not like '%v$sql%' order by 1) a;
04. ROWNUM EXACT\_MATCHING\_SIGNATURE FORCE\_MATCHING\_SIGNATURE PLAN\_HASH\_VALUE SQL\_TEXT
05. ---------- ------------------------ ------------------------ --------------- --------------------------------------------------
06. 1      5363536431331905229      5363536431331905229      3836375644 select /* xjs2 \*/ object\_name    from T1 where obj
07. ect\_name='T1' and rownum&lt;=:rn
08. 2      5363536431331905229      5363536431331905229      3836375644 select /* xjs2 \*/ object\_name    from t1 where obj
09. ect\_name='T1' and rownum&lt;=:rn
10. 3     12992689086515482106     12992689086515482106      3836375644 select /* xjs2 \*/ object\_name    from t1 where obj
11. ect\_name='T2' and rownum&lt;=:rn

可以看到，现在exact\_matching\_signature与force\_matching\_signature完全一样了。  
从force\_matching\_signature的特性，我们可以想到一个用途，用于查找没有使用绑定变量的SQL语句，类似于使用plan\_hash\_value来查找。

回到前面，accept\_sql\_profile这个过程，force\_match参数设为TRUE，那么dba\_sql\_profiles中的signature则是由SQL的force\_matching\_signature而来，否则便是exact\_matching\_signature。对于Outlines来说，则只能是exact\_matching\_signature。从这个角度上讲，Sql Profiles比Outlines的使用范围更广，因为Sql profiles对没有使用绑定变量的SQL也支持得很好。值得注意的是，Sql profiles的force\_match属性是不能更改的，只能在创建时指定，如果要更改，则只能重新创建改Sql Profile。

下面来看看sys.sqlprof$attr数据字典。这里面没有SQL Profile的名字，而是用的sql的signature。大家从attr\_val的结果发现了什么？

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

1. OPT\_ESTIMATE(@"SEL$1", TABLE, "T1"@"SEL$1", SCALE\_ROWS=0.01161091426)

可以看到，SQL Profiles的attr\_val实际上就是一些Hints，这跟Outlines没有本质上的区别。只是SQL Profiles中的Hint，没有指定SQL使用哪个索引，也没有指定表的连接方法和连接顺序。这里只指定了T1表评估返回的行数，与原始的评估返回的行数的放大缩小的倍数。2498\*0.01161091426正好为29。这里就是告诉Oracle优化器，T1表经过谓语过滤后返回行数应该为评估的0.01161091426倍。从这里可以看出，SQL Profiles并不会锁定SQL的执行计划，只是提供了更多、更准确的统计信息给优化器。看下面的测试：

[view plain](http://www.laoxiong.net/sql-profiles-part.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-part.html)[print](http://www.laoxiong.net/sql-profiles-part.html)[?](http://www.laoxiong.net/sql-profiles-part.html)

01. SQL&gt; exec dbms\_stats.set\_table\_stats('TEST1','T1',numrows=&gt;5000000);
02. PL/SQL 过程已成功完成。
03. SQL&gt; explain plan for select  t1.\*,t2.owner
04. 2       from t1,t2
05. 3       where t1.object\_name like '%T1%'
06. 4       and t1.object\_id=t2.object\_id;
07. 已解释。
08. SQL&gt; @showplan
09. PLAN\_TABLE\_OUTPUT
10. \----------------------------------------------------------------------------------
11. Plan hash value: 1838229974
12. \---------------------------------------------------------------------------
13. | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
14. \---------------------------------------------------------------------------
15. |   0 | SELECT STATEMENT   |      |  2903 |   113K|   448  (53)| 00:00:06 |
16. |*  1 |  HASH JOIN         |      |  2903 |   113K|   448  (53)| 00:00:06 |
17. |*  2 |   TABLE ACCESS FULL| T1   |  2903 | 84187 |   288  (81)| 00:00:04 |
18. |   3 |   TABLE ACCESS FULL| T2   | 49954 |   536K|   159   (2)| 00:00:02 |
19. \---------------------------------------------------------------------------
20. Predicate Information (identified by operation id):
21. \---------------------------------------------------
22. 1 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
23. 2 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
24. Note
25. \-----
26. - SQL profile "SYS\_SQLPROF\_014b39f084c88000" used for this statement

将T1表的统计信息中的表行数改为500万，Oracle就会评估为返回5000000\*5%\*0.01161091426=2903行。这里执行计划又变回为full scan+hash join。可以看到，虽然SQL Profile起作用了，但是并没有锁定执行计划。

小结：本文简单介绍了什么是SQL Profiles及其作用，如何使用SQL Tuning Advisor来生成SQL Profile，以及生成的SQL Profile产生的Hint。同时也介绍了SQL的signature。

下一篇将会介绍如何手工来为创建、生成SQL Profile，以及如何让SQL Profile也能像Outlines一样锁定SQL的执行计划，以保持SQL执行计划的稳定性。

在上一篇[《SQL Profiles-Part I》](http://www.laoxiong.net/sql-profiles-part.html)，我向大家介绍了什么是SQL Profiles及其作用，如何使用SQL Tuning Advisor来生成SQL Profile，以及生成的SQL Profile产生的Hint。同时也介绍了SQL的signature。那么在今天，将向大家介绍如何手工创建SQL Profiles（即不通过SQL Tuning Advisor)来达成2个目的：

- 锁定或者说稳定SQL执行计划。
- 在不能修改应用的SQL的情况下，来改变或者说是强制使SQL使用我们指定的执行计划，即使原始的SQL包含了Hints。

那么，这里最关键的一点是，如何来手工创建SQL Profiles?  
答案是，正如上一篇中有朋友的[留言](http://www.laoxiong.net/sql-profiles-part.html#comment-1071)，使用DBMS\_SQLTUNE.IMPORT\_SQL\_PROFILE过程。

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; desc dbms\_sqltune
02. ...
03. PROCEDURE IMPORT\_SQL\_PROFILE
04. 参数名称                       类型                    输入/输出默认值?
05. ------------------------------ ----------------------- ------ --------
06. SQL\_TEXT                       CLOB                    IN
07. PROFILE                        SQLPROF\_ATTR            IN
08. NAME                           VARCHAR2                IN     DEFAULT
09. DESCRIPTION                    VARCHAR2                IN     DEFAULT
10. CATEGORY                       VARCHAR2                IN     DEFAULT
11. VALIDATE                       BOOLEAN                 IN     DEFAULT
12. REPLACE                        BOOLEAN                 IN     DEFAULT
13. FORCE\_MATCH                    BOOLEAN                 IN     DEFAULT
14. ...

这个过程其名字与实际功能有所差异，其实可以理解为CREATE OR REPLACE SQL\_PROFILE。过程中的PROFILE参数为SYS.SQLPROF\_ATTR，这种类型其实就是VARCHAR2的集合类型(COLLECTION)：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. SQL&gt; select text from dba\_source where name='SQLPROF\_ATTR' and owner='SYS';
2. TYPE     sqlprof\_attr
3. AS VARRAY(2000) of VARCHAR2(500)

下面我们就用这个过程来创建SQL PROFILE：  
为避免干扰，将上一篇测试中生成的SQL Profile删除掉，同时恢复T1表的统计信息中的表行数：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. SQL&gt; exec dbms\_sqltune.drop\_sql\_profile('SYS\_SQLPROF\_014b39f084c88000');
2. PL/SQL 过程已成功完成。
3. SQL&gt; exec dbms\_stats.set\_table\_stats('TEST1','T1',numrows=&gt;49953);
4. PL/SQL 过程已成功完成。

现在我们手工创建一个SQL Profile：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; declare
02. 2    v\_hints sys.sqlprof\_attr;
03. 3  begin
04. 4    v\_hints:=sys.sqlprof\_attr('USE\_NL(T1 T2)','INDEX(T2)');
05. 5    dbms\_sqltune.import\_sql\_profile('select t1.\*,t2.owner from t1,t2 where t1.object\_name like ''%T1%'' and t1.object\_id=t2.object\_id',
06. 6                v\_hints,'SQLPROFILE\_NAME1',force\_match=&gt;true);
07. 7  end;
08. 8  /
09. PL/SQL 过程已成功完成。
10. SQL&gt; select attr\_val from dba\_sql\_profiles a, sys.sqlprof$attr b
11. 2  where a.signature = b.signature
12. 3  and a.name='SQLPROFILE\_NAME1';
13. ATTR\_VAL
14. \----------------------------------------
15. USE\_NL(T1 T2)
16. INDEX(T2)

下面执行SQL Profiles对应的SQL：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select  t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择29行。
06. 执行计划
07. \----------------------------------------------------------
08. Plan hash value: 1838229974
09. \---------------------------------------------------------------------------
10. | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
11. \---------------------------------------------------------------------------
12. |   0 | SELECT STATEMENT   |      |  2498 | 99920 |   219   (4)| 00:00:03 |
13. |*  1 |  HASH JOIN         |      |  2498 | 99920 |   219   (4)| 00:00:03 |
14. |*  2 |   TABLE ACCESS FULL| T1   |  2498 | 72442 |    59   (6)| 00:00:01 |
15. |   3 |   TABLE ACCESS FULL| T2   | 49954 |   536K|   159   (2)| 00:00:02 |
16. \---------------------------------------------------------------------------
17. Predicate Information (identified by operation id):
18. \---------------------------------------------------
19. 1 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
20. 2 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
21. Note
22. \-----
23. - SQL profile "SQLPROFILE\_NAME1" used for this statement
24. 统计信息
25. \----------------------------------------------------------
26. 0  recursive calls
27. 0  db block gets
28. 933  consistent gets

**可以看到，SQL使用了SQL Profile，不过没有达到我们预期的效果。**

看起来是SQL Profile使用的Hints有问题。我们重新设置SQL Profile的Hints，在Hints中加上“Query Block Name”。这一次在执行IMPORT\_SQL\_PROFILE过程时，将REPLACE参数设置为TRUE，以替换现有的SQL Profile：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; declare
02. 2    v\_hints sys.sqlprof\_attr;
03. 3  begin
04. 4    v\_hints:=sys.sqlprof\_attr('USE\_NL(T1@SEL$1 T2@SEL$1)','INDEX(T2@SEL$1)');
05. 5    dbms\_sqltune.import\_sql\_profile('select t1.\*,t2.owner from t1,t2 where t1.object\_name like ''%T1%'' and t1.object\_id=t2.object\_id',
06. 6                v\_hints,'SQLPROFILE\_NAME1',force\_match=&gt;true,replace=&gt;true);
07. 7  end;
08. 8  /
09. PL/SQL 过程已成功完成。
10. SQL&gt; select attr\_val from dba\_sql\_profiles a, sys.sqlprof$attr b
11. 2  where a.signature = b.signature
12. 3  and a.name='SQLPROFILE\_NAME1';
13. ATTR\_VAL
14. \----------------------------------------
15. USE\_NL(T1@SEL$1 T2@SEL$1)
16. INDEX(T2@SEL$1)

再次执行下面的SQL：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select  t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择29行。
06. 执行计划
07. \----------------------------------------------------------
08. Plan hash value: 3787413387
09. \--------------------------------------------------------------------------------------
10. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
11. \--------------------------------------------------------------------------------------
12. |   0 | SELECT STATEMENT            |        |  2498 | 99920 |  5061   (1)| 00:01:01 |
13. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
14. |   2 |   NESTED LOOPS              |        |  2498 | 99920 |  5061   (1)| 00:01:01 |
15. |*  3 |    TABLE ACCESS FULL        | T1     |  2498 | 72442 |    59   (6)| 00:00:01 |
16. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
17. \--------------------------------------------------------------------------------------
18. Predicate Information (identified by operation id):
19. \---------------------------------------------------
20. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
21. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
22. Note
23. \-----
24. - SQL profile "SQLPROFILE\_NAME1" used for this statement
25. 统计信息
26. \----------------------------------------------------------
27. 0  recursive calls
28. 0  db block gets
29. 294  consistent gets

**这一次达到了预期的效果。看起来在SQL Profiles中对Hints还有一定的要求。**  
那么我们再一次手工修改T1表的统计信息，看看结果如何：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; exec dbms\_stats.set\_table\_stats('TEST1','T1',numrows=&gt;5000000);
02. PL/SQL 过程已成功完成。
03. SQL&gt; select  t1.\*,t2.owner
04. 2       from t1,t2
05. 3       where t1.object\_name like '%T1%'
06. 4       and t1.object\_id=t2.object\_id;
07. 已选择29行。
08. 执行计划
09. \----------------------------------------------------------
10. Plan hash value: 3787413387
11. \--------------------------------------------------------------------------------------
12. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
13. \--------------------------------------------------------------------------------------
14. |   0 | SELECT STATEMENT            |        |   250K|  9765K|   500K  (1)| 01:40:12 |
15. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
16. |   2 |   NESTED LOOPS              |        |   250K|  9765K|   500K  (1)| 01:40:12 |
17. |*  3 |    TABLE ACCESS FULL        | T1     |   250K|  7080K|   288  (81)| 00:00:04 |
18. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
19. \--------------------------------------------------------------------------------------
20. Predicate Information (identified by operation id):
21. \---------------------------------------------------
22. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
23. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
24. Note
25. \-----
26. - SQL profile "SQLPROFILE\_NAME1" used for this statement
27. 统计信息
28. \----------------------------------------------------------
29. 0  recursive calls
30. 0  db block gets
31. 294  consistent gets

可以看到，Oracle优化器评估表T1经过Like条件过滤后返回的行数虽然很大，但是这里的执行计划仍然与未修改统计信息之前一样，使用range scan+ nested loop join。

通过以上的测试，我们明白了DBMS\_SQLTUNE.IMPORT\_SQL\_PROFILE的使用，同时也验证了这种方式的有效性，**SQL Profiles能够像Outlines一样，能够稳定SQL的执行计划。**

接下来我们需要完成两个任务。  
**任务一：对现有的SQL稳定其执行计划。**  
这里的问题是：稳定一条SQL语句的Hints从哪里来？简单的sql，没问题，我们可以手工构造，但是复杂的SQL，手工构造相对比较复杂，同时手工构造的Hints不一定能够保证SQL的执行计划就会稳定。从10g开始，v$sql\_plan中就包括了SQL语句OUTLINE数据，也就是稳定执行计划的Hints。从下面可以看到：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select  t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择29行。
06. SQL&gt; select * from table(dbms\_xplan.display\_cursor(null,null,'outline'));
07. PLAN\_TABLE\_OUTPUT
08. \----------------------------------------------------------------------------------------
09. SQL\_ID  6m45w7r0xgdfj, child number 0
10. \-------------------------------------
11. select  t1.\*,t2.owner      from t1,t2      where t1.object\_name like '%T1%'
12. and t1.object\_id=t2.object\_id
13. Plan hash value: 3787413387
14. \--------------------------------------------------------------------------------------
15. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
16. \--------------------------------------------------------------------------------------
17. |   0 | SELECT STATEMENT            |        |       |       |  5061 (100)|          |
18. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
19. |   2 |   NESTED LOOPS              |        |  2498 | 99920 |  5061   (1)| 00:01:01 |
20. |*  3 |    TABLE ACCESS FULL        | T1     |  2498 | 72442 |    59   (6)| 00:00:01 |
21. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
22. \--------------------------------------------------------------------------------------
23. Outline Data
24. \-------------
25. /\*+
26. BEGIN\_OUTLINE\_DATA
27. IGNORE\_OPTIM\_EMBEDDED\_HINTS
28. OPTIMIZER\_FEATURES\_ENABLE('10.2.0.1')
29. ALL\_ROWS
30. OUTLINE\_LEAF(@"SEL$1")
31. FULL(@"SEL$1" "T1"@"SEL$1")
32. INDEX(@"SEL$1" "T2"@"SEL$1" ("T2"."OBJECT\_ID"))
33. LEADING(@"SEL$1" "T1"@"SEL$1" "T2"@"SEL$1")
34. USE\_NL(@"SEL$1" "T2"@"SEL$1")
35. END\_OUTLINE\_DATA
36. \*/
37. Predicate Information (identified by operation id):
38. \---------------------------------------------------
39. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
40. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
41. Note
42. \-----
43. - SQL profile "SQLPROFILE\_NAME1" used for this statement

上面所显示的“Outline Data”即是我们稳定SQL执行计划需要的Hints(我们甚至可以将这些Hints直接写到我们的SQL中）。对需要稳定执行计划的SQL，我们所要做的就是如前面所示，将Hints与SQL文本一起创建一个SQL Profile。这里不得不提到一个SQL脚本，来自MOS。”SQLT (SQLTXPLAIN) - Tool that helps to diagnose SQL statements performing poorly \[ID 215187.1]“，在这篇文章中，可以下载到sqlt.zip，这个压缩文件内有一个文件：coe\_xfr\_sql\_profile.sql。这个脚本可以用于从shared pool、awr中提取指定的SQL ID的Outline Data并创建SQL Profile。下面是示例：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select /\*+ proftest1 \*/ t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. --在shared pool中查找刚刚执行的SQL，其ID为b4zvp712np1bp--
06. SQL&gt; @coe\_xfr\_sql\_profile.sql
07. Parameter 1:
08. SQL\_ID (required)
09. 输入 1 的值:  b4zvp712np1bp
10. PLAN\_HASH\_VALUE AVG\_ET\_SECS
11. --------------- -----------
12. 2959412835        .112
13. Parameter 2:
14. PLAN\_HASH\_VALUE (required)
15. 输入 2 的值:  2959412835
16. Values passed:
17. \~~~~~~~~~~~~~
18. SQL\_ID         : "b4zvp712np1bp"
19. PLAN\_HASH\_VALUE: "2959412835"
20. Execute coe\_xfr\_sql\_profile\_b4zvp712np1bp\_2959412835.sql
21. on TARGET system in order to create a custom SQL Profile
22. with plan 2959412835 linked to adjusted sql\_text.
23. COE\_XFR\_SQL\_PROFILE completed.
24. SQL&gt;@coe\_xfr\_sql\_profile\_b4zvp712np1bp\_2959412835.sql
25. PL/SQL 过程已成功完成。
26. SQL&gt;WHENEVER SQLERROR CONTINUE
27. SQL&gt;SET ECHO OFF;
28. SIGNATURE
29. \---------------------
30. 6058051510930011685
31. ... manual custom SQL Profile has been created
32. COE\_XFR\_SQL\_PROFILE\_b4zvp712np1bp\_2959412835 completed
33. SQL&gt;select attr\_val from sys.sqlprof$attr where signature=6058051510930011685;
34. ATTR\_VAL
35. \--------------------------------------------------
36. BEGIN\_OUTLINE\_DATA
37. IGNORE\_OPTIM\_EMBEDDED\_HINTS
38. OPTIMIZER\_FEATURES\_ENABLE('10.2.0.1')
39. ALL\_ROWS
40. OUTLINE\_LEAF(@"SEL$1")
41. FULL(@"SEL$1" "T2"@"SEL$1")
42. FULL(@"SEL$1" "T1"@"SEL$1")
43. LEADING(@"SEL$1" "T2"@"SEL$1" "T1"@"SEL$1")
44. USE\_HASH(@"SEL$1" "T1"@"SEL$1")
45. END\_OUTLINE\_DATA

coe\_xfr\_sql\_profile.sql这个脚本首先要求输入sql id，然后从shared pool、awr中获取sql执行的各个执行计划的统计信息（执行计划不稳定的SQL通常会有多个不同的执行计划），然后输入你认为是正确的、需要稳定的执行计划的hash value，脚本就会生成另一个脚本，这里为coe\_xfr\_sql\_profile\_b4zvp712np1bp\_2959412835.sql，然后运行这个脚本，就会创建出稳定执行计划所需要的SQL Profile，SQL Profile的名字为：coe+sql\_id+plan\_hash\_value，这里为coe\_b4zvp712np1bp\_2959412835。注意，这里创建的SQL Profile，force match默认为FALSE，我们可以手工修改脚本将其改为TRUE，同时我们也可以按意愿来修改生成的脚本的其他内容。

除了上面提到的脚本，[http://kerryosborne.oracle-guy.com](http://kerryosborne.oracle-guy.com/)这个BLOG里面也有许多与SQL Profiles相关的脚本。其中[create\_sql\_profile.sql](http://kerryosborne.oracle-guy.com/scripts/create_sql_profile.sql)可完成类似的功能，只不过功能相对简单，只能从shared pool中生成SQL Profile，因此也更方便。

任务二：在不能修改SQL的情况下改变并固定SQL的执行计划，即使原始的SQL使用了Hints。  
常常遇到这样的情况，SQL语句其执行计划有问题，或者是SQL使用了错误的Hints（比如 /\*+ RULE \*/）导致SQL性能较差，但是应用又不能修改或者时间内不能修改，那么我们怎么来改变SQL的执行计划呢。有3种办法，一种是调整统计信息，这个不建议使用，因为比较复杂、不稳定可靠（统计信息可能会重新收集），影响面广（会影响其他访问此对象的SQL）。第二种是使用OUTLINE，这种方法比较复杂。第三种就是我们今天要介绍的使用SQL Profiles了。

使用SQL Profiles来改变SQL的执行计划，其本质上就是使用Hints来改变SQL的执行计划。对于简单的SQL，我们同样可以像前面一样手工构造Hints然后再使用DBMS\_SQLTUNE.IMPORT\_SQL\_PROFILE来实现。但是这种方法还是略显烦琐。那么通常的方法就是”乾坤大挪移“了：

- 取得原始SQL的文本（如有可能还包括sql id)
- 构造一个与原始SQL在逻辑上、结构上完全相同的SQL。这里强制逻辑上和结构上相同，SQL解析的用户名、SQL中引用对象的用户名甚至是一些predicate条件都可以不同。当然能够与原始SQL完全一样就更省事。
- 执行我们构造的SQL，并取得构造的SQL的Outline Data。
- 使用原始SQL的文本和构造的SQL的Outline Data创建SQL Profile。

下面我们来演示一下整个过程。我们这里要修改执行计划的SQL是：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. select /\*+ orig\_sql full(t1) full(t2) use\_hash(t1 t2) \*/ t1.\*,t2.owner
2. from t1,t2
3. where t1.object\_name like '%T1%'
4. and t1.object\_id=t2.object\_id;

我们首先需要执行这一条SQL，然后取得的SQL ID为gmvb9bp7f9kqd：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select /\*+ orig\_sql full(t1) full(t2) use\_hash(t1 t2) \*/ t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择29行。
06. 执行计划
07. \----------------------------------------------------------
08. Plan hash value: 2959412835
09. \-----------------------------------------------------------------------------------
10. | Id  | Operation          | Name | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
11. \-----------------------------------------------------------------------------------
12. |   0 | SELECT STATEMENT   |      |   250K|  9765K|       |   998  (25)| 00:00:12 |
13. |*  1 |  HASH JOIN         |      |   250K|  9765K|  1128K|   998  (25)| 00:00:12 |
14. |   2 |   TABLE ACCESS FULL| T2   | 49954 |   536K|       |   159   (2)| 00:00:02 |
15. |*  3 |   TABLE ACCESS FULL| T1   |   250K|  7080K|       |   288  (81)| 00:00:04 |
16. \-----------------------------------------------------------------------------------

然后我们构造一条SQL，让这条SQL按我们希望的执行计划运行，构造的SQL其ID为cymak300cycmd：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt; select /\*+ modify\_sql index(t1) use\_nl(t1 t2) \*/ t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T1%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择29行。
06. 执行计划
07. \----------------------------------------------------------
08. Plan hash value: 3787413387
09. \--------------------------------------------------------------------------------------
10. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
11. \--------------------------------------------------------------------------------------
12. |   0 | SELECT STATEMENT            |        |   250K|  9765K|   500K  (1)| 01:40:12 |
13. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
14. |   2 |   NESTED LOOPS              |        |   250K|  9765K|   500K  (1)| 01:40:12 |
15. |*  3 |    TABLE ACCESS FULL        | T1     |   250K|  7080K|   288  (81)| 00:00:04 |
16. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
17. \--------------------------------------------------------------------------------------
18. Predicate Information (identified by operation id):
19. \---------------------------------------------------
20. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T1%')
21. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")

然后使用coe\_xfr\_sql\_profile.sql脚本来提取我们构造的SQL的Outline Data，生成的结果为coe\_xfr\_sql\_profile\_cymak300cycmd\_3787413387.sql，打开结果文件，可以看到有这么一段：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. h := SYS.SQLPROF\_ATTR(
02. q'\[BEGIN\_OUTLINE\_DATA]',
03. q'\[IGNORE\_OPTIM\_EMBEDDED\_HINTS]',
04. q'\[OPTIMIZER\_FEATURES\_ENABLE('10.2.0.1')]',
05. q'\[ALL\_ROWS]',
06. q'\[OUTLINE\_LEAF(@"SEL$1")]',
07. q'\[FULL(@"SEL$1" "T1"@"SEL$1")]',
08. q'\[INDEX(@"SEL$1" "T2"@"SEL$1" ("T2"."OBJECT\_ID"))]',
09. q'\[LEADING(@"SEL$1" "T1"@"SEL$1" "T2"@"SEL$1")]',
10. q'\[USE\_NL(@"SEL$1" "T2"@"SEL$1")]',
11. q'\[END\_OUTLINE\_DATA]');

再针对gmvb9bp7f9kqd使用coe\_xfr\_sql\_profile.sql，生成的结果文件为coe\_xfr\_sql\_profile\_gmvb9bp7f9kqd\_2959412835.sql。手工修改这个文件，将里面h := SYS.SQLPROF\_ATTR…那一段替换成我们之前得到的那一段。这一次我们将这个文件中的force\_match从FALSE改成TRUE。  
最后我们运行coe\_xfr\_sql\_profile\_gmvb9bp7f9kqd\_2959412835.sql这个脚本文件：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. SQL&gt;@coe\_xfr\_sql\_profile\_gmvb9bp7f9kqd\_2959412835.sql
2. PL/SQL 过程已成功完成。
3. SQL&gt;WHENEVER SQLERROR CONTINUE
4. SQL&gt;SET ECHO OFF;
5. SIGNATURE
6. \---------------------
7. 15409905709853673912
8. ... manual custom SQL Profile has been created
9. COE\_XFR\_SQL\_PROFILE\_gmvb9bp7f9kqd\_2959412835 completed

这样就完成了我们所需要的SQL Profile的创建。下面再看看原来的SQL执行情况（这里我故意将like条件改了一下，以查看force match是否起作用）：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

01. SQL&gt;select /\*+ orig\_sql full(t1) full(t2) use\_hash(t1 t2) \*/ t1.\*,t2.owner
02. 2       from t1,t2
03. 3       where t1.object\_name like '%T2%'
04. 4       and t1.object\_id=t2.object\_id;
05. 已选择77行。
06. 执行计划
07. \----------------------------------------------------------
08. Plan hash value: 3787413387
09. \--------------------------------------------------------------------------------------
10. | Id  | Operation                   | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
11. \--------------------------------------------------------------------------------------
12. |   0 | SELECT STATEMENT            |        |   250K|  9765K|   500K  (1)| 01:40:12 |
13. |   1 |  TABLE ACCESS BY INDEX ROWID| T2     |     1 |    11 |     2   (0)| 00:00:01 |
14. |   2 |   NESTED LOOPS              |        |   250K|  9765K|   500K  (1)| 01:40:12 |
15. |*  3 |    TABLE ACCESS FULL        | T1     |   250K|  7080K|   288  (81)| 00:00:04 |
16. |*  4 |    INDEX RANGE SCAN         | T2\_IDX |     1 |       |     1   (0)| 00:00:01 |
17. \--------------------------------------------------------------------------------------
18. Predicate Information (identified by operation id):
19. \---------------------------------------------------
20. 3 - filter("T1"."OBJECT\_NAME" LIKE '%T2%')
21. 4 - access("T1"."OBJECT\_ID"="T2"."OBJECT\_ID")
22. Note
23. \-----
24. - SQL profile "coe\_gmvb9bp7f9kqd\_2959412835" used for this statement
25. 统计信息
26. \----------------------------------------------------------
27. 0  recursive calls
28. 0  db block gets
29. 363  consistent gets

可以看到SQL Profile起作用了。

最后一步，生成SQL Profile时稍显复杂，不过我们可以修改之前提到的create\_sql\_profile.sql文件来达到同样的目的，只不过前几个步骤仍然是不可省略的。将里面的代码：

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. select extractvalue(value(d), '/hint') as outline\_hints bulk collect
2. into ar\_profile\_hints
3. from xmltable('/\*/outline\_data/hint' passing
4. (select xmltype(other\_xml) as xmlval
5. from v$sql\_plan
6. where sql\_id = '&&sql\_id'
7. and child\_number = &&child\_no
8. and other\_xml is not null)) d;

改为

[view plain](http://www.laoxiong.net/sql-profiles-partii.html)[copy to clipboard](http://www.laoxiong.net/sql-profiles-partii.html)[print](http://www.laoxiong.net/sql-profiles-partii.html)[?](http://www.laoxiong.net/sql-profiles-partii.html)

1. select extractvalue(value(d), '/hint') as outline\_hints bulk collect
2. into ar\_profile\_hints
3. from xmltable('/\*/outline\_data/hint' passing
4. (select xmltype(other\_xml) as xmlval
5. from v$sql\_plan
6. where sql\_id = '&&modi\_sql\_id'
7. and child\_number = &&modi\_child\_no
8. and other\_xml is not null)) d;

注意这里modi\_sql\_id和modi\_child\_no为我们构造的SQL执行后的id及child\_number。同时这2个变量在文件前面需要定义，此处不再细述。

**小结：本文承接上一篇，介绍了如何利用SQL Profile来稳定执行计划；如何利用SQL Profile来改变SQL的执行计划。**对于SQL Profiles来说，不属于任何一个用户，比Outlines更具有操控性灵活性。对于SQL Profiles的category，这里不做介绍，有兴趣的朋友请参考文档。