@@header

/*
*
*  Author     : Vishal Gupta
*  Purpose    : Create SQL Profile
*  Parameters : 1 - SQL ID
*               2 - SQL Child Number
*               3 - SQL Profile Categor, usually "DEFAULT"
*               4 - FORCE_MATCH, possibile values - TRUE or FALSE
*               5 - SQL Profile Description
*          
*
*  Revision History:
*  ===================
*  Date       Author        Description
*  ---------  ------------  -----------------------------------------
*  16-May-12  Vishal Gupta  First cut
*
*/


DEFINE SQLID="&&1" 
DEFINE CHILD_NO="&&2"
DEFINE CATEGORY="&&3"
DEFINE FORCE_MATCH="&&4"
DEFINE DESCRIPTION="&&5"

set serveroutput on
declare
     ar_profile_hints sys.sqlprof_attr;
     cl_sql_text      clob;
     l_profile_name   VARCHAR2(30) := 'PROF_' || '&&SQLID' || '_' || '&&PLAN_HASH_VALUE';
begin
      SELECT extractvalue(value(d), '/hint') AS outline_hints 
      bulk collect
      INTO ar_profile_hints
      FROM xmltable('/*/outline_data/hint' passing
          (SELECT xmltype(other_xml) AS xmlval
             FROM v$sql_plan
            WHERE sql_id           = '&&SQLID'
              AND child_number     = &&CHILD_NO
              AND other_xml IS NOT NULL
         ) ) d;

    SELECT sql.sql_fulltext 
    INTO cl_sql_text 
    FROM v$sqlarea sql
    WHERE sql.sql_id = '&&SQLID';

     dbms_sqltune.import_sql_profile(  sql_text    => cl_sql_text
                                     , profile     => ar_profile_hints
                                     , category    => '&&CATEGORY'
                                     , name        => l_profile_name
                                     , description => '&&DESCRIPTION'
                                      -- use force_match => true
                                      -- to use CURSOR_SHARING=SIMILAR
                                      -- behaviour, i.e. match even with
                                      -- differing literals
                                    , force_match  => &&FORCE_MATCH
                                 -- , replace      => true
      );
      
      dbms_output.put_line(' ');
      dbms_output.put_line('SQL Profile '||l_profile_name||' created.');
      dbms_output.put_line(' ');

end;
/

UNDEFINE SQLID
UNDEFINE CHILD_NO
UNDEFINE CATEGORY
UNDEFINE FORCE_MATCH


@@footer
