/*
 * Title  : awr_base_line.sql
 * Author : EXADIME LLC
 * Created: 29-Mar-2018
 * Updated: 29-Mar-2018
 * Release: 1.0.0
 * Purpose: To create baseline for good SQL plan captured in AWR.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback on
set serverout on
set termout on

set linesize 80
set pagesize 0
set pause off
set long 80

set heading off
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

accept p_bsnap char prompt "Enter Begin Snap Id: "
accept p_esnap char prompt "Enter End Snap Id: "
accept p_sqlid char prompt "Enter SQL Id: "
accept p_plan_hash char prompt "Enter Plan Hash Value: "

spool &&rpt_dir/awr_base_line.rpt

DECLARE
	cur sys_refcursor;
	int pls_integer;
BEGIN
	--1.Create SQL Tuning Set.
	DBMS_SQLTUNE.CREATE_SQLSET(
		sqlset_name => 'awr_base_line_&&p_sqlid',
		description => 'SQL Tuning Set for loading plan into SQL Plan Baseline (SQL Id: &&p_sqlid).'
	);

	--2.Load SQL from AWR into SQL Tuning Set.
	OPEN cur FOR
	SELECT VALUE(P)
	FROM TABLE(
		dbms_sqltune.select_workload_repository(begin_snap=>&&p_bsnap, end_snap=>&&p_esnap,basic_filter=>'sql_id = ''&&p_sqlid''',attribute_list=>'ALL')
	) p;
	DBMS_SQLTUNE.LOAD_SQLSET( sqlset_name=> 'awr_base_line_&&p_sqlid', populate_cursor=>cur);
	CLOSE cur;

	--3.Filter good SQL based on plan has value and create baseline.
	int:=DBMS_SPM.LOAD_PLANS_FROM_SQLSET(
		sqlset_name => 'awr_base_line_&&p_sqlid', 
		basic_filter=>'plan_hash_value = ''&&p_plan_hash'''
	);

	--4.Drop SQL Tuning Set.
	DBMS_SQLTUNE.DROP_SQLSET(
		sqlset_name => 'awr_base_line_&&p_sqlid'
	);

	if int=1 then
		dbms_output.put_line('Baseline created.');
	else
		dbms_output.put_line('Baseline creation failed!');
	end if;
END;
/

spool off

clear columns

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off
