2026-03-12 20:23:15

This commit is contained in:
root
2026-03-12 21:23:47 +01:00
parent eab4b36eca
commit 93039b8489
3332 changed files with 699614 additions and 0 deletions

131
star/arch_size_hourly.sql Normal file
View File

@@ -0,0 +1,131 @@
set term off
/*
*
* Author : Vishal Gupta
* Purpose : Display hourly and daily redolog switches by size
* Parameters : None
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 30-Dec-14 Vishal Gupta Added number of days as input parameter
* 18-Mar-14 Vishal Gupta Added separator columns for daily total
* 27-Feb-12 Vishal Gupta Formated the output and parameterized size granuality
* 05-Aug-04 Vishal Gupta First Draft
*
*/
set term on
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE days
DEFINE days="&&1"
set term off
COLUMN _DAYS NEW_VALUE DAYS NOPRINT
SELECT UPPER(DECODE('&&days','','15','&&days')) "_DAYS"
FROM DUAL;
set term on
/************************************
* CONFIGURATION PARAMETERS
************************************/
DEFINE size_label=GB
DEFINE size_divider="1024/1024/1024"
DEFINE round_precision=2
PROMPT
PROMPT ************************************************************************
PROMPT * A R C H I V E L O G S W I T C H S U M M A R Y (By Size)
PROMPT * (Hourly and Daily figures in &&size_label)
PROMPT *
PROMPT * Input Parameters
PROMPT * - Days = '&&days'
PROMPT ************************************************************************
PROMPT
PROMPT - <-------------------------------------------------------- hourly total ----------------------------------------------->
/*
Total h0 h1 h2 h3 h4 h5 h6 h7 h8 h9 h10 h11 h12 h13 h14 h15 h16 h17 h18 h19 h20 h21 h22 h23
Date Day (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB) (GB)
--------- --- ----- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
*/
SET head on FEED off ECHO OFF LINES 1000 TRIMSPOOL ON TRIM on PAGES 1000
COLUMN separator HEADING "!|!|!" FORMAT A1
COLUMN "Date" HEADING "Date" FORMAT A9
COLUMN "Total" HEADING "Day|Total|(&size_label)" FORMAT 99999
COLUMN "Day" HEADING "Day" FORMAT A3
COLUMN h0 HEADING "h0|(&size_label)" FORMAT 9999
COLUMN h1 HEADING "h1|(&size_label)" FORMAT 9999
COLUMN h2 HEADING "h2|(&size_label)" FORMAT 9999
COLUMN h3 HEADING "h3|(&size_label)" FORMAT 9999
COLUMN h4 HEADING "h4|(&size_label)" FORMAT 9999
COLUMN h5 HEADING "h5|(&size_label)" FORMAT 9999
COLUMN h6 HEADING "h6|(&size_label)" FORMAT 9999
COLUMN h7 HEADING "h7|(&size_label)" FORMAT 9999
COLUMN h8 HEADING "h8|(&size_label)" FORMAT 9999
COLUMN h9 HEADING "h9|(&size_label)" FORMAT 9999
COLUMN h10 HEADING "h10|(&size_label)" FORMAT 9999
COLUMN h11 HEADING "h11|(&size_label)" FORMAT 9999
COLUMN h12 HEADING "h12|(&size_label)" FORMAT 9999
COLUMN h13 HEADING "h13|(&size_label)" FORMAT 9999
COLUMN h14 HEADING "h14|(&size_label)" FORMAT 9999
COLUMN h15 HEADING "h15|(&size_label)" FORMAT 9999
COLUMN h16 HEADING "h16|(&size_label)" FORMAT 9999
COLUMN h17 HEADING "h17|(&size_label)" FORMAT 9999
COLUMN h18 HEADING "h18|(&size_label)" FORMAT 9999
COLUMN h19 HEADING "h19|(&size_label)" FORMAT 9999
COLUMN h20 HEADING "h20|(&size_label)" FORMAT 9999
COLUMN h21 HEADING "h21|(&size_label)" FORMAT 9999
COLUMN h22 HEADING "h22|(&size_label)" FORMAT 9999
COLUMN h23 HEADING "h23|(&size_label)" FORMAT 9999
SELECT to_char(trunc(COMPLETION_TIME),'DD-Mon-YY') "Date",
to_char(COMPLETION_TIME, 'Dy') "Day",
'|' separator,
ROUND(SUM(((BLOCKS * BLOCK_SIZE)/&size_divider))) "Total",
'|' separator,
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'00',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h0",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'01',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h1",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'02',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h2",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'03',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h3",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'04',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h4",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'05',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h5",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'06',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h6",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'07',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h7",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'08',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h8",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'09',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h9",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'10',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h10",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'11',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h11",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'12',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h12",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'13',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h13",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'14',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h14",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'15',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h15",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'16',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h16",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'17',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h17",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'18',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h18",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'19',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h19",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'20',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h20",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'21',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h21",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'22',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h22",
ROUND(SUM(decode(to_char(COMPLETION_TIME, 'hh24'),'23',(BLOCKS * BLOCK_SIZE)/&size_divider,0))) "h23"
from v$archived_log
where standby_dest = 'NO'
AND CREATOR IN ('ARCH' , 'FGRD','LGWR','RFS')
AND completion_time > sysdate - &days
group by trunc(COMPLETION_TIME), to_char(COMPLETION_TIME, 'Dy')
order by trunc(COMPLETION_TIME)
/

View File

@@ -0,0 +1,92 @@
set term off
/*
*
* Author : Vishal Gupta
* Purpose : Display hourly and daily redolog switches by size
* Parameters : None
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 30-Dec-14 Vishal Gupta Added number of days as input parameter
* 18-Mar-14 Vishal Gupta Added separator columns for daily total
* 27-Feb-12 Vishal Gupta Formated the output and parameterized size granuality
* 05-Aug-04 Vishal Gupta First Draft
*
*/
set term on
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE days
DEFINE days="&&1"
set term off
COLUMN _DAYS NEW_VALUE DAYS NOPRINT
SELECT UPPER(DECODE('&&days','','2','&&days')) "_DAYS"
FROM DUAL;
set term on
/************************************
* CONFIGURATION PARAMETERS
************************************/
DEFINE size_label=MB
DEFINE size_divider="1024/1024"
--DEFINE size_label=GB
--DEFINE size_divider="1024/1024/1024"
DEFINE round_precision=2
PROMPT
PROMPT ************************************************************************
PROMPT * A R C H I V E L O G S W I T C H S U M M A R Y (By Size)
PROMPT * (Hourly and Daily figures in &&size_label)
PROMPT *
PROMPT * Input Parameters
PROMPT * - Days = '&&days'
PROMPT ************************************************************************
PROMPT
SET head on FEED off ECHO OFF LINES 1000 TRIMSPOOL ON TRIM on PAGES 1000
COLUMN separator HEADING "!|!|!" FORMAT A1
COLUMN "Date" HEADING "Date" FORMAT A12
COLUMN "Day" HEADING "Day" FORMAT A3
COLUMN "Total" HEADING "Hourly|Total|(&size_label)" FORMAT 9,999,999
COLUMN "M00" HEADING "Minutes|01-10 |(&size_label) " FORMAT 999,999
COLUMN "M10" HEADING "Minutes|11-20 |(&size_label) " FORMAT 999,999
COLUMN "M20" HEADING "Minutes|21-30 |(&size_label) " FORMAT 999,999
COLUMN "M30" HEADING "Minutes|31-40 |(&size_label) " FORMAT 999,999
COLUMN "M40" HEADING "Minutes|41-50 |(&size_label) " FORMAT 999,999
COLUMN "M50" HEADING "Minutes|51-60 |(&size_label) " FORMAT 999,999
SELECT TO_CHAR(trunc(COMPLETION_TIME,'HH24'),'DD-MON-YY HH24') "Date",
to_char(COMPLETION_TIME, 'Dy') "Day",
'|' separator,
ROUND(SUM(((BLOCKS * BLOCK_SIZE)/&&size_divider))) "Total",
'|' separator,
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 01 AND 10 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M00",
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 11 AND 20 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M10",
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 21 AND 30 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M20",
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 31 AND 40 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M30",
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 41 AND 50 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M40",
ROUND(SUM(CASE WHEN TO_NUMBER(to_char(COMPLETION_TIME, 'MI')) BETWEEN 51 AND 60 THEN ROUND((BLOCKS * BLOCK_SIZE)/&&size_divider) ELSE 0 END)) "M50",
'|' separator
from v$archived_log
where standby_dest = 'NO'
and CREATOR IN ('ARCH' , 'FGRD')
AND completion_time > sysdate - &days
group by trunc(COMPLETION_TIME,'HH24'), to_char(COMPLETION_TIME, 'Dy')
order by trunc(COMPLETION_TIME,'HH24')
;

93
star/arch_switch_hist.sql Normal file
View File

@@ -0,0 +1,93 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2011 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : perf_log_switch_history_count_daily_7.sql |
-- | CLASS : Tuning |
-- | PURPOSE : Reports on how often log switches occur in your database on a |
-- | daily basis. This script is to be used with an Oracle 7 |
-- | database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
-- SET LINESIZE 145
SET PAGESIZE 9999
SET VERIFY off
ACCEPT startDate PROMPT 'Enter start date (DD-MON-YYYY): '
ACCEPT endDate PROMPT 'Enter end date (DD-MON-YYYY): '
COLUMN H00 FORMAT 999 HEADING '00'
COLUMN H01 FORMAT 999 HEADING '01'
COLUMN H02 FORMAT 999 HEADING '02'
COLUMN H03 FORMAT 999 HEADING '03'
COLUMN H04 FORMAT 999 HEADING '04'
COLUMN H05 FORMAT 999 HEADING '05'
COLUMN H06 FORMAT 999 HEADING '06'
COLUMN H07 FORMAT 999 HEADING '07'
COLUMN H08 FORMAT 999 HEADING '08'
COLUMN H09 FORMAT 999 HEADING '09'
COLUMN H10 FORMAT 999 HEADING '10'
COLUMN H11 FORMAT 999 HEADING '11'
COLUMN H12 FORMAT 999 HEADING '12'
COLUMN H13 FORMAT 999 HEADING '13'
COLUMN H14 FORMAT 999 HEADING '14'
COLUMN H15 FORMAT 999 HEADING '15'
COLUMN H16 FORMAT 999 HEADING '16'
COLUMN H17 FORMAT 999 HEADING '17'
COLUMN H18 FORMAT 999 HEADING '18'
COLUMN H19 FORMAT 999 HEADING '19'
COLUMN H20 FORMAT 999 HEADING '20'
COLUMN H21 FORMAT 999 HEADING '21'
COLUMN H22 FORMAT 999 HEADING '22'
COLUMN H23 FORMAT 999 HEADING '23'
COLUMN TOTAL FORMAT 999,999 HEADING 'Total'
SELECT
SUBSTR(time,1,5) DAY
, SUM(DECODE(SUBSTR(time,10,2),'00',1,0)) H00
, SUM(DECODE(SUBSTR(time,10,2),'01',1,0)) H01
, SUM(DECODE(SUBSTR(time,10,2),'02',1,0)) H02
, SUM(DECODE(SUBSTR(time,10,2),'03',1,0)) H03
, SUM(DECODE(SUBSTR(time,10,2),'04',1,0)) H04
, SUM(DECODE(SUBSTR(time,10,2),'05',1,0)) H05
, SUM(DECODE(SUBSTR(time,10,2),'06',1,0)) H06
, SUM(DECODE(SUBSTR(time,10,2),'07',1,0)) H07
, SUM(DECODE(SUBSTR(time,10,2),'08',1,0)) H08
, SUM(DECODE(SUBSTR(time,10,2),'09',1,0)) H09
, SUM(DECODE(SUBSTR(time,10,2),'10',1,0)) H10
, SUM(DECODE(SUBSTR(time,10,2),'11',1,0)) H11
, SUM(DECODE(SUBSTR(time,10,2),'12',1,0)) H12
, SUM(DECODE(SUBSTR(time,10,2),'13',1,0)) H13
, SUM(DECODE(SUBSTR(time,10,2),'14',1,0)) H14
, SUM(DECODE(SUBSTR(time,10,2),'15',1,0)) H15
, SUM(DECODE(SUBSTR(time,10,2),'16',1,0)) H16
, SUM(DECODE(SUBSTR(time,10,2),'17',1,0)) H17
, SUM(DECODE(SUBSTR(time,10,2),'18',1,0)) H18
, SUM(DECODE(SUBSTR(time,10,2),'19',1,0)) H19
, SUM(DECODE(SUBSTR(time,10,2),'20',1,0)) H20
, SUM(DECODE(SUBSTR(time,10,2),'21',1,0)) H21
, SUM(DECODE(SUBSTR(time,10,2),'22',1,0)) H22
, SUM(DECODE(SUBSTR(time,10,2),'23',1,0)) H23
, COUNT(*) TOTAL
FROM
v$log_history a
WHERE
(TO_DATE(SUBSTR(time, 1,8), 'MM/DD/RR')
>=
TO_DATE('&startDate', 'DD-MON-YYYY')
)
AND
(TO_DATE(SUBSTR(time, 1,8), 'MM/DD/RR')
<=
TO_DATE('&endDate', 'DD-MON-YYYY')
)
GROUP BY SUBSTR(time,1,5)
/

143
star/ash_wait_chains.sql Normal file
View File

@@ -0,0 +1,143 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: ash_wait_chains.sql (v0.6 BETA)
-- Purpose: Display ASH wait chains (multi-session wait signature, a session
-- waiting for another session etc.)
--
-- Author: Tanel Poder
-- Copyright: (c) http://blog.tanelpoder.com
--
-- Usage:
-- @ash_wait_chains <grouping_cols> <filters> <fromtime> <totime>
--
-- Example:
-- @ash_wait_chains username||':'||program2||event2 session_type='FOREGROUND' sysdate-1/24 sysdate
--
-- Other:
-- This script uses only the in-memory V$ACTIVE_SESSION_HISTORY, use
-- @dash_wait_chains.sql for accessiong the DBA_HIST_ACTIVE_SESS_HISTORY archive
--
-- Oracle 10g does not have the BLOCKING_INST_ID column in ASH so you'll need
-- to comment out this column in this script. This may give you somewhat
-- incorrect results in RAC environment with global blockers.
--
--------------------------------------------------------------------------------
COL wait_chain FOR A300 WORD_WRAP
COL distinct_sids FOR 9999 HEAD "#Blkrs"
COL "%This" FOR A6
PROMPT
PROMPT -- Display ASH Wait Chain Signatures script v0.6 BETA by Tanel Poder ( http://blog.tanelpoder.com )
WITH
bclass AS (SELECT /*+ INLINE */ class, ROWNUM r from v$waitstat),
ash AS (SELECT /*+ INLINE QB_NAME(ash) LEADING(a) USE_HASH(u) SWAP_JOIN_INPUTS(u) */
a.*
, o.*
, u.username
, CASE WHEN a.session_type = 'BACKGROUND' AND a.program LIKE '%(DBW%)' THEN
'(DBWn)'
WHEN a.session_type = 'BACKGROUND' OR REGEXP_LIKE(a.program, '.*\([PJ]\d+\)') THEN
REGEXP_REPLACE(SUBSTR(a.program,INSTR(a.program,'(')), '\d', 'n')
ELSE
'('||REGEXP_REPLACE(REGEXP_REPLACE(a.program, '(.*)@(.*)(\(.*\))', '\1'), '\d', 'n')||')'
END || ' ' program2
, NVL(a.event||CASE WHEN event like 'enq%' AND session_state = 'WAITING'
THEN ' [mode='||BITAND(p1, POWER(2,14)-1)||']'
WHEN a.event IN (SELECT name FROM v$event_name WHERE parameter3 = 'class#')
THEN ' ['||NVL((SELECT class FROM bclass WHERE r = a.p3),'undo @bclass '||a.p3)||']' ELSE null END,'ON CPU')
|| ' ' event2
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p1 ELSE null END, '0XXXXXXXXXXXXXXX') p1hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p3 ELSE null END, '0XXXXXXXXXXXXXXX') p3hex
, CASE WHEN BITAND(time_model, POWER(2, 01)) = POWER(2, 01) THEN 'DBTIME ' END
||CASE WHEN BITAND(time_model, POWER(2, 02)) = POWER(2, 02) THEN 'BACKGROUND ' END
||CASE WHEN BITAND(time_model, POWER(2, 03)) = POWER(2, 03) THEN 'CONNECTION_MGMT ' END
||CASE WHEN BITAND(time_model, POWER(2, 04)) = POWER(2, 04) THEN 'PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 05)) = POWER(2, 05) THEN 'FAILED_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 06)) = POWER(2, 06) THEN 'NOMEM_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 07)) = POWER(2, 07) THEN 'HARD_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 08)) = POWER(2, 08) THEN 'NO_SHARERS_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 09)) = POWER(2, 09) THEN 'BIND_MISMATCH_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 10)) = POWER(2, 10) THEN 'SQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 11)) = POWER(2, 11) THEN 'PLSQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 12)) = POWER(2, 12) THEN 'PLSQL_RPC ' END
||CASE WHEN BITAND(time_model, POWER(2, 13)) = POWER(2, 13) THEN 'PLSQL_COMPILATION ' END
||CASE WHEN BITAND(time_model, POWER(2, 14)) = POWER(2, 14) THEN 'JAVA_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 15)) = POWER(2, 15) THEN 'BIND ' END
||CASE WHEN BITAND(time_model, POWER(2, 16)) = POWER(2, 16) THEN 'CURSOR_CLOSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 17)) = POWER(2, 17) THEN 'SEQUENCE_LOAD ' END
||CASE WHEN BITAND(time_model, POWER(2, 18)) = POWER(2, 18) THEN 'INMEMORY_QUERY ' END
||CASE WHEN BITAND(time_model, POWER(2, 19)) = POWER(2, 19) THEN 'INMEMORY_POPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 20)) = POWER(2, 20) THEN 'INMEMORY_PREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 21)) = POWER(2, 21) THEN 'INMEMORY_REPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 22)) = POWER(2, 22) THEN 'INMEMORY_TREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 23)) = POWER(2, 23) THEN 'TABLESPACE_ENCRYPTION ' END time_model_name
FROM
gv$active_session_history a
, dba_users u
, (SELECT
object_id,data_object_id,owner,object_name,subobject_name,object_type
, owner||'.'||object_name obj
, owner||'.'||object_name||' ['||object_type||']' objt
FROM dba_objects) o
WHERE
a.user_id = u.user_id (+)
AND a.current_obj# = o.object_id(+)
AND sample_time BETWEEN &3 AND &4
),
ash_samples AS (SELECT /*+ INLINE */ DISTINCT sample_id FROM ash),
ash_data AS (SELECT /*+ INLINE */ * FROM ash),
chains AS (
SELECT /*+ INLINE */
sample_time ts
, level lvl
, session_id sid
, REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 AND d.blocking_session IS NOT NULL THEN ' -> [idle blocker '||d.blocking_inst_id||','||d.blocking_session||','||d.blocking_session_serial#||(SELECT ' ('||s.program||')' FROM gv$session s WHERE (s.inst_id, s.sid , s.serial#) = ((d.blocking_inst_id,d.blocking_session,d.blocking_session_serial#)))||']' ELSE NULL END path -- there's a reason why I'm doing this
--, SYS_CONNECT_BY_PATH(&1, ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 THEN '('||d.session_id||')' ELSE NULL END path
-- , REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 AND LEVEL > 1 THEN ' [sid='||session_id||' seq#='||TO_CHAR(seq#)||']' ELSE NULL END path -- there's a reason why I'm doing this
--, REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ') path -- there's a reason why I'm doing this (ORA-30004 :)
, CASE WHEN CONNECT_BY_ISLEAF = 1 THEN d.session_id ELSE NULL END sids
, CONNECT_BY_ISLEAF isleaf
, CONNECT_BY_ISCYCLE iscycle
, d.*
FROM
ash_samples s
, ash_data d
WHERE
s.sample_id = d.sample_id
AND d.sample_time BETWEEN &3 AND &4
CONNECT BY NOCYCLE
( PRIOR d.blocking_session = d.session_id
AND PRIOR d.blocking_inst_id = d.inst_id
AND PRIOR s.sample_id = d.sample_id
)
START WITH &2
)
SELECT * FROM (
SELECT
LPAD(ROUND(RATIO_TO_REPORT(COUNT(*)) OVER () * 100)||'%',5,' ') "%This"
, COUNT(*) seconds
, ROUND(COUNT(*) / ((CAST(&4 AS DATE) - CAST(&3 AS DATE)) * 86400), 1) AAS
, COUNT(DISTINCT sids) distinct_sids
, path wait_chain
, TO_CHAR(MIN(sample_time), 'YYYY-MM-DD HH24:MI:SS') first_seen
, TO_CHAR(MAX(sample_time), 'YYYY-MM-DD HH24:MI:SS') last_seen
-- , MIN(sids)
-- , MAX(sids)
FROM
chains
WHERE
isleaf = 1
GROUP BY
&1
, path
ORDER BY
COUNT(*) DESC
)
WHERE
ROWNUM <= 30
/

133
star/ashtop.sql Normal file
View File

@@ -0,0 +1,133 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: ashtop.sql v1.2
-- Purpose: Display top ASH time (count of ASH samples) grouped by your
-- specified dimensions
--
-- Author: Tanel Poder
-- Copyright: (c) http://blog.tanelpoder.com
--
-- Usage:
-- @ashtop <grouping_cols> <filters> <fromtime> <totime>
--
-- Example:
-- @ashtop username,sql_id session_type='FOREGROUND' sysdate-1/24 sysdate
--
-- Other:
-- This script uses only the in-memory GV$ACTIVE_SESSION_HISTORY, use
-- @dashtop.sql for accessiong the DBA_HIST_ACTIVE_SESS_HISTORY archive
--
--------------------------------------------------------------------------------
COL "%This" FOR A7
--COL p1 FOR 99999999999999
--COL p2 FOR 99999999999999
--COL p3 FOR 99999999999999
COL p1text FOR A30 word_wrap
COL p2text FOR A30 word_wrap
COL p3text FOR A30 word_wrap
COL p1hex FOR A17
COL p2hex FOR A17
COL p3hex FOR A17
COL dop FOR 99
COL AAS FOR 9999.9
COL totalseconds HEAD "Total|Seconds" FOR 99999999
COL dist_sqlexec_seen HEAD "Distinct|Execs Seen" FOR 999999
COL dist_timestamps HEAD "Distinct|Tstamps" FOR 999999
COL event FOR A42 WORD_WRAP
COL event2 FOR A42 WORD_WRAP
COL time_model_name FOR A50 WORD_WRAP
COL program2 FOR A40 TRUNCATE
COL username FOR A20 wrap
COL obj FOR A30
COL objt FOR A50
COL sql_opname FOR A20
COL top_level_call_name FOR A30
COL wait_class FOR A15
SELECT
*
FROM (
WITH bclass AS (SELECT /*+ INLINE */ class, ROWNUM r from v$waitstat)
SELECT /*+ LEADING(a) USE_HASH(u) */
COUNT(*) totalseconds
, ROUND(COUNT(*) / ((CAST(&4 AS DATE) - CAST(&3 AS DATE)) * 86400), 1) AAS
, LPAD(ROUND(RATIO_TO_REPORT(COUNT(*)) OVER () * 100)||'%',5,' ')||' |' "%This"
, &1
, TO_CHAR(MIN(sample_time), 'YYYY-MM-DD HH24:MI:SS') first_seen
, TO_CHAR(MAX(sample_time), 'YYYY-MM-DD HH24:MI:SS') last_seen
-- , MAX(sql_exec_id) - MIN(sql_exec_id)
, COUNT(DISTINCT sql_exec_start||':'||sql_exec_id) dist_sqlexec_seen
, COUNT(DISTINCT sample_time) dist_timestamps
FROM
(SELECT
a.*
, session_id sid
, session_serial# serial
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p1 ELSE null END, '0XXXXXXXXXXXXXXX') p1hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p3 ELSE null END, '0XXXXXXXXXXXXXXX') p3hex
, TRUNC(px_flags / 2097152) dop
, NVL(a.event, a.session_state)||
CASE
WHEN a.event like 'enq%' AND session_state = 'WAITING'
THEN ' [mode='||BITAND(p1, POWER(2,14)-1)||']'
WHEN a.event IN (SELECT name FROM v$event_name WHERE parameter3 = 'class#')
THEN ' ['||CASE WHEN a.p3 <= (SELECT MAX(r) FROM bclass)
THEN (SELECT class FROM bclass WHERE r = a.p3)
ELSE (SELECT DECODE(MOD(BITAND(a.p3,TO_NUMBER('FFFF','XXXX')) - 17,2),0,'undo header',1,'undo data', 'error') FROM dual)
END ||']'
ELSE null
END event2 -- event is NULL in ASH if the session is not waiting (session_state = ON CPU)
, CASE WHEN a.session_type = 'BACKGROUND' OR REGEXP_LIKE(a.program, '.*\([PJ]\d+\)') THEN
REGEXP_REPLACE(SUBSTR(a.program,INSTR(a.program,'(')), '\d', 'n')
ELSE
'('||REGEXP_REPLACE(REGEXP_REPLACE(a.program, '(.*)@(.*)(\(.*\))', '\1'), '\d', 'n')||')'
END || ' ' program2
, CASE WHEN BITAND(time_model, POWER(2, 01)) = POWER(2, 01) THEN 'DBTIME ' END
||CASE WHEN BITAND(time_model, POWER(2, 02)) = POWER(2, 02) THEN 'BACKGROUND ' END
||CASE WHEN BITAND(time_model, POWER(2, 03)) = POWER(2, 03) THEN 'CONNECTION_MGMT ' END
||CASE WHEN BITAND(time_model, POWER(2, 04)) = POWER(2, 04) THEN 'PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 05)) = POWER(2, 05) THEN 'FAILED_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 06)) = POWER(2, 06) THEN 'NOMEM_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 07)) = POWER(2, 07) THEN 'HARD_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 08)) = POWER(2, 08) THEN 'NO_SHARERS_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 09)) = POWER(2, 09) THEN 'BIND_MISMATCH_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 10)) = POWER(2, 10) THEN 'SQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 11)) = POWER(2, 11) THEN 'PLSQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 12)) = POWER(2, 12) THEN 'PLSQL_RPC ' END
||CASE WHEN BITAND(time_model, POWER(2, 13)) = POWER(2, 13) THEN 'PLSQL_COMPILATION ' END
||CASE WHEN BITAND(time_model, POWER(2, 14)) = POWER(2, 14) THEN 'JAVA_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 15)) = POWER(2, 15) THEN 'BIND ' END
||CASE WHEN BITAND(time_model, POWER(2, 16)) = POWER(2, 16) THEN 'CURSOR_CLOSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 17)) = POWER(2, 17) THEN 'SEQUENCE_LOAD ' END
||CASE WHEN BITAND(time_model, POWER(2, 18)) = POWER(2, 18) THEN 'INMEMORY_QUERY ' END
||CASE WHEN BITAND(time_model, POWER(2, 19)) = POWER(2, 19) THEN 'INMEMORY_POPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 20)) = POWER(2, 20) THEN 'INMEMORY_PREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 21)) = POWER(2, 21) THEN 'INMEMORY_REPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 22)) = POWER(2, 22) THEN 'INMEMORY_TREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 23)) = POWER(2, 23) THEN 'TABLESPACE_ENCRYPTION ' END time_model_name
FROM gv$active_session_history a) a
, dba_users u
, (SELECT
object_id,data_object_id,owner,object_name,subobject_name,object_type
, owner||'.'||object_name obj
, owner||'.'||object_name||' ['||object_type||']' objt
FROM dba_objects) o
WHERE
a.user_id = u.user_id (+)
AND a.current_obj# = o.object_id(+)
AND &2
AND sample_time BETWEEN &3 AND &4
GROUP BY
&1
ORDER BY
TotalSeconds DESC
, &1
)
WHERE
ROWNUM <= 15
/

111
star/asqlmon.sql Normal file
View File

@@ -0,0 +1,111 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
------------------------------------------------------------------------------------------------------------------------
--
-- File name: asqlmon.sql (v1.3)
--
-- Purpose: Report SQL-monitoring-style drill-down into where in an execution plan the execution time is spent
--
-- Author: Tanel Poder
--
-- Copyright: (c) http://blog.tanelpoder.com - All rights reserved.
--
-- Disclaimer: This script is provided "as is", no warranties nor guarantees are
-- made. Use at your own risk :)
--
-- Usage: @asqlmon <sqlid> <child#> <from_time> <to_time>
--
-- Notes: This script runs on Oracle 11g+ and you should have the
-- Diagnostics pack license for using it as it queries
-- some separately licensed views.
--
------------------------------------------------------------------------------------------------------------------------
SET LINESIZE 999 PAGESIZE 5000 TRIMOUT ON TRIMSPOOL ON
COL asqlmon_operation HEADING Plan_Operation FORMAT A72
COL asqlmon_predicates HEAD PREDICATES FOR a100 word_wrap
COL obj_alias_qbc_name FOR a40
COL options FOR a30
COL asqlmon_plan_hash_value HEAD PLAN_HASH_VALUE FOR 99999999999
COL asqlmon_sql_id HEAD SQL_ID
COL asqlmon_sql_child HEAD CHILD FOR 999999
COL pct_child HEAD "Activity %" FOR A8
COL pct_child_vis HEAD "Visual" FOR A12
COL asqlmon_id HEAD "ID" FOR 9999
COL asqlmon_parent_id HEAD "PID" FOR 9999
BREAK ON asqlmon_sql_id SKIP 1 ON asqlmon_sql_child SKIP 1 ON asqlmon_plan_hash_value SKIP 1 ON asqlmon_operation
PROMPT
PROMPT -- ASQLMon v1.3 - by Tanel Poder ( https://tanelpoder.com ) - Display SQL execution plan line level activity breakdown from ASH
WITH sample_times AS (
select * from dual
),
sq AS (
SELECT
count(*) samples
, ash.sql_id
, ash.sql_child_number
, ash.sql_plan_hash_value
, NVL(ash.sql_plan_line_id,1) sql_plan_line_id -- this is because simple "planless" operations like single-row insert
, ash.sql_plan_operation
, ash.sql_plan_options
, ash.session_state
, ash.event
-- , AVG(ash.p3) avg_p3 -- p3 is sometimes useful for listing block counts for IO wait events
FROM
v$active_session_history ash
WHERE
1=1
AND ash.sql_id LIKE '&1'
AND ash.sql_child_number LIKE '&2'
AND ash.sample_time BETWEEN &3 AND &4
GROUP BY
ash.sql_id
, ash.sql_child_number
, ash.sql_plan_hash_value
, NVL(ash.sql_plan_line_id,1)
, ash.sql_plan_operation
, ash.sql_plan_options
, ash.session_state
, ash.event
)
SELECT
-- plan.sql_id asqlmon_sql_id
plan.child_number asqlmon_sql_child
, plan.plan_hash_value asqlmon_plan_hash_value
, sq.samples seconds
, LPAD(TO_CHAR(ROUND(RATIO_TO_REPORT(sq.samples) OVER (PARTITION BY sq.sql_id, sq.sql_plan_hash_value) * 100, 1), 999.9)||' %',8) pct_child
, '|'||RPAD( NVL( LPAD('#', ROUND(RATIO_TO_REPORT(sq.samples) OVER (PARTITION BY sq.sql_id, sq.sql_plan_hash_value) * 10), '#'), ' '), 10,' ')||'|' pct_child_vis
--, LPAD(plan.id,4)||CASE WHEN parent_id IS NULL THEN ' ' ELSE ' <- ' END||LPAD(plan.parent_id,4) asqlmon_plan_id
, plan.id asqlmon_id
, plan.parent_id asqlmon_parent_id
, LPAD(' ', depth, ' ') || plan.operation ||' '|| plan.options || NVL2(plan.object_name, ' ['||plan.object_name ||']', null) asqlmon_operation
, sq.session_state
, sq.event
-- , sq.avg_p3
, plan.object_alias || CASE WHEN plan.qblock_name IS NOT NULL THEN ' ['|| plan.qblock_name || ']' END obj_alias_qbc_name
-- , CASE WHEN plan.access_predicates IS NOT NULL THEN '[A:] '|| SUBSTR(plan.access_predicates,1,1990) END || CASE WHEN plan.filter_predicates IS NOT NULL THEN ' [F:] ' || SUBSTR(plan.filter_predicates,1,1990) END asqlmon_predicates
-- , plan.projection
FROM
v$sql_plan plan
, sq
WHERE
1=1
AND sq.sql_id(+) = plan.sql_id
AND sq.sql_child_number(+) = plan.child_number
AND sq.sql_plan_line_id(+) = plan.id
AND sq.sql_plan_hash_value(+) = plan.plan_hash_value
AND plan.sql_id LIKE '&1'
AND plan.child_number LIKE '&2'
ORDER BY
plan.child_number
, plan.plan_hash_value
, plan.id
/

2
star/awr_snapshot.sql Normal file
View File

@@ -0,0 +1,2 @@
-- Create AWR snapshot
EXEC DBMS_WORKLOAD_REPOSITORY.create_snapshot;

129
star/awr_sql_binds.sql Normal file
View File

@@ -0,0 +1,129 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display SQL Binds from AWR
* Version : 10.2 and above
* Parameters : 1 - SQL_ID
* 2 - Number of Days (Default 7 days)
* 2 - Whereclause
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 27-Aug-15 Vishal Gupta Created
*
*
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE sql_id
UNDEFINE days
UNDEFINE whereclause
UNDEFINE force_matching_signature
UNDEFINE use_force_matching_signature
DEFINE sql_id="&&1"
DEFINE days="&&2"
DEFINE whereclause="&&3"
DEFINE force_matching_signature=""
COLUMN _days NEW_VALUE days NOPRINT
COLUMN _force_matching_signature NEW_VALUE force_matching_signature NOPRINT
set term off
SELECT DECODE('&&days','','7','&&days') "_days"
, DECODE('&&sql_id','%','%','') "_force_matching_signature"
FROM DUAL
;
set term on
COLUMN _force_matching_signature NEW_VALUE force_matching_signature NOPRINT
set term off
select to_char(ss2.force_matching_signature) "_force_matching_signature"
from v$database d
, dba_hist_sqlstat ss2
where d.dbid = ss2.dbid
AND ss2.sql_id = '&&sql_id' and rownum = 1;
select CASE WHEN '&&force_matching_signature' IS NULL THEN '0'
WHEN '&&force_matching_signature' = '' THEN '0'
ELSE '&&force_matching_signature'
END "_force_matching_signature"
from dual
;
set term on
/************************************/
Prompt
Prompt **************************************************************
Prompt * AWR SQL Bind Values
Prompt * (Force Matching Signature = '&&force_matching_signature')
PROMPT *
PROMPT * Input Parameters
PROMPT * - SQL Id = '&&sql_id'
PROMPT * - Days = '&&days'
PROMPT * - WhereClause = '&&whereclause'
Prompt **************************************************************
COLUMN seperator HEADING "!|!|!|!" FORMAT a1
COLUMN end_interval_time HEADING "Snap Time" FORMAT a15
COLUMN instance_number HEADING "I#" FORMAT 99
COLUMN SQL_ID HEADING "SQLId" FORMAT a13
COLUMN plan_hash_value HEADING "Plan|Hash|Value" FORMAT 999999999999
COLUMN bind_values HEADING "Bind Values" FORMAT a100
COLUMN bind_datatype HEADING "Bind DataType" FORMAT a80
SELECT TO_CHAR(s.end_interval_time,'DD-MON-YY HH24:MI') end_interval_time
, ss.instance_number
, ss.sql_id
, ss.plan_hash_value
, (select listagg(NVL(name,':B' || position)
||'['
|| datatype_string || NVL2(scale
,'(' || scale || NVL2(precision,','|| precision,'') || ')'
,''
)
|| ']'
||'='
|| CASE
WHEN datatype_string <> 'TIMESTAMP' THEN NVL(value_string,'NULL')
ELSE TO_CHAR(ANYDATA.ACCESStimestamp(VALUE_ANYDATA))
END
,','
) WITHIN GROUP (order by position)
from table(dbms_sqltune.extract_binds(ss.BIND_DATA))
) bind_values
/*
, (select listagg(NVL(name,':B' || position) || '='
|| datatype_string || NVL2(scale,'(' || scale || NVL2(precision,','|| precision, '') || ')' ,'' )
,','
) WITHIN GROUP (order by position)
from table(dbms_sqltune.extract_binds(ss.BIND_DATA))
) bind_datatype
*/
from v$database d
JOIN dba_hist_snapshot s ON s.dbid = d.dbid
JOIN dba_hist_sqlstat ss ON ss.dbid = s.dbid AND ss.instance_number = s.instance_number AND ss.snap_id = s.snap_id
AND ss.executions_delta > 0
where s.end_interval_time > SYSDATE - &&days
AND ss.sql_id LIKE CASE ss.force_matching_signature
WHEN 0 THEN '&&sql_id'
ELSE '%'
END
AND ss.force_matching_signature = '&&force_matching_signature'
&&whereclause
ORDER BY s.end_interval_time
, ss.instance_number
;

12
star/awr_sqlid.sql Normal file
View File

@@ -0,0 +1,12 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
COL sql_text FOR A200 WORD_WRAP
SELECT
*
FROM
dba_hist_sqltext
WHERE
sql_id = '&1'
/

53
star/awrsign.sql Normal file
View File

@@ -0,0 +1,53 @@
COLUMN iname HEADING "Instance" FORMAT A8
COLUMN snap_id HEADING "Snap|Id" FORMAT 9999999
COLUMN endsnaptime HEADING "End|snaphot|time" FORMAT A11
COLUMN sql_id HEADING "SQL_ID" FORMAT A13
COLUMN plan_hash_value HEADING "Plan|hash|value"
COLUMN executions_delta HEADING "#Ex" FORMAT 9999999
COLUMN end_of_fetch_count_delta HEADING "#EOF" FORMAT 9999999
COLUMN buffer_gets_delta HEADING "Buffer|gets"
COLUMN bufferperexec HEADING "Buffer|gets|/exec" FORMAT 9999999999
COLUMN optimizer_cost HEADING "0ptimizer|cost"
COLUMN rows_processed_delta HEADING "#Rows"
COLUMN sql_profile HEADING "SQL|Prof" FORMAT A4
COLUMN elapsed_time_delta HEADING "Elapsed|time|/exec|(sec)" FORMAT 99999
COLUMN cpu_time_delta HEADING "CPU|time|/exec|(sec)" FORMAT 9999
COLUMN iowait_delta HEADING "IO|time|/exec|(sec)" FORMAT 99999
COLUMN px_servers_execs_delta HEADING "Px" FORMAT 9999
COLUMN disk_reads_delta HEADING "Disk|reads"
COLUMN io_offload_elig_bytes_delta HEADING "Elig|Mb" FORMAT 999999
COLUMN io_interconnect_bytes_delta HEADING "Inter|Mb" FORMAT 999999
select
i.instance_name iname,
snap_id,
to_char(end_interval_time,'dd/mm hh24:mi') endsnaptime,
sql_id,
plan_hash_value,
optimizer_cost,
executions_delta,
end_of_fetch_count_delta,
buffer_gets_delta,
buffer_gets_delta/executions_delta bufferperexec,
decode (sql_profile,null, '',substr(sql_profile,1,4)) sql_profile,
px_servers_execs_delta,
disk_reads_delta,
round(elapsed_time_delta/1000000) elapsed_time_delta,
round(cpu_time_delta/1000000) cpu_time_delta,
round(iowait_delta/1000000) iowait_delta,
io_offload_elig_bytes_delta/1024/1024 io_offload_elig_bytes_delta,
io_interconnect_bytes_delta/1024/1024 io_interconnect_bytes_delta,
rows_processed_delta
from
dba_hist_sqlstat sqlstat
join dba_hist_snapshot snap using (snap_id,instance_number)
join gv$instance i using (instance_number)
where
snap.begin_interval_time>=&&2
and snap.end_interval_time<=&&3
and force_matching_signature='&&1'
and executions_delta>0
order by
snap_id asc
/

51
star/awrsqlid.sql Normal file
View File

@@ -0,0 +1,51 @@
COLUMN iname HEADING "Instance" FORMAT A8
COLUMN snap_id HEADING "Snap|Id" FORMAT 9999999
COLUMN endsnaptime HEADING "End|snaphot|time" FORMAT A11
COLUMN plan_hash_value HEADING "Plan|hash|value"
COLUMN executions_delta HEADING "#Ex" FORMAT 9999999
COLUMN end_of_fetch_count_delta HEADING "#EOF" FORMAT 9999999
COLUMN buffer_gets_delta HEADING "Buffer|gets"
COLUMN bufferperexec HEADING "Buffer|gets|/exec" FORMAT 9999999999
COLUMN optimizer_cost HEADING "0ptimizer|cost"
COLUMN rows_processed_delta HEADING "#Rows"
COLUMN sql_profile HEADING "SQL|Prof" FORMAT A4
COLUMN elapsed_time_delta HEADING "Elapsed|time|/exec|(sec)" FORMAT 99999
COLUMN cpu_time_delta HEADING "CPU|time|/exec|(sec)" FORMAT 9999
COLUMN iowait_delta HEADING "IO|time|/exec|(sec)" FORMAT 99999
COLUMN px_servers_execs_delta HEADING "Px" FORMAT 99999
COLUMN disk_reads_delta HEADING "Disk|reads"
COLUMN io_offload_elig_bytes_delta HEADING "Elig|Mb" FORMAT 999999
COLUMN io_interconnect_bytes_delta HEADING "Inter|Mb" FORMAT 999999
select
i.instance_name iname,
snap_id,
to_char(end_interval_time,'dd/mm hh24:mi') endsnaptime,
plan_hash_value,
optimizer_cost,
executions_delta,
end_of_fetch_count_delta,
buffer_gets_delta,
buffer_gets_delta/executions_delta bufferperexec,
decode (sql_profile,null, '',substr(sql_profile,1,4)) sql_profile,
px_servers_execs_delta,
disk_reads_delta,
round(elapsed_time_delta/1000000) elapsed_time_delta,
round(cpu_time_delta/1000000) cpu_time_delta,
round(iowait_delta/1000000) iowait_delta,
io_offload_elig_bytes_delta/1024/1024 io_offload_elig_bytes_delta,
io_interconnect_bytes_delta/1024/1024 io_interconnect_bytes_delta,
rows_processed_delta
from
dba_hist_sqlstat sqlstat
join dba_hist_snapshot snap using (snap_id,instance_number)
join gv$instance i using (instance_number)
where
snap.begin_interval_time>=&&2
and snap.end_interval_time<=&&3
and sql_id='&&1'
and executions_delta>0
order by
snap_id asc
/

View File

@@ -0,0 +1,484 @@
SPO coe_xfr_sql_profile.log;
SET DEF ON TERM OFF ECHO ON FEED OFF VER OFF HEA ON LIN 2000 PAGES 100 LONG 8000000 LONGC 800000 TRIMS ON TI OFF TIMI OFF SERVEROUT ON SIZE 1000000 NUMF "" SQLP SQL>;
SET SERVEROUT ON SIZE UNL;
REM
REM $Header: 215187.1 coe_xfr_sql_profile.sql 11.4.5.5 2013/03/01 carlos.sierra $
REM
REM Copyright (c) 2000-2013, Oracle Corporation. All rights reserved.
REM
REM AUTHOR
REM carlos.sierra@oracle.com
REM
REM SCRIPT
REM coe_xfr_sql_profile.sql
REM
REM DESCRIPTION
REM This script generates another that contains the commands to
REM create a manual custom SQL Profile out of a known plan from
REM memory or AWR. The manual custom profile can be implemented
REM into the same SOURCE system where the plan was retrieved,
REM or into another similar TARGET system that has same schema
REM objects referenced by the SQL that generated the known plan.
REM
REM PRE-REQUISITES
REM 1. Oracle Tuning Pack license.
REM
REM PARAMETERS
REM 1. SQL_ID (required)
REM 2. Plan Hash Value for which a manual custom SQL Profile is
REM needed (required). A list of known plans is presented.
REM You may choose from list provided or enter a valid phv
REM from a version of the SQL modified with Hints.
REM
REM EXECUTION
REM 1. Connect into SQL*Plus as user with access to data dictionary.
REM Do not use SYS.
REM 2. Execute script coe_xfr_sql_profile.sql passing SQL_ID and
REM plan hash value (parameters can be passed inline or until
REM requested).
REM
REM EXAMPLE
REM # sqlplus system
REM SQL> START coe_xfr_sql_profile.sql [SQL_ID] [PLAN_HASH_VALUE];
REM SQL> START coe_xfr_sql_profile.sql gnjy0mn4y9pbm 2055843663;
REM SQL> START coe_xfr_sql_profile.sql gnjy0mn4y9pbm;
REM SQL> START coe_xfr_sql_profile.sql;
REM
REM NOTES
REM 1. For possible errors see coe_xfr_sql_profile.log
REM 2. If SQLT is installed in SOURCE, you can use instead:
REM sqlt/utl/sqltprofile.sql
REM 3. Be aware that using DBMS_SQLTUNE requires a license for
REM Oracle Tuning Pack.
REM 4. Use a DBA user but not SYS.
REM
SET TERM ON ECHO OFF;
PRO
PRO Parameter 1:
PRO SQL_ID (required)
PRO
DEF sql_id = '&1';
PRO
WITH
p AS (
SELECT plan_hash_value
FROM gv$sql_plan
WHERE sql_id = TRIM('&&sql_id.')
AND other_xml IS NOT NULL
UNION
SELECT plan_hash_value
FROM dba_hist_sql_plan
WHERE sql_id = TRIM('&&sql_id.')
AND other_xml IS NOT NULL ),
m AS (
SELECT plan_hash_value,
SUM(elapsed_time)/SUM(executions) avg_et_secs
FROM gv$sql
WHERE sql_id = TRIM('&&sql_id.')
AND executions > 0
GROUP BY
plan_hash_value ),
a AS (
SELECT plan_hash_value,
SUM(elapsed_time_total)/SUM(executions_total) avg_et_secs
FROM dba_hist_sqlstat
WHERE sql_id = TRIM('&&sql_id.')
AND executions_total > 0
GROUP BY
plan_hash_value )
SELECT p.plan_hash_value,
ROUND(NVL(m.avg_et_secs, a.avg_et_secs)/1e6, 3) avg_et_secs
FROM p, m, a
WHERE p.plan_hash_value = m.plan_hash_value(+)
AND p.plan_hash_value = a.plan_hash_value(+)
ORDER BY
avg_et_secs NULLS LAST;
PRO
PRO Parameter 2:
PRO PLAN_HASH_VALUE (required)
PRO
DEF plan_hash_value = '&2';
PRO
PRO Values passed to coe_xfr_sql_profile:
PRO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PRO SQL_ID : "&&sql_id."
PRO PLAN_HASH_VALUE: "&&plan_hash_value."
PRO
SET TERM OFF ECHO ON;
WHENEVER SQLERROR EXIT SQL.SQLCODE;
-- trim parameters
COL sql_id NEW_V sql_id FOR A30;
COL plan_hash_value NEW_V plan_hash_value FOR A30;
SELECT TRIM('&&sql_id.') sql_id, TRIM('&&plan_hash_value.') plan_hash_value FROM DUAL;
VAR sql_text CLOB;
VAR sql_text2 CLOB;
VAR other_xml CLOB;
EXEC :sql_text := NULL;
EXEC :sql_text2 := NULL;
EXEC :other_xml := NULL;
-- get sql_text from memory
DECLARE
l_sql_text VARCHAR2(32767);
BEGIN -- 10g see bug 5017909
FOR i IN (SELECT DISTINCT piece, sql_text
FROM gv$sqltext_with_newlines
WHERE sql_id = TRIM('&&sql_id.')
ORDER BY 1, 2)
LOOP
IF :sql_text IS NULL THEN
DBMS_LOB.CREATETEMPORARY(:sql_text, TRUE);
DBMS_LOB.OPEN(:sql_text, DBMS_LOB.LOB_READWRITE);
END IF;
-- removes NUL characters
l_sql_text := REPLACE(i.sql_text, CHR(00), ' ');
-- adds a NUL character at the end of each line
DBMS_LOB.WRITEAPPEND(:sql_text, LENGTH(l_sql_text) + 1, l_sql_text||CHR(00));
END LOOP;
-- if found in memory then sql_text is not null
IF :sql_text IS NOT NULL THEN
DBMS_LOB.CLOSE(:sql_text);
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting sql_text from memory: '||SQLERRM);
:sql_text := NULL;
END;
/
SELECT :sql_text FROM DUAL;
-- get sql_text from awr
DECLARE
l_sql_text VARCHAR2(32767);
l_clob_size NUMBER;
l_offset NUMBER;
BEGIN
IF :sql_text IS NULL OR NVL(DBMS_LOB.GETLENGTH(:sql_text), 0) = 0 THEN
SELECT sql_text
INTO :sql_text2
FROM dba_hist_sqltext
WHERE sql_id = TRIM('&&sql_id.')
AND sql_text IS NOT NULL
AND ROWNUM = 1;
END IF;
-- if found in awr then sql_text2 is not null
IF :sql_text2 IS NOT NULL THEN
l_clob_size := NVL(DBMS_LOB.GETLENGTH(:sql_text2), 0);
l_offset := 1;
DBMS_LOB.CREATETEMPORARY(:sql_text, TRUE);
DBMS_LOB.OPEN(:sql_text, DBMS_LOB.LOB_READWRITE);
-- store in clob as 64 character pieces plus a NUL character at the end of each piece
WHILE l_offset < l_clob_size
LOOP
IF l_clob_size - l_offset > 64 THEN
l_sql_text := REPLACE(DBMS_LOB.SUBSTR(:sql_text2, 64, l_offset), CHR(00), ' ');
ELSE -- last piece
l_sql_text := REPLACE(DBMS_LOB.SUBSTR(:sql_text2, l_clob_size - l_offset + 1, l_offset), CHR(00), ' ');
END IF;
DBMS_LOB.WRITEAPPEND(:sql_text, LENGTH(l_sql_text) + 1, l_sql_text||CHR(00));
l_offset := l_offset + 64;
END LOOP;
DBMS_LOB.CLOSE(:sql_text);
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting sql_text from awr: '||SQLERRM);
:sql_text := NULL;
END;
/
SELECT :sql_text2 FROM DUAL;
SELECT :sql_text FROM DUAL;
-- validate sql_text
SET TERM ON;
BEGIN
IF :sql_text IS NULL THEN
RAISE_APPLICATION_ERROR(-20100, 'SQL_TEXT for SQL_ID &&sql_id. was not found in memory (gv$sqltext_with_newlines) or AWR (dba_hist_sqltext).');
END IF;
END;
/
SET TERM OFF;
-- get other_xml from memory
BEGIN
FOR i IN (SELECT other_xml
FROM gv$sql_plan
WHERE sql_id = TRIM('&&sql_id.')
AND plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
AND other_xml IS NOT NULL
ORDER BY
child_number, id)
LOOP
:other_xml := i.other_xml;
EXIT; -- 1st
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting other_xml from memory: '||SQLERRM);
:other_xml := NULL;
END;
/
-- get other_xml from awr
BEGIN
IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
FOR i IN (SELECT other_xml
FROM dba_hist_sql_plan
WHERE sql_id = TRIM('&&sql_id.')
AND plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
AND other_xml IS NOT NULL
ORDER BY
id)
LOOP
:other_xml := i.other_xml;
EXIT; -- 1st
END LOOP;
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting other_xml from awr: '||SQLERRM);
:other_xml := NULL;
END;
/
-- get other_xml from memory from modified SQL
BEGIN
IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
FOR i IN (SELECT other_xml
FROM gv$sql_plan
WHERE plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
AND other_xml IS NOT NULL
ORDER BY
child_number, id)
LOOP
:other_xml := i.other_xml;
EXIT; -- 1st
END LOOP;
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting other_xml from memory: '||SQLERRM);
:other_xml := NULL;
END;
/
-- get other_xml from awr from modified SQL
BEGIN
IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
FOR i IN (SELECT other_xml
FROM dba_hist_sql_plan
WHERE plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
AND other_xml IS NOT NULL
ORDER BY
id)
LOOP
:other_xml := i.other_xml;
EXIT; -- 1st
END LOOP;
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('getting other_xml from awr: '||SQLERRM);
:other_xml := NULL;
END;
/
SELECT :other_xml FROM DUAL;
-- validate other_xml
SET TERM ON;
BEGIN
IF :other_xml IS NULL THEN
RAISE_APPLICATION_ERROR(-20101, 'PLAN for SQL_ID &&sql_id. and PHV &&plan_hash_value. was not found in memory (gv$sql_plan) or AWR (dba_hist_sql_plan).');
END IF;
END;
/
SET TERM OFF;
-- generates script that creates sql profile in target system:
SET ECHO OFF;
PRO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql.
SET FEED OFF LIN 666 TRIMS ON TI OFF TIMI OFF SERVEROUT ON SIZE 1000000 FOR WOR;
SET SERVEROUT ON SIZE UNL FOR WOR;
SPO OFF;
SPO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql;
DECLARE
l_pos NUMBER;
l_clob_size NUMBER;
l_offset NUMBER;
l_sql_text VARCHAR2(32767);
l_len NUMBER;
l_hint VARCHAR2(32767);
BEGIN
DBMS_OUTPUT.PUT_LINE('SPO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..log;');
DBMS_OUTPUT.PUT_LINE('SET ECHO ON TERM ON LIN 2000 TRIMS ON NUMF 99999999999999999999;');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM $Header: 215187.1 coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql 11.4.4.4 '||TO_CHAR(SYSDATE, 'YYYY/MM/DD')||' carlos.sierra $');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM Copyright (c) 2000-2012, Oracle Corporation. All rights reserved.');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM AUTHOR');
DBMS_OUTPUT.PUT_LINE('REM carlos.sierra@oracle.com');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM SCRIPT');
DBMS_OUTPUT.PUT_LINE('REM coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM DESCRIPTION');
DBMS_OUTPUT.PUT_LINE('REM This script is generated by coe_xfr_sql_profile.sql');
DBMS_OUTPUT.PUT_LINE('REM It contains the SQL*Plus commands to create a custom');
DBMS_OUTPUT.PUT_LINE('REM SQL Profile for SQL_ID &&sql_id. based on plan hash');
DBMS_OUTPUT.PUT_LINE('REM value &&plan_hash_value..');
DBMS_OUTPUT.PUT_LINE('REM The custom SQL Profile to be created by this script');
DBMS_OUTPUT.PUT_LINE('REM will affect plans for SQL commands with signature');
DBMS_OUTPUT.PUT_LINE('REM matching the one for SQL Text below.');
DBMS_OUTPUT.PUT_LINE('REM Review SQL Text and adjust accordingly.');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM PARAMETERS');
DBMS_OUTPUT.PUT_LINE('REM None.');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM EXAMPLE');
DBMS_OUTPUT.PUT_LINE('REM SQL> START coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql;');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('REM NOTES');
DBMS_OUTPUT.PUT_LINE('REM 1. Should be run as SYSTEM or SYSDBA.');
DBMS_OUTPUT.PUT_LINE('REM 2. User must have CREATE ANY SQL PROFILE privilege.');
DBMS_OUTPUT.PUT_LINE('REM 3. SOURCE and TARGET systems can be the same or similar.');
DBMS_OUTPUT.PUT_LINE('REM 4. To drop this custom SQL Profile after it has been created:');
DBMS_OUTPUT.PUT_LINE('REM EXEC DBMS_SQLTUNE.DROP_SQL_PROFILE(''coe_&&sql_id._&&plan_hash_value.'');');
DBMS_OUTPUT.PUT_LINE('REM 5. Be aware that using DBMS_SQLTUNE requires a license');
DBMS_OUTPUT.PUT_LINE('REM for the Oracle Tuning Pack.');
DBMS_OUTPUT.PUT_LINE('REM 6. If you modified a SQL putting Hints in order to produce a desired');
DBMS_OUTPUT.PUT_LINE('REM Plan, you can remove the artifical Hints from SQL Text pieces below.');
DBMS_OUTPUT.PUT_LINE('REM By doing so you can create a custom SQL Profile for the original');
DBMS_OUTPUT.PUT_LINE('REM SQL but with the Plan captured from the modified SQL (with Hints).');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('WHENEVER SQLERROR EXIT SQL.SQLCODE;');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('VAR signature NUMBER;');
DBMS_OUTPUT.PUT_LINE('VAR signaturef NUMBER;');
DBMS_OUTPUT.PUT_LINE('REM');
DBMS_OUTPUT.PUT_LINE('DECLARE');
DBMS_OUTPUT.PUT_LINE('sql_txt CLOB;');
DBMS_OUTPUT.PUT_LINE('h SYS.SQLPROF_ATTR;');
DBMS_OUTPUT.PUT_LINE('PROCEDURE wa (p_line IN VARCHAR2) IS');
DBMS_OUTPUT.PUT_LINE('BEGIN');
DBMS_OUTPUT.PUT_LINE('DBMS_LOB.WRITEAPPEND(sql_txt, LENGTH(p_line), p_line);');
DBMS_OUTPUT.PUT_LINE('END wa;');
DBMS_OUTPUT.PUT_LINE('BEGIN');
DBMS_OUTPUT.PUT_LINE('DBMS_LOB.CREATETEMPORARY(sql_txt, TRUE);');
DBMS_OUTPUT.PUT_LINE('DBMS_LOB.OPEN(sql_txt, DBMS_LOB.LOB_READWRITE);');
DBMS_OUTPUT.PUT_LINE('-- SQL Text pieces below do not have to be of same length.');
DBMS_OUTPUT.PUT_LINE('-- So if you edit SQL Text (i.e. removing temporary Hints),');
DBMS_OUTPUT.PUT_LINE('-- there is no need to edit or re-align unmodified pieces.');
l_clob_size := NVL(DBMS_LOB.GETLENGTH(:sql_text), 0);
l_offset := 1;
WHILE l_offset < l_clob_size
LOOP
l_pos := DBMS_LOB.INSTR(:sql_text, CHR(00), l_offset);
IF l_pos > 0 THEN
l_len := l_pos - l_offset;
ELSE -- last piece
l_len := l_clob_size - l_pos + 1;
END IF;
l_sql_text := DBMS_LOB.SUBSTR(:sql_text, l_len, l_offset);
/* cannot do such 3 replacement since a line could end with a comment using "--"
l_sql_text := REPLACE(l_sql_text, CHR(10), ' '); -- replace LF with SP
l_sql_text := REPLACE(l_sql_text, CHR(13), ' '); -- replace CR with SP
l_sql_text := REPLACE(l_sql_text, CHR(09), ' '); -- replace TAB with SP
*/
l_offset := l_offset + l_len + 1;
IF l_len > 0 THEN
IF INSTR(l_sql_text, '''[') + INSTR(l_sql_text, ']''') = 0 THEN
l_sql_text := '['||l_sql_text||']';
ELSIF INSTR(l_sql_text, '''{') + INSTR(l_sql_text, '}''') = 0 THEN
l_sql_text := '{'||l_sql_text||'}';
ELSIF INSTR(l_sql_text, '''<') + INSTR(l_sql_text, '>''') = 0 THEN
l_sql_text := '<'||l_sql_text||'>';
ELSIF INSTR(l_sql_text, '''(') + INSTR(l_sql_text, ')''') = 0 THEN
l_sql_text := '('||l_sql_text||')';
ELSIF INSTR(l_sql_text, '''"') + INSTR(l_sql_text, '"''') = 0 THEN
l_sql_text := '"'||l_sql_text||'"';
ELSIF INSTR(l_sql_text, '''|') + INSTR(l_sql_text, '|''') = 0 THEN
l_sql_text := '|'||l_sql_text||'|';
ELSIF INSTR(l_sql_text, '''~') + INSTR(l_sql_text, '~''') = 0 THEN
l_sql_text := '~'||l_sql_text||'~';
ELSIF INSTR(l_sql_text, '''^') + INSTR(l_sql_text, '^''') = 0 THEN
l_sql_text := '^'||l_sql_text||'^';
ELSIF INSTR(l_sql_text, '''@') + INSTR(l_sql_text, '@''') = 0 THEN
l_sql_text := '@'||l_sql_text||'@';
ELSIF INSTR(l_sql_text, '''#') + INSTR(l_sql_text, '#''') = 0 THEN
l_sql_text := '#'||l_sql_text||'#';
ELSIF INSTR(l_sql_text, '''%') + INSTR(l_sql_text, '%''') = 0 THEN
l_sql_text := '%'||l_sql_text||'%';
ELSIF INSTR(l_sql_text, '''$') + INSTR(l_sql_text, '$''') = 0 THEN
l_sql_text := '$'||l_sql_text||'$';
ELSE
l_sql_text := CHR(96)||l_sql_text||CHR(96);
END IF;
DBMS_OUTPUT.PUT_LINE('wa(q'''||l_sql_text||''');');
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('DBMS_LOB.CLOSE(sql_txt);');
DBMS_OUTPUT.PUT_LINE('h := SYS.SQLPROF_ATTR(');
DBMS_OUTPUT.PUT_LINE('q''[BEGIN_OUTLINE_DATA]'',');
FOR i IN (SELECT /*+ opt_param('parallel_execution_enabled', 'false') */
SUBSTR(EXTRACTVALUE(VALUE(d), '/hint'), 1, 4000) hint
FROM TABLE(XMLSEQUENCE(EXTRACT(XMLTYPE(:other_xml), '/*/outline_data/hint'))) d)
LOOP
l_hint := i.hint;
WHILE NVL(LENGTH(l_hint), 0) > 0
LOOP
IF LENGTH(l_hint) <= 500 THEN
DBMS_OUTPUT.PUT_LINE('q''['||l_hint||']'',');
l_hint := NULL;
ELSE
l_pos := INSTR(SUBSTR(l_hint, 1, 500), ' ', -1);
DBMS_OUTPUT.PUT_LINE('q''['||SUBSTR(l_hint, 1, l_pos)||']'',');
l_hint := ' '||SUBSTR(l_hint, l_pos);
END IF;
END LOOP;
END LOOP;
DBMS_OUTPUT.PUT_LINE('q''[END_OUTLINE_DATA]'');');
DBMS_OUTPUT.PUT_LINE(':signature := DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql_txt);');
DBMS_OUTPUT.PUT_LINE(':signaturef := DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql_txt, TRUE);');
DBMS_OUTPUT.PUT_LINE('DBMS_SQLTUNE.IMPORT_SQL_PROFILE (');
DBMS_OUTPUT.PUT_LINE('sql_text => sql_txt,');
DBMS_OUTPUT.PUT_LINE('profile => h,');
DBMS_OUTPUT.PUT_LINE('name => ''coe_&&sql_id._&&plan_hash_value.'',');
DBMS_OUTPUT.PUT_LINE('description => ''coe &&sql_id. &&plan_hash_value. ''||:signature||'' ''||:signaturef||'''',');
DBMS_OUTPUT.PUT_LINE('category => ''DEFAULT'',');
DBMS_OUTPUT.PUT_LINE('validate => TRUE,');
DBMS_OUTPUT.PUT_LINE('replace => TRUE,');
DBMS_OUTPUT.PUT_LINE('force_match => FALSE /* TRUE:FORCE (match even when different literals in SQL). FALSE:EXACT (similar to CURSOR_SHARING) */ );');
DBMS_OUTPUT.PUT_LINE('DBMS_LOB.FREETEMPORARY(sql_txt);');
DBMS_OUTPUT.PUT_LINE('END;');
DBMS_OUTPUT.PUT_LINE('/');
DBMS_OUTPUT.PUT_LINE('WHENEVER SQLERROR CONTINUE');
DBMS_OUTPUT.PUT_LINE('SET ECHO OFF;');
DBMS_OUTPUT.PUT_LINE('PRINT signature');
DBMS_OUTPUT.PUT_LINE('PRINT signaturef');
DBMS_OUTPUT.PUT_LINE('PRO');
DBMS_OUTPUT.PUT_LINE('PRO ... manual custom SQL Profile has been created');
DBMS_OUTPUT.PUT_LINE('PRO');
DBMS_OUTPUT.PUT_LINE('SET TERM ON ECHO OFF LIN 80 TRIMS OFF NUMF "";');
DBMS_OUTPUT.PUT_LINE('SPO OFF;');
DBMS_OUTPUT.PUT_LINE('PRO');
DBMS_OUTPUT.PUT_LINE('PRO COE_XFR_SQL_PROFILE_&&sql_id._&&plan_hash_value. completed');
END;
/
SPO OFF;
SET DEF ON TERM ON ECHO OFF FEED 6 VER ON HEA ON LIN 80 PAGES 14 LONG 80 LONGC 80 TRIMS OFF TI OFF TIMI OFF SERVEROUT OFF NUMF "" SQLP SQL>;
SET SERVEROUT OFF;
PRO
PRO Execute coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql
PRO on TARGET system in order to create a custom SQL Profile
PRO with plan &&plan_hash_value linked to adjusted sql_text.
PRO
UNDEFINE 1 2 sql_id plan_hash_value
CL COL
PRO
PRO COE_XFR_SQL_PROFILE completed.

7
star/colored_sql_id.sql Normal file
View File

@@ -0,0 +1,7 @@
select * from DBA_HIST_COLORED_SQL;
prompt To ADD colored <sql_id>: execute DBMS_WORKLOAD_REPOSITORY.ADD_COLORED_SQL(sql_id=>'<sql_id>')
prompt To REMOVE colored <sql_id>: execute DBMS_WORKLOAD_REPOSITORY.REMOVE_COLORED_SQL(sql_id=>'<sql_id>')
prompt

View File

@@ -0,0 +1,108 @@
-- Create SQL Plan Baselin from AWR Plan
SET PAGES 200 LONG 80000;
ACC sql_id PROMPT 'Enter SQL_ID: ';
WITH
p AS (
SELECT plan_hash_value
FROM dba_hist_sql_plan
WHERE sql_id = TRIM('&&sql_id.')
AND dbid = (SELECT dbid FROM v$database)
AND other_xml IS NOT NULL ),
a AS (
SELECT plan_hash_value,
SUM(elapsed_time_total)/SUM(executions_total) avg_et_secs,
MAX(executions_total) executions_total
FROM dba_hist_sqlstat
WHERE sql_id = TRIM('&&sql_id.')
AND executions_total > 0
GROUP BY
plan_hash_value )
SELECT p.plan_hash_value,
ROUND(a.avg_et_secs/1e6, 6) avg_et_secs,
a.executions_total
FROM p, a
WHERE p.plan_hash_value = a.plan_hash_value(+)
ORDER BY
avg_et_secs NULLS LAST;
ACC plan_hash_value PROMPT 'Enter Plan Hash Value: ';
COL dbid NEW_V dbid NOPRI;
SELECT dbid FROM v$database;
COL begin_snap_id NEW_V begin_snap_id NOPRI;
COL end_snap_id NEW_V end_snap_id NOPRI;
SELECT MIN(p.snap_id) begin_snap_id, MAX(p.snap_id) end_snap_id
FROM dba_hist_sqlstat p,
dba_hist_snapshot s
WHERE p.dbid = &&dbid
AND p.sql_id = '&&sql_id.'
AND p.plan_hash_value = TO_NUMBER('&&plan_hash_value.')
AND s.snap_id = p.snap_id
AND s.dbid = p.dbid
AND s.instance_number = p.instance_number;
VAR sqlset_name VARCHAR2(30);
EXEC :sqlset_name := REPLACE('s_&&sql_id._&&plan_hash_value._awr', ' ');
PRINT sqlset_name;
SET SERVEROUT ON;
VAR plans NUMBER;
DECLARE
l_sqlset_name VARCHAR2(30);
l_description VARCHAR2(256);
sts_cur SYS.DBMS_SQLTUNE.SQLSET_CURSOR;
BEGIN
l_sqlset_name := :sqlset_name;
l_description := 'SQL_ID:&&sql_id., PHV:&&plan_hash_value., BEGIN:&&begin_snap_id., END:&&end_snap_id.';
l_description := REPLACE(REPLACE(l_description, ' '), ',', ', ');
BEGIN
DBMS_OUTPUT.put_line('dropping sqlset: '||l_sqlset_name);
SYS.DBMS_SQLTUNE.drop_sqlset (
sqlset_name => l_sqlset_name,
sqlset_owner => USER );
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(SQLERRM||' while trying to drop STS: '||l_sqlset_name||' (safe to ignore)');
END;
l_sqlset_name :=
SYS.DBMS_SQLTUNE.create_sqlset (
sqlset_name => l_sqlset_name,
description => l_description,
sqlset_owner => USER );
DBMS_OUTPUT.put_line('created sqlset: '||l_sqlset_name);
OPEN sts_cur FOR
SELECT VALUE(p)
FROM TABLE(DBMS_SQLTUNE.select_workload_repository (&&begin_snap_id., &&end_snap_id.,
'sql_id = ''&&sql_id.'' AND plan_hash_value = TO_NUMBER(''&&plan_hash_value.'') AND loaded_versions > 0',
NULL, NULL, NULL, NULL, 1, NULL, 'ALL')) p;
SYS.DBMS_SQLTUNE.load_sqlset (
sqlset_name => l_sqlset_name,
populate_cursor => sts_cur );
DBMS_OUTPUT.put_line('loaded sqlset: '||l_sqlset_name);
CLOSE sts_cur;
:plans := DBMS_SPM.load_plans_from_sqlset (
sqlset_name => l_sqlset_name,
sqlset_owner => USER );
END;
/
PRINT plans;
SET PAGES 14 LONG 80 ECHO OFF SERVEROUT OFF;
UNDEF sql_id plan_hash_value
CL COL

View File

@@ -0,0 +1,35 @@
REM $Header: 215187.1 create_spb_from_cur.sql 12.1.02 2013/09/09 carlos.sierra $
-- Create SQL Plan Baseline from SQL Cursor
ACC sql_text_piece PROMPT 'Enter SQL Text piece: '
SET PAGES 200 LONG 80000 ECHO ON;
COL sql_text PRI;
SELECT sql_id, sql_text /* exclude_me */
FROM v$sqlarea
WHERE sql_text LIKE '%&&sql_text_piece.%'
AND sql_text NOT LIKE '%/* exclude_me */%';
ACC sql_id PROMPT 'Enter SQL_ID: ';
SELECT plan_hash_value, SUM(executions) executions, SUM(elapsed_time) elapsed_time, /* exclude_me */
CASE WHEN SUM(executions) > 0 THEN ROUND(SUM(elapsed_time)/SUM(executions)/1e6, 3) END avg_secs_per_exec
FROM v$sql
WHERE sql_id = '&&sql_id.'
GROUP BY
plan_hash_value
ORDER BY
4 DESC NULLS FIRST;
ACC plan_hash_value PROMPT 'Enter Plan Hash Value: ';
VAR plans NUMBER;
EXEC :plans := DBMS_SPM.load_plans_from_cursor_cache('&&sql_id.', TO_NUMBER('&&plan_hash_value.'));
PRINT plans;
SET PAGES 14 LONG 80 ECHO OFF;
UNDEF sql_text_piece sql_id plan_hash_value

137
star/dash_wait_chains.sql Normal file
View File

@@ -0,0 +1,137 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: dash_wait_chains.sql (v0.6 BETA)
-- Purpose: Display ASH wait chains (multi-session wait signature, a session
-- waiting for another session etc.)
--
-- Author: Tanel Poder
-- Copyright: (c) https://tanelpoder.com
--
-- Usage:
-- @dash_wait_chains <grouping_cols> <filters> <fromtime> <totime>
--
-- Example:
-- @dash_wait_chains username||':'||program2||event2 session_type='FOREGROUND' sysdate-1 sysdate
--
-- Other:
-- This script uses only the DBA_HIST_ACTIVE_SESS_HISTORY view, use
-- @ash_wait_chains.sql for accessiong the V$ ASH view
--
--------------------------------------------------------------------------------
COL wait_chain FOR A300 WORD_WRAP
COL distinct_sids FOR 9999 HEAD "#Blkrs"
COL "%This" FOR A6
PROMPT
PROMPT -- Display ASH Wait Chain Signatures script v0.6 BETA by Tanel Poder ( https://tanelpoder.com )
WITH
bclass AS (SELECT /*+ INLINE */ class, ROWNUM r from v$waitstat),
ash AS (SELECT /*+ INLINE QB_NAME(ash) LEADING(a) USE_HASH(u) SWAP_JOIN_INPUTS(u) */
a.*
, o.*
, u.username
, CASE WHEN a.session_type = 'BACKGROUND' OR REGEXP_LIKE(a.program, '.*\([PJ]\d+\)') THEN
REGEXP_REPLACE(SUBSTR(a.program,INSTR(a.program,'(')), '\d', 'n')
ELSE
'('||REGEXP_REPLACE(REGEXP_REPLACE(a.program, '(.*)@(.*)(\(.*\))', '\1'), '\d', 'n')||')'
END || ' ' program2
, NVL(a.event||CASE WHEN event like 'enq%' AND session_state = 'WAITING'
THEN ' [mode='||BITAND(p1, POWER(2,14)-1)||']'
WHEN a.event IN (SELECT name FROM v$event_name WHERE parameter3 = 'class#')
THEN ' ['||NVL((SELECT class FROM bclass WHERE r = a.p3),'undo @bclass '||a.p3)||']' ELSE null END,'ON CPU')
|| ' ' event2
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p1 ELSE null END, '0XXXXXXXXXXXXXXX') p1hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p3 ELSE null END, '0XXXXXXXXXXXXXXX') p3hex
, CASE WHEN BITAND(time_model, POWER(2, 01)) = POWER(2, 01) THEN 'DBTIME ' END
||CASE WHEN BITAND(time_model, POWER(2, 02)) = POWER(2, 02) THEN 'BACKGROUND ' END
||CASE WHEN BITAND(time_model, POWER(2, 03)) = POWER(2, 03) THEN 'CONNECTION_MGMT ' END
||CASE WHEN BITAND(time_model, POWER(2, 04)) = POWER(2, 04) THEN 'PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 05)) = POWER(2, 05) THEN 'FAILED_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 06)) = POWER(2, 06) THEN 'NOMEM_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 07)) = POWER(2, 07) THEN 'HARD_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 08)) = POWER(2, 08) THEN 'NO_SHARERS_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 09)) = POWER(2, 09) THEN 'BIND_MISMATCH_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 10)) = POWER(2, 10) THEN 'SQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 11)) = POWER(2, 11) THEN 'PLSQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 12)) = POWER(2, 12) THEN 'PLSQL_RPC ' END
||CASE WHEN BITAND(time_model, POWER(2, 13)) = POWER(2, 13) THEN 'PLSQL_COMPILATION ' END
||CASE WHEN BITAND(time_model, POWER(2, 14)) = POWER(2, 14) THEN 'JAVA_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 15)) = POWER(2, 15) THEN 'BIND ' END
||CASE WHEN BITAND(time_model, POWER(2, 16)) = POWER(2, 16) THEN 'CURSOR_CLOSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 17)) = POWER(2, 17) THEN 'SEQUENCE_LOAD ' END
||CASE WHEN BITAND(time_model, POWER(2, 18)) = POWER(2, 18) THEN 'INMEMORY_QUERY ' END
||CASE WHEN BITAND(time_model, POWER(2, 19)) = POWER(2, 19) THEN 'INMEMORY_POPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 20)) = POWER(2, 20) THEN 'INMEMORY_PREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 21)) = POWER(2, 21) THEN 'INMEMORY_REPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 22)) = POWER(2, 22) THEN 'INMEMORY_TREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 23)) = POWER(2, 23) THEN 'TABLESPACE_ENCRYPTION ' END time_model_name
FROM
dba_hist_active_sess_history a
, dba_users u
, (SELECT
object_id,data_object_id,owner,object_name,subobject_name,object_type
, owner||'.'||object_name obj
, owner||'.'||object_name||' ['||object_type||']' objt
FROM dba_objects) o
WHERE
a.user_id = u.user_id (+)
AND a.current_obj# = o.object_id(+)
AND sample_time BETWEEN &3 AND &4
),
ash_samples AS (SELECT /*+ INLINE */ DISTINCT sample_id FROM ash),
ash_data AS (SELECT /*+ INLINE */ * FROM ash),
chains AS (
SELECT /*+ INLINE */
sample_time ts
, level lvl
, session_id sid
, REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 AND d.blocking_session IS NOT NULL THEN ' -> [idle blocker '||d.blocking_inst_id||','||d.blocking_session||','||d.blocking_session_serial#||(SELECT ' ('||s.program||')' FROM gv$session s WHERE (s.inst_id, s.sid , s.serial#) = ((d.blocking_inst_id,d.blocking_session,d.blocking_session_serial#)))||']' ELSE NULL END path -- there's a reason why I'm doing this
--, REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ') path -- there's a reason why I'm doing this (ORA-30004 :)
--, SYS_CONNECT_BY_PATH(&1, ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 THEN '('||d.session_id||')' ELSE NULL END path
--, REPLACE(SYS_CONNECT_BY_PATH(&1, '->'), '->', ' -> ')||CASE WHEN CONNECT_BY_ISLEAF = 1 THEN ' [sid='||d.session_id||' seq#='||TO_CHAR(seq#)||']' ELSE NULL END path -- there's a reason why I'm doing this (ORA-30004 :)
, CASE WHEN CONNECT_BY_ISLEAF = 1 THEN d.session_id ELSE NULL END sids
, CONNECT_BY_ISLEAF isleaf
, CONNECT_BY_ISCYCLE iscycle
, d.*
FROM
ash_samples s
, ash_data d
WHERE
s.sample_id = d.sample_id
AND d.sample_time BETWEEN &3 AND &4
CONNECT BY NOCYCLE
( PRIOR d.blocking_session = d.session_id
AND PRIOR s.sample_id = d.sample_id
AND PRIOR d.blocking_inst_id = d.instance_number)
START WITH &2
)
SELECT * FROM (
SELECT
LPAD(ROUND(RATIO_TO_REPORT(COUNT(*)) OVER () * 100)||'%',5,' ') "%This"
, COUNT(*) * 10 seconds
, ROUND(COUNT(*) * 10 / ((CAST(&4 AS DATE) - CAST(&3 AS DATE)) * 86400), 1) AAS
-- , MIN(sids)
-- , MAX(sids)
, COUNT(DISTINCT sids) distinct_sids
, path wait_chain
, TO_CHAR(MIN(sample_time), 'YYYY-MM-DD HH24:MI:SS') first_seen
, TO_CHAR(MAX(sample_time), 'YYYY-MM-DD HH24:MI:SS') last_seen
FROM
chains
WHERE
isleaf = 1
GROUP BY
&1
, path
ORDER BY
COUNT(*) DESC
)
WHERE
rownum <= 30
/

146
star/dashtop.sql Normal file
View File

@@ -0,0 +1,146 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: dashtop.sql v1.2
-- Purpose: Display top ASH time (count of ASH samples) grouped by your
-- specified dimensions
--
-- Author: Tanel Poder
-- Copyright: (c) http://blog.tanelpoder.com
--
-- Usage:
-- @dashtop <grouping_cols> <filters> <fromtime> <totime>
--
-- Example:
-- @dashtop username,sql_id session_type='FOREGROUND' sysdate-1/24 sysdate
--
-- Other:
-- This script uses only the AWR's DBA_HIST_ACTIVE_SESS_HISTORY, use
-- @dashtop.sql for accessiong the V$ ASH view
--
--
-- TODO:
-- Deal with cases where there's no AWR snapshot saved to DBA_HIST_SNAPSHOTS
-- (due to a DB issue) but DBA_HIST_ASH samples are there
--------------------------------------------------------------------------------
COL "%This" FOR A7
--COL p1 FOR 99999999999999
--COL p2 FOR 99999999999999
--COL p3 FOR 99999999999999
COL p1text FOR A30 word_wrap
COL p2text FOR A30 word_wrap
COL p3text FOR A30 word_wrap
COL p1hex FOR A17
COL p2hex FOR A17
COL p3hex FOR A17
COL AAS FOR 9999.9
COL totalseconds HEAD "Total|Seconds" FOR 99999999
COL dist_sqlexec_seen HEAD "Distinct|Execs Seen"
COL event FOR A42 WORD_WRAP
COL event2 FOR A46 WORD_WRAP
COL time_model_name FOR A50 WORD_WRAP
COL program2 FOR A40 TRUNCATE
COL username FOR A20 wrap
COL obj FOR A30
COL objt FOR A50
COL sql_opname FOR A20
COL top_level_call_name FOR A30
COL wait_class FOR A15
SELECT * FROM (
WITH bclass AS (SELECT class, ROWNUM r from v$waitstat)
SELECT /*+ LEADING(a) USE_HASH(u) */
10 * COUNT(*) "TotalSeconds"
, ROUND(10 * COUNT(*) / ((CAST(&4 AS DATE) - CAST(&3 AS DATE)) * 86400), 1) AAS
, LPAD(ROUND(RATIO_TO_REPORT(COUNT(*)) OVER () * 100)||'%',5,' ') "%This"
, &1
-- , 10 * SUM(CASE WHEN wait_class IS NULL THEN 1 ELSE 0 END) "CPU"
-- , 10 * SUM(CASE WHEN wait_class ='User I/O' THEN 1 ELSE 0 END) "User I/O"
-- , 10 * SUM(CASE WHEN wait_class ='Application' THEN 1 ELSE 0 END) "Application"
-- , 10 * SUM(CASE WHEN wait_class ='Concurrency' THEN 1 ELSE 0 END) "Concurrency"
-- , 10 * SUM(CASE WHEN wait_class ='Commit' THEN 1 ELSE 0 END) "Commit"
-- , 10 * SUM(CASE WHEN wait_class ='Configuration' THEN 1 ELSE 0 END) "Configuration"
-- , 10 * SUM(CASE WHEN wait_class ='Cluster' THEN 1 ELSE 0 END) "Cluster"
-- , 10 * SUM(CASE WHEN wait_class ='Idle' THEN 1 ELSE 0 END) "Idle"
-- , 10 * SUM(CASE WHEN wait_class ='Network' THEN 1 ELSE 0 END) "Network"
-- , 10 * SUM(CASE WHEN wait_class ='System I/O' THEN 1 ELSE 0 END) "System I/O"
-- , 10 * SUM(CASE WHEN wait_class ='Scheduler' THEN 1 ELSE 0 END) "Scheduler"
-- , 10 * SUM(CASE WHEN wait_class ='Administrative' THEN 1 ELSE 0 END) "Administrative"
-- , 10 * SUM(CASE WHEN wait_class ='Queueing' THEN 1 ELSE 0 END) "Queueing"
-- , 10 * SUM(CASE WHEN wait_class ='Other' THEN 1 ELSE 0 END) "Other"
, TO_CHAR(MIN(sample_time), 'YYYY-MM-DD HH24:MI:SS') first_seen
, TO_CHAR(MAX(sample_time), 'YYYY-MM-DD HH24:MI:SS') last_seen
FROM
(SELECT
a.*
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p1 ELSE null END, '0XXXXXXXXXXXXXXX') p1hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex
, TO_CHAR(CASE WHEN session_state = 'WAITING' THEN p3 ELSE null END, '0XXXXXXXXXXXXXXX') p3hex
, NVL(event, session_state)||
CASE
WHEN event like 'enq%' AND session_state = 'WAITING'
THEN ' [mode='||BITAND(p1, POWER(2,14)-1)||']'
WHEN a.event IN (SELECT name FROM v$event_name WHERE parameter3 = 'class#')
THEN ' ['||CASE WHEN a.p3 <= (SELECT MAX(r) FROM bclass)
THEN (SELECT class FROM bclass WHERE r = a.p3)
ELSE (SELECT DECODE(MOD(BITAND(a.p3,TO_NUMBER('FFFF','XXXX')) - 17,2),0,'undo header',1,'undo data', 'error') FROM dual)
END ||']'
ELSE null
END event2 -- event is NULL in ASH if the session is not waiting (session_state = ON CPU)
, CASE WHEN a.session_type = 'BACKGROUND' OR REGEXP_LIKE(a.program, '.*\([PJ]\d+\)') THEN
REGEXP_REPLACE(SUBSTR(a.program,INSTR(a.program,'(')), '\d', 'n')
ELSE
'('||REGEXP_REPLACE(REGEXP_REPLACE(a.program, '(.*)@(.*)(\(.*\))', '\1'), '\d', 'n')||')'
END || ' ' program2
, CASE WHEN BITAND(time_model, POWER(2, 01)) = POWER(2, 01) THEN 'DBTIME ' END
||CASE WHEN BITAND(time_model, POWER(2, 02)) = POWER(2, 02) THEN 'BACKGROUND ' END
||CASE WHEN BITAND(time_model, POWER(2, 03)) = POWER(2, 03) THEN 'CONNECTION_MGMT ' END
||CASE WHEN BITAND(time_model, POWER(2, 04)) = POWER(2, 04) THEN 'PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 05)) = POWER(2, 05) THEN 'FAILED_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 06)) = POWER(2, 06) THEN 'NOMEM_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 07)) = POWER(2, 07) THEN 'HARD_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 08)) = POWER(2, 08) THEN 'NO_SHARERS_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 09)) = POWER(2, 09) THEN 'BIND_MISMATCH_PARSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 10)) = POWER(2, 10) THEN 'SQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 11)) = POWER(2, 11) THEN 'PLSQL_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 12)) = POWER(2, 12) THEN 'PLSQL_RPC ' END
||CASE WHEN BITAND(time_model, POWER(2, 13)) = POWER(2, 13) THEN 'PLSQL_COMPILATION ' END
||CASE WHEN BITAND(time_model, POWER(2, 14)) = POWER(2, 14) THEN 'JAVA_EXECUTION ' END
||CASE WHEN BITAND(time_model, POWER(2, 15)) = POWER(2, 15) THEN 'BIND ' END
||CASE WHEN BITAND(time_model, POWER(2, 16)) = POWER(2, 16) THEN 'CURSOR_CLOSE ' END
||CASE WHEN BITAND(time_model, POWER(2, 17)) = POWER(2, 17) THEN 'SEQUENCE_LOAD ' END
||CASE WHEN BITAND(time_model, POWER(2, 18)) = POWER(2, 18) THEN 'INMEMORY_QUERY ' END
||CASE WHEN BITAND(time_model, POWER(2, 19)) = POWER(2, 19) THEN 'INMEMORY_POPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 20)) = POWER(2, 20) THEN 'INMEMORY_PREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 21)) = POWER(2, 21) THEN 'INMEMORY_REPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 22)) = POWER(2, 22) THEN 'INMEMORY_TREPOPULATE ' END
||CASE WHEN BITAND(time_model, POWER(2, 23)) = POWER(2, 23) THEN 'TABLESPACE_ENCRYPTION ' END time_model_name
FROM dba_hist_active_sess_history a) a
, dba_users u
, (SELECT
object_id,data_object_id,owner,object_name,subobject_name,object_type
, owner||'.'||object_name obj
, owner||'.'||object_name||' ['||object_type||']' objt
FROM dba_objects) o
WHERE
a.user_id = u.user_id (+)
AND a.current_obj# = o.object_id(+)
AND &2
AND a.sample_time BETWEEN &3 AND &4
AND a.dbid = (SELECT d.dbid FROM v$database d) -- for partition pruning
--AND a.snap_id IN (SELECT sn.snap_id FROM dba_hist_snapshot sn WHERE sn.begin_interval_time >= &3 AND sn.end_interval_time <= &4) -- for partition pruning
AND snap_id IN (SELECT snap_id FROM dba_hist_snapshot WHERE sample_time BETWEEN &3 AND &4) -- for partition pruning
--AND (a.dbid, a.snap_id) IN (SELECT d.dbid, sn.snap_id FROM v$database d, dba_hist_snapshot sn WHERE d.dbid = sn.dbid AND sn.begin_interval_time >= &3 AND sn.end_interval_time <= &4) -- for partition pruning
GROUP BY
&1
ORDER BY
"TotalSeconds" DESC
, &1
)
WHERE
ROWNUM <= 20
/

107
star/dasqlmon.sql Normal file
View File

@@ -0,0 +1,107 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
------------------------------------------------------------------------------------------------------------------------
--
-- File name: dasqlmon.sql (v1.2)
--
-- Purpose: Report SQL-monitoring-style drill-down into where in an execution plan the execution time is spent
--
-- Author: Tanel Poder
--
-- Copyright: (c) https://tanelpoder.com - All rights reserved.
--
-- Disclaimer: This script is provided "as is", no warranties nor guarantees are
-- made. Use at your own risk :)
--
-- Usage: @dasqlmon <sqlid> <plan_hash_value> <from_time> <to_time>
--
-- Notes: This script runs on Oracle 11g+ and you should have the
-- Diagnostics license for using it as it queries
-- some separately licensed views.
--
------------------------------------------------------------------------------------------------------------------------
SET LINESIZE 999 PAGESIZE 5000 TRIMOUT ON TRIMSPOOL ON
COL asqlmon_operation HEAD Plan_Operation FOR a70
COL asqlmon_predicates HEAD PREDICATES FOR a100 word_wrap
COL obj_alias_qbc_name FOR a40
COL options FOR a30
COL asqlmon_plan_hash_value HEAD PLAN_HASH_VALUE
COL asqlmon_sql_id HEAD SQL_ID NOPRINT
COL asqlmon_sql_child HEAD "CHILD" PRINT
COL asqlmon_sample_time HEAD SAMPLE_HOUR
COL projection FOR A520
COL pct_child HEAD "Activity %" FOR A8
COL pct_child_vis HEAD "Visual" FOR A12
COL asqlmon_id HEAD "ID" FOR 9999
COL asqlmon_parent_id HEAD "PID" FOR 9999
BREAK ON asqlmon_sql_id SKIP 1 ON asqlmon_sql_child SKIP 1 ON asqlmon_plan_hash_value SKIP 1 ON asqlmon_sample_time SKIP 1 DUP ON asqlmon_operation
PROMPT
PROMPT -- ASQLMon v1.1 - by Tanel Poder ( https://tanelpoder.com ) - Display SQL execution plan line level activity breakdown from ASH
WITH sample_times AS (
select * from dual
),
sq AS (
SELECT
count(*) samples
, ash.sql_id
, ash.sql_plan_hash_value
, NVL(ash.sql_plan_line_id,1) sql_plan_line_id -- this is because simple "planless" operations like single-row insert
, ash.sql_plan_operation
, ash.sql_plan_options
, ash.session_state
, ash.event
-- , AVG(ash.p3) avg_p3 -- p3 is sometimes useful for listing block counts for IO wait events
FROM
dba_hist_active_sess_history ash
WHERE
1=1
AND ash.sql_id LIKE '&1'
AND ash.sql_plan_hash_value LIKE '&2'
AND ash.sample_time BETWEEN &3 AND &4
GROUP BY
ash.sql_id
, ash.sql_plan_hash_value
, NVL(ash.sql_plan_line_id,1)
, ash.sql_plan_operation
, ash.sql_plan_options
, ash.session_state
, ash.event
)
SELECT
plan.sql_id asqlmon_sql_id
, plan.plan_hash_value asqlmon_plan_hash_value
, sq.samples * 10 seconds
, LPAD(TO_CHAR(ROUND(RATIO_TO_REPORT(sq.samples) OVER (PARTITION BY sq.sql_id, sq.sql_plan_hash_value) * 100, 1), 999.9)||' %',8) pct_child
, '|'||RPAD( NVL( LPAD('#', ROUND(RATIO_TO_REPORT(sq.samples) OVER (PARTITION BY sq.sql_id, sq.sql_plan_hash_value) * 10), '#'), ' '), 10,' ')||'|' pct_child_vis
--, LPAD(plan.id,4)||CASE WHEN parent_id IS NULL THEN ' ' ELSE ' <- ' END||LPAD(plan.parent_id,4) asqlmon_plan_id
, plan.id asqlmon_id
, plan.parent_id asqlmon_parent_id
, LPAD(' ', depth, ' ') || plan.operation ||' '|| plan.options || NVL2(plan.object_name, ' ['||plan.object_name ||']', null) asqlmon_operation
, sq.session_state
, sq.event
-- , sq.avg_p3
, plan.object_alias || CASE WHEN plan.qblock_name IS NOT NULL THEN ' ['|| plan.qblock_name || ']' END obj_alias_qbc_name
, CASE WHEN plan.access_predicates IS NOT NULL THEN '[A:] '|| plan.access_predicates END || CASE WHEN plan.filter_predicates IS NOT NULL THEN ' [F:]' || plan.filter_predicates END asqlmon_predicates
-- , plan.projection
FROM
dba_hist_sql_plan plan
, sq
WHERE
1=1
AND sq.sql_id(+) = plan.sql_id
AND sq.sql_plan_line_id(+) = plan.id
AND sq.sql_plan_hash_value(+) = plan.plan_hash_value
AND plan.sql_id LIKE '&1'
AND plan.plan_hash_value LIKE '&2'
ORDER BY
plan.plan_hash_value
, plan.id
/

View File

@@ -0,0 +1,63 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_invalid_objects.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provide a detailed report of all invalid objects in the |
-- | database. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Invalid Objects |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
-- SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN owner FORMAT a25 HEADING 'Owner'
COLUMN object_name FORMAT a30 HEADING 'Object Name'
COLUMN object_type FORMAT a20 HEADING 'Object Type'
COLUMN status FORMAT a10 HEADING 'Status'
BREAK ON owner SKIP 2 ON report
COMPUTE count LABEL "" OF object_name ON owner
COMPUTE count LABEL "Grand Total: " OF object_name ON report
SELECT
owner
, object_name
, object_type
, status
FROM dba_objects
WHERE status <> 'VALID'
ORDER BY owner, object_name
/

62
star/dba_registry.sql Normal file
View File

@@ -0,0 +1,62 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : dba_registry.sql |
-- | CLASS : Database Administration |
-- | PURPOSE : Provides summary report on all registered components. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Database Registry Components |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
-- SET LINESIZE 180
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN comp_id FORMAT a9 HEADING 'Component|ID'
COLUMN comp_name FORMAT a35 HEADING 'Component|Name'
COLUMN version FORMAT a13 HEADING 'Version'
COLUMN status FORMAT a11 HEADING 'Status'
COLUMN modified HEADING 'Modified'
COLUMN Schema FORMAT a15 HEADING 'Schema'
COLUMN procedure FORMAT a45 HEADING 'Procedure'
SELECT
comp_id
, comp_name
, version
, status
, modified
, schema
, procedure
FROM
dba_registry
ORDER BY
comp_id;

146
star/h.sql Normal file
View File

@@ -0,0 +1,146 @@
DEFINE search_string=&1
COLUMN name FORMAT A28 TRUNC
COLUMN description FORMAT A60 WORD_WRAP
COLUMN usage FORMAT A60 WORD_WRAP
COLUMN example FORMAT A56 WORD_WRAP
COLUMN tag FORMAT A20 WORD_WRAP
WITH q AS (
SELECT *
FROM (
SELECT 'otherxml.sql' AS name, 'Display outline hints from library cache' AS description, '@otherxml <sql_id> <child#>
' AS Usage, '@otherxml 1fbwxvngasv1f 1' AS Example, 'outline hint' AS tag FROM dual UNION ALL
SELECT 'sql_profile_hints.sql' AS name, 'Display SQL profile hints' AS description, '@sql_profile_hints.sql <sql_profile>
' AS Usage, '@sql_profile_hints.sql sqlprof_2v4h21kf9bz0h' AS Example, 'sqlprof hint' AS tag FROM dual UNION ALL
SELECT 'awr_sqlid.sql' AS name, 'Display SQL text from AWR' AS description, '@awr_sqlid <sql_id>
' AS Usage, '@awr_sqlid 7q729nhdgtsqq' AS Example, 'awr sqltext' AS tag FROM dual UNION ALL
SELECT 'sqlbinds.sql' AS name, 'Show captured binds from GV$SQL_BIND_CAPTURE' AS description, '@sqlbinds <sql_id> <child_number> <bindvar_name>
' AS Usage, '@sqlbinds 0qyu7wm1b2g1r % %' AS Example, 'bind' AS tag FROM dual UNION ALL
SELECT 'awr_sql_binds.sql' AS name, 'Display SQL Binds from AWR' AS description, '@awr_sql_binds.sql <sql_id> <num_days> <where>
' AS Usage, '@awr_sql_binds.sql 0qyu7wm1b2g1r 7 "and 1=1"'||chr(10)||'@awr_sql_binds.sql 6qqf9bakz7j3n 7 "and plan_hash_value=2088506832"' AS Example, 'bind' AS tag FROM dual UNION ALL
SELECT 'xlast.sql' AS name, 'Explain plan last SQL_ID' AS description, 'xlast.sql
' AS Usage, '' AS Example, 'explain' AS tag FROM dual UNION ALL
SELECT 'colored_sql_id.sql' AS name, 'Show colored SQL_ID' AS description, 'colored_sql_id.sql
' AS Usage, '' AS Example, 'color' AS tag FROM dual UNION ALL
SELECT 'xplan.sql' AS name, 'Explain plan from Library Cache' AS description, '@xplan <sql_id> <child_num>
' AS Usage, '@xplan.sql gy2zd0jzw3w6y 0' AS Example, 'explain' AS tag FROM dual UNION ALL
SELECT 'sqlidtabstat.sql' AS name, 'Staleness for tables/indexes in execution plan' AS description, '@sqlidtabstat.sql <sql_id>
' AS Usage, '@sqlidtabstat.sql 2bu78cxnrm4s7' AS Example, 'stale' AS tag FROM dual UNION ALL
SELECT 'stale.sql' AS name, 'List DB stale tables' AS description, '@stale.sql
' AS Usage, '' AS Example, 'stale' AS tag FROM dual UNION ALL
SELECT 'tab_details.sql' AS name, 'Table details' AS description, '@tab_details.sql <owner> <table_name>
' AS Usage, '@tab_details.sql SCOTT EMP' AS Example, 'table detail' AS tag FROM dual UNION ALL
SELECT 'tabstat.sql' AS name, 'Stats details for non PARTITIONED table' AS description, '@tabstat.sql <OWNER> <TABLE>
' AS Usage, '@tabstat.sql SCOTT DEPT' AS Example, 'table stat' AS tag FROM dual UNION ALL
SELECT 'tspstat.sql' AS name, 'Stats details for SUB-PARTITIONED table' AS description, '@tspstat.sql <owner> <table_name> <partition_name> <subpartition_name>
' AS Usage, '@tspstat.sql SCOTT EMP EMP1998 EMP EMP1998_ITALY'||chr(10)||'@tspstat.sql SCOTT EMP EMP1998 EMP %' AS Example, 'subpart stat' AS tag FROM dual UNION ALL
SELECT 'tpstat.sql' AS name, 'Stats details for PARTITIONED table' AS description, '@tpstat.sql <OWNER> <TABLE> <PARTITION>
' AS Usage, '@tpstat.sql SCOTT EMP EMP1998' AS Example, 'part stat' AS tag FROM dual UNION ALL
SELECT 'stats_history.sql' AS name, 'Display table statistics history' AS description, '@stats_history.sql <OWNER> <OBJ_NAME> <PART_NAME> <OBJ_TYPE>
' AS Usage, '@stats_history.sql XPS LOAD % %' AS Example, 'history stat' AS tag FROM dual UNION ALL
SELECT 'stats_getpref_table.sql' AS name, 'Get table statistics prefs' AS description, '@stats_getpref_table.sql <owner> <table_name>
' AS Usage, '@stats_getpref_table.sql REPORT REP112' AS Example, 'pref stat' AS tag FROM dual UNION ALL
SELECT 'stats_getpref_global.sql' AS name, 'Get GLOBAL statistics prefs' AS description, '@stats_getpref_global.sql
' AS Usage, '' AS Example, 'pref stat' AS tag FROM dual UNION ALL
SELECT 'sqltt_sqlid.sql' AS name, 'Create SQL Tuning Task for SQL_ID' AS description, '@sqltt_sqlid.sql <sql_id> <max_minutes>
' AS Usage, '@sqltt_sqlid.sql 70mfpusqy9jvj 5' AS Example, 'tuning task' AS tag FROM dual UNION ALL
SELECT 'awr_snapshot.sql' AS name, 'Create AWR snapshot' AS description, '@awr_snapshot.sql
' AS Usage, '' AS Example, 'awr snapshot' AS tag FROM dual UNION ALL
SELECT 'sql_profile.sql' AS name, 'Display all SQL Profiles' AS description, '@sql_profile.sql
' AS Usage, '' AS Example, 'sqlprofile' AS tag FROM dual UNION ALL
SELECT 'sql_profile_detail.sql' AS name, 'Display SQL Profile detail' AS description, '@sql_profile_detail.sql <sql_profile>
' AS Usage, '@sql_profile_detail.sql sqlprof_2v4h21kf9bz0h' AS Example, 'sqlprofile' AS tag FROM dual UNION ALL
SELECT 'create_spb_from_cur.sql' AS name, 'Create SQL Plan Baseline from Library Cache' AS description, '@create_spb_from_cur.sql <sql_id>
' AS Usage, '@create_spb_from_cur.sql g3sm89z3xb4zs' AS Example, 'baseline spb' AS tag FROM dual UNION ALL
SELECT 'create_spb_from_awr.sql' AS name, 'Create SQL Plan Baseline from AWR' AS description, '@create_spb_from_awr.sql <sql_id>
' AS Usage, '@create_spb_from_awr.sql g3sm89z3xb4zs' AS Example, 'baseline spb awr' AS tag FROM dual UNION ALL
SELECT 'sql_plan_baselines.sql' AS name, 'List SQL Plan Baselines' AS description, '@sql_plan_baselines.sql
' AS Usage, '' AS Example, 'baseline spb' AS tag FROM dual UNION ALL
SELECT 'sqlid_sign.sql' AS name, 'Display force matching signature of SQL_ID' AS description, '@sqlid_sign.sql <sql_id>
' AS Usage, '' AS Example, 'signature' AS tag FROM dual UNION ALL
SELECT 'awrsign.sql' AS name, 'AWR history for this force matching signature' AS description, '@awrsign.sql <force_matching_signature> <from_date> <to_date>
' AS Usage, '' AS Example, 'signature' AS tag FROM dual UNION ALL
SELECT 'awrsqlid.sql' AS name, 'AWR history of SQL_ID' AS description, '@awrsqlid.sql <force_matching_signature> <from_date> <to_date>
' AS Usage, '' AS Example, 'awr' AS tag FROM dual UNION ALL
SELECT 'ashtop.sql' AS name, 'ASH time from GV$ACTIVE_SESSION_HISTORY grouped by dimensions' AS description, '@ashtop.sql <grouping_cols> <filters> <fromtime> <totime>
' AS Usage, '@ashtop.sql username,sql_id session_type=''FOREGROUND'' sysdate-1/24 sysdate' AS Example, 'ash' AS tag FROM dual UNION ALL
SELECT 'dashtop.sql' AS name, 'ASH time from DBA_HIST_ACTIVE_SESS_HISTORY grouped by dimensions' AS description, '@dashtop.sql <grouping_cols> <filters> <fromtime> <totime>
' AS Usage, '@dashtop.sql sql_id 1=1 "TIMESTAMP''2024-02-06 09:10:35''" "TIMESTAMP''2024-02-06 12:20:50''"' AS Example, 'ash' AS tag FROM dual UNION ALL
SELECT 'ash_wait_chains.sql' AS name, 'ASH wait chains GV$ACTIVE_SESSION_HISTORY' AS description, '@ash_wait_chains.sql <grouping_cols> <filters> <fromtime> <totime>
' AS Usage, '@ash_wait_chains.sql username||'':''||program2||event2 session_type=''FOREGROUND'' sysdate-1/24 sysdate' AS Example, 'ash wait chain' AS tag FROM dual UNION ALL
SELECT 'dash_wait_chains.sql' AS name, 'ASH wait chains DBA_HIST_ACTIVE_SESS_HISTORY' AS description, '@dash_wait_chains.sql <grouping_cols> <filters> <fromtime> <totime>
' AS Usage, '@dash_wait_chains.sql username||'':''||program2||event2 session_type=''FOREGROUND'' "TIMESTAMP''2024-02-06 09:10:35''" "TIMESTAMP''2024-02-06 12:20:50''"' AS Example, 'ash wait chain' AS tag FROM dual UNION ALL
SELECT 'asqlmon.sql' AS name, 'Report SQL-monitoring-style from ASH (GV$ACTIVE_SESSION_HISTORY)' AS description, '@asqlmon.sql <sqlid> <child#> <from_time> <to_time>
' AS Usage, '' AS Example, 'ash sqlmon' AS tag FROM dual UNION ALL
SELECT 'dasqlmon.sql' AS name, 'Report SQL-monitoring-style from ASH (DBA_HIST_ACTIVE_SESS_HISTORY)' AS description, '@dasqlmon.sql <sqlid> <child#> <from_time> <to_time>
' AS Usage, '' AS Example, 'ash sqlmon' AS tag FROM dual UNION ALL
SELECT 'transaction_long_running.sql' AS name, 'Long running transactions' AS description, '@transaction_long_running.sql <complement_where_clause>
' AS Usage, '@transaction_long_running.sql "and 1=1"'||chr(10)||'@transaction_long_running.sql "and sid=3198"' AS Example, 'trans' AS tag FROM dual UNION ALL
SELECT 'pardef.sql' AS name, 'Table (and index) partitions definition' AS description, '@pardef.sql <owner> <table_name> <part_name>
' AS Usage, '@pardef.sql POC DEMO1 %' AS Example, 'part' AS tag FROM dual UNION ALL
SELECT 'planx.sql' AS name, 'Carlos Sierra Explain Plan from LC/AWR' AS description, '@planx.sql <diag_pack_licence> <sql_id>
' AS Usage, '@planx.sql Y gy2zd0jzw3w6y' AS Example, 'explain cache library awr' AS tag FROM dual UNION ALL
SELECT 's.sql' AS name, 'Display current Session Wait and SQL_ID' AS description, '@s.sql <list of sid>
' AS Usage, '@s.sql 52,110,225'||chr(10)||'@s.sql "select sid from v$session where username = ''XYZ''"'||chr(10)||'@s/sql &mysid' AS Example, 'session wait sql_id' AS tag FROM dual UNION ALL
SELECT 'usess.sql' AS name, 'User session ldetails (SQL_ID, event, module etc.)' AS description, '@usess.sql <where_clause>
' AS Usage, '@usess.sql "1=1"'||chr(10)||'@usess.sql s.status=''ACTIVE'''||chr(10)||'@usess.sql "s.status=''ACTIVE'' and s.username=''STREAM_USER'' and s.module like ''%REPLI%''"' AS Example, 'session wait' AS tag FROM dual UNION ALL
SELECT 'sess.sql' AS name, 'User session (idevelopment.info)' AS description, '@sess.sql
' AS Usage, '' AS Example, 'session' AS tag FROM dual UNION ALL
SELECT 'sessa.sql' AS name, 'User active session (idevelopment.info)' AS description, '@sessa.sql
' AS Usage, '' AS Example, 'session active' AS tag FROM dual UNION ALL
SELECT 'locked_objects.sql' AS name, 'Locked objects' AS description, '@locked_objects.sql <owner> <object_name> <object_type> <where_clause>
' AS Usage, '@locked_objects.sql % % % "and 1=1"'||chr(10)||'@locked_objects.sql SCOTT EMP % "and 1=1"'||chr(10)||'@locked_objects.sql % % % "and osuser!=''oracle'' and owner!=''SYS''"' AS Example, 'lock' AS tag FROM dual UNION ALL
SELECT 'locks.sql' AS name, 'Displays currently locked objects in database' AS description, '@locks.sql
' AS Usage, '' AS Example, 'lock' AS tag FROM dual UNION ALL
SELECT 'locks_blocking.sql' AS name, 'Displays blocking locks in database' AS description, '@locks_blocking.sql
' AS Usage, '' AS Example, 'lock block' AS tag FROM dual UNION ALL
SELECT 'sid_details.sql' AS name, 'Display Session Details' AS description, '@sid_details.sql <sid> <indt_id>
' AS Usage, '@sid_details.sql 7531 3' AS Example, 'session' AS tag FROM dual UNION ALL
SELECT 'nonshared.sql' AS name, 'Print reasons for non-shared child cursors from V$SQL_SHARED_CURSOR' AS description, '@nonshared.sql <sql_id>
' AS Usage, '@nonshared.sql 7gf6xg9xfv3vb' AS Example, 'shared cursor' AS tag FROM dual UNION ALL
SELECT 'o.sql' AS name, 'Display object' AS description, '@o.sql <owner>.<object_name>
' AS Usage, '@o.sql SCOTT.EMP'||chr(10)||'@o.sql %.EMP%' AS Example, 'object' AS tag FROM dual UNION ALL
SELECT 'xawr.sql' AS name, 'Execution plan from AWR' AS description, '@xawr.sql <sql_id> <phv>
' AS Usage, '@xawr.sql 6qqf9bakz7j3n 1522095726' AS Example, 'awr sql_id' AS tag FROM dual UNION ALL
SELECT 'wrka.sql' AS name, 'PGA and TEMP usage' AS description, '@wrka.sql <where_clause>
' AS Usage, '@wrka.sql 1=1 '||chr(10)||'@wrka.sql sid=123'||chr(10)||'@wrka.sql username=''APPUSER'' '||chr(10)||'@wrka.sql @wrka "program LIKE ''%BatchRunner.exe%'' AND machine=''host123''"' AS Example, 'temp pga' AS tag FROM dual UNION ALL
SELECT 'wrkasum.sql' AS name, 'Summary of PGA and TEMP' AS description, '@wrkasum.sql <where_clause>
' AS Usage, '@wrkasum.sql sql_id=''7q729nhdgtsqq''' AS Example, 'temp pga' AS tag FROM dual UNION ALL
SELECT 'arch_size_hourly.sql' AS name, 'Archivelog size history by DAY' AS description, '@arch_size_hourly.sql <number_of_days>
' AS Usage, '@arch_size_hourly.sql 7' AS Example, 'arch' AS tag FROM dual UNION ALL
SELECT 'arch_size_hourly_detail.sql' AS name, 'Archivelog size history by HOUR' AS description, '@arch_size_hourly_detail.sql <number_of_days>
' AS Usage, '@arch_size_hourly_detail.sql 2' AS Example, 'arch' AS tag FROM dual UNION ALL
SELECT 'arch_switch_hist.sql' AS name, 'Archivelog switch history by DAY+HOUR' AS description, '@arch_switch_hist.sql
' AS Usage, '@arch_switch_hist.sql' AS Example, 'arch switch' AS tag FROM dual UNION ALL
SELECT 'recovery_area_usage.sql' AS name, 'Display Recovery Area Usage' AS description, '@recovery_area_usage.sql
' AS Usage, '@recovery_area_usage.sql' AS Example, 'recovery area recovery area fra' AS tag FROM dual UNION ALL
SELECT 'log.sql' AS name, 'Show redo log layout' AS description, '@log.sql
' AS Usage, '@log.sql' AS Example, 'log redo standby' AS tag FROM dual UNION ALL
SELECT 'tbs.sql' AS name, 'Tablespace usage' AS description, '@tbs.sql <tablespace_name>
' AS Usage, '@tbs.sql %'||chr(10)||'@tbs USERS' AS Example, 'tablespace' AS tag FROM dual UNION ALL
SELECT 'dba_registry.sql' AS name, 'Database registry/components' AS description, '@dba_registry.sql
' AS Usage, '@dba_registry.sql' AS Example, 'registry component' AS tag FROM dual UNION ALL
SELECT 'dba_invalid_objects.sql' AS name, 'List invalid objects' AS description, '@dba_invalid_objects.sql
' AS Usage, '@dba_invalid_objects.sql' AS Example, 'invalid' AS tag FROM dual UNION ALL
SELECT 'tpardef.sql' AS name, 'Table only partitions definition' AS description, '@tpardef.sql <owner> <table_name> <part_name>
' AS Usage, '@tpardef.sql POC DEMO1 %' AS Example, 'part' AS tag FROM dual UNION ALL
SELECT 'sqlid.sql' AS name, 'SQL_ID details from Library Cache' AS description, '@sqlid.sql <SQL_ID> <CHILD_NUMBER>
' AS Usage, '@sqlid.sql a5ks9fhw2v9s1 %'||chr(10)||'@sqlid.sql a5ks9fhw2v9s1 0' AS Example, 'sqlid cache library' AS tag FROM dual UNION ALL
SELECT 'hint.sql' AS name, 'SQL Hint information' AS description, '@hint.sql <hint_pattern>
' AS Usage, '@hint.sql FULL'||chr(10)||'@hint.sql MERGE' AS Example, 'hint' AS tag FROM dual
)
)
SELECT name,description,usage,example FROM q
WHERE
(upper(name) LIKE upper ('%&search_string%') OR regexp_like(name, '&search_string', 'i'))
OR (upper(description) LIKE upper ('%&search_string%') OR regexp_like(description, '&search_string', 'i'))
OR (upper(tag) LIKE upper ('%&search_string%') OR regexp_like(tag, '&search_string', 'i'))
ORDER BY
name ASC
/
UNDEFINE search_string
CLEAR COLUMNS

23
star/hint.sql Normal file
View File

@@ -0,0 +1,23 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
col name for a35
col version for a15
col version_outline for a15
col inverse for a35
col hint_scope for a27
select
name,
version,
version_outline,
inverse,
decode(bitand(target_level,1),1,'STATEMENT ') ||
decode(bitand(target_level,2),2,'QBLOCK ') ||
decode(bitand(target_level,4),4,'OBJECT ') ||
decode(bitand(target_level,8),8,'JOIN ') hint_scope
from v$sql_hint
where lower(name) like lower('%&1%')
/

95
star/i.sql Normal file
View File

@@ -0,0 +1,95 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at https://blog.tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms and conditions.
--------------------------------------------------------------------------------
--
-- Name: i.sql
-- Purpose: the Who am I script (also sets terminal title)
--
-- Author: Tanel Poder
-- Copyright: (c) http://blog.tanelpoder.com
--
-- Other: Some settings client OS specific (search for title)
--
--------------------------------------------------------------------------------
def mysid="NA"
def _i_spid="NA"
def _i_cpid="NA"
def _i_opid="NA"
def _i_serial="NA"
def _i_inst="NA"
def _i_host="NA"
def _i_user="&_user"
def _i_conn="&_connect_identifier"
col i_username head USERNAME for a20
col i_sid head SID for a5 new_value mysid
col i_serial head "SERIAL#" for a8 new_value _i_serial
col i_cpid head CPID for a15 new_value _i_cpid
col i_spid head SPID for a10 new_value _i_spid
col i_opid head OPID for a5 new_value _i_opid
col i_host_name head HOST_NAME for a25 new_value _i_host truncate
--col i_instance_name head CON@INST_NAME for a20 new_value _i_inst
col i_instance_name head INST_NAME for a20 new_value _i_inst
col i_ver head VERSION for a12
col i_startup_day head STARTED for a19
col _i_user noprint new_value _i_user
col _i_conn noprint new_value _i_conn
col i_myoraver noprint new_value myoraver
col i_inst head I# FOR 99
col i_db_role head DB_ROLE FOR A17
col d_open_mode head OPEN_MODE FOR A17
select
s.username i_username,
-- i.instance_name i_instance_name,
(CASE WHEN TO_NUMBER(SUBSTR(i.version, 1, instr(i.version,'.',1)-1)) >= 12 THEN (SELECT SYS_CONTEXT('userenv', 'con_name') FROM dual)||'-'||i.instance_name ELSE i.instance_name END) i_instance_name,
i.host_name i_host_name,
sys_context('userenv', 'database_role') i_db_role,
d.open_mode,
i.instance_number i_inst,
to_char(s.sid) i_sid,
to_char(s.serial#) i_serial,
(select substr(banner_full, instr(banner_full, 'Version ')+8,11) from v$version where rownum = 1) i_ver,
-- (select substr(banner, instr(banner, 'Release ')+8,10) from v$version where rownum = 1) i_ver,
(select substr(substr(banner, instr(banner, 'Release ')+8),
1,
instr(substr(banner, instr(banner, 'Release ')+8),'.')-1)
from v$version
where rownum = 1) i_myoraver,
to_char(startup_time, 'YYYY-MM-DD HH24:MI:SS') i_startup_day,
trim(p.spid) i_spid,
trim(to_char(p.pid)) i_opid,
s.process i_cpid,
s.saddr saddr,
p.addr paddr,
lower(s.username) "_i_user",
upper('&_connect_identifier') "_i_conn"
from
v$session s,
v$instance i,
v$process p,
v$database d
where
s.paddr = p.addr
and
sid = (select sid from v$mystat where rownum = 1);
-- Windows CMD.exe specific stuff
--host title &_i_user@&_i_conn [sid=&mysid ser#=&_i_serial spid=&_i_spid inst=&_i_inst host=&_i_host cpid=&_i_cpid opid=&_i_opid]
--host doskey /exename=sqlplus.exe desc=set lines 80 sqlprompt ""$Tdescribe $*$Tset lines 299 sqlprompt "SQL> "
-- short xterm title
-- host echo -ne '\033]0;&_i_user@&_i_inst &mysid[&_i_spid]\007'
-- long xterm title
--host echo -ne "\033]0;host=&_i_host inst=&_i_inst sid=&mysid ser#=&_i_serial spid=&_i_spid cpid=&_i_cpid opid=&_i_opid\007"
def myopid=&_i_opid
def myspid=&_i_spid
def mycpid=&_i_cpid
-- undef _i_spid _i_inst _i_host _i_user _i_conn _i_cpid

205
star/init.sql Normal file
View File

@@ -0,0 +1,205 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- Name: init.sql
-- Purpose: Initializes sqlplus variables for 156 character terminal width and other settings.
--
-- Author: Tanel Poder
-- Copyright: (c) http://www.tanelpoder.com
--
-- Other: You need to comment out the right variable definitions for your client platform below.
-- Assumes SQLPATH variable set to point to TPT script directory.
--
--------------------------------------------------------------------------------
-- this must be here to avoid logon problems when SQLPATH env variable is unset
def SQLPATH=""
-- set SQLPATH variable to either Unix or Windows format
def SQLPATH=$SQLPATH -- (Unix/Mac OSX)
--def SQLPATH=%SQLPATH% -- (Windows)
-- def _start=start -- Windows
-- def _start=firefox -- Unix/Linux
def _start=open -- MacOS
def _delete="rm -f" -- Unix/MacOSX
-- def _delete="del" -- Windows
def _tpt_tempdir=&SQLPATH/tmp
-- some internal variables required for TPT scripts
define _ti_sequence=0
define _tptmode=normal
define _xt_seq=0
define all='"select /*+ no_merge */ sid from v$session"'
define prev="(select /*+ no_unnest */ prev_sql_id from v$session where sid = (select sid from v$mystat where rownum=1))"
-- geeky shorcuts for producing date ranges for various ASH scripts
define min="sysdate-1/24/60 sysdate"
define 1min="sysdate-1/24/60 sysdate"
define minute="sysdate-1/24/60 sysdate"
define 5min="sysdate-1/24/12 sysdate"
define hour="sysdate-1/24 sysdate"
define 1hour="sysdate-1/24 sysdate"
define 2hours="sysdate-1/12 sysdate"
define 24hours="sysdate-1 sysdate"
define day="sysdate-1 sysdate"
define today="TRUNC(sysdate) sysdate"
set errordetails off
-- you should change linesize to match terminal width - 1 only
-- if you don't have a terminal with horizontal scrolling
-- capability (cmd.exe and Terminator terminal do have horizontal scrolling)
set linesize 999
-- set truncate after linesize on
-- set truncate on
-- set pagesize larger to avoid repeting headings
set pagesize 5000
-- fetch 10000000 bytes of long datatypes. good for
-- querying DBA_VIEWS and DBA_TRIGGERS
set long 10000000
set longchunksize 10000000
-- larger arraysize for faster fetching of data
-- note that arraysize can affect outcome of experiments
-- like buffer gets for select statements etc.
--
-- setting from 500 to 100 as otherwise snapper/dbms_output starts getting ORA-6502 errors due to 32k fetch limit of dbms_output
set arraysize 100
-- normally I keep this commented out, otherwise
-- a DBMS_OUTPUT.GET_LINES call is made after all
-- PL/SQL executions from sqlplus. this may distort
-- execution statistics for experiments
--set serveroutput on size unlimited
-- to have less garbage on screen
set verify off
-- to trim trailing spaces from spool files
set trimspool on
-- to trim trailing spaces from screen output
set trimout on
-- don't use tabs instead of spaces for "wide blanks"
-- this can mess up the vertical column locations in output
set tab off
-- this makes describe command better to read and more
-- informative in case of complex datatypes in columns
set describe depth 1 linenum on indent on
-- you can make sqlplus run any command as your editor
-- I could use "start notepad" on windows if you want to
-- return control back to sqlplus immediately after launching
-- notepad (so that you can continue typing in sqlplus
define _editor="vi -c 'set notitle'"
-- define _external_editor="/Applications/Terminator.app/Contents/MacOS/Terminator vi "
-- assign the tracefile name to trc variable
def trc=unknown
column tracefile noprint new_value trc
-- its nice to have termout off here as otherwise this would be
-- displayed on the screen
set termout off
select value ||'/'||(select instance_name from v$instance) ||'_ora_'||
(select spid||case when traceid is not null then '_'||traceid else null end
from v$process where addr = (select paddr from v$session
where sid = (select sid from v$mystat
where rownum = 1
)
)
) || '.trc' tracefile
from v$parameter where name = 'user_dump_dest';
column tracefile print
-- make default date format nicer
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
-- include username and connect identifier in prompt
-- column pr new_value _pr
-- select initcap('&_user@&_connect_identifier> ') pr from dual;
-- set sqlprompt "&_pr"
-- column _pr clear
-- format some more columns for common DBA queries
col first_change# for 99999999999999999
col next_change# for 999999999999999999999
col checkpoint_change# for 99999999999999999
col resetlogs_change# for 99999999999999999
col plan_plus_exp for a100
col value_col_plus_show_param ON HEADING 'VALUE' FORMAT a100
col name_col_plus_show_param ON HEADING 'PARAMETER_NAME' FORMAT a60
-- oracle 12.2+ has too wide OWNER and OBJECT_NAME...
col owner for a30 wrap
col object_name for a30 wrap
col subobject_name for a30 wrap
col segment_name for a30 wrap
col partition_name for a30 wrap
-- set html format
@@htmlset nowrap "&_user@&_connect_identifier report"
-- set seminar logging file
DEF _tpt_tempfile=sqlplus_tmpfile
col seminar_logfile new_value seminar_logfile
col tpt_tempfile new_value _tpt_tempfile
select
to_char(sysdate, 'YYYYMMDD-HH24MISS') seminar_logfile
, instance_name||'-'||to_char(sysdate, 'YYYYMMDD-HH24MISS') tpt_tempfile
from v$instance;
def seminar_logfile=&SQLPATH/logs/&_tpt_tempfile..log
-- spool sqlplus output
spool &seminar_logfile append
set editfile afiedit.sql
-- set up a default ref cursor for Snapper V4 begin/end snapshotting
-- var snapper refcursor
-- reset termout back to normal
set termout on

122
star/locked_objects.sql Normal file
View File

@@ -0,0 +1,122 @@
/*
* Author : Vishal Gupta
* Purpose : Displays currently locked objects in database
* Parameters : 1 - owner (% - wildchar, \ - escape char) , this could also be passed as OWNER.OBJECT_NAME
* 2 - Object name (% - wildchar, \ - escape char)
* 3 - Object Type (% - wildchar, \ - escape char)
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 29-Jan-16 Vishal Gupta Switched from gv$locked_objects to gv$lock, as
* earlier view was giving information about locks on
* temporary tables (with preserve on commit rows setting).
* - Also added machine and process in the output
* 06-Sep-12 Vishal Gupta Added where clause to add more filtering
* 09-Aug-12 Vishal Gupta Created
*
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE owner
UNDEFINE object_name
UNDEFINE object_type
UNDEFINE WHERE_CLAUSE
DEFINE owner="&&1"
DEFINE object_name="&&2"
DEFINE object_type="&&3"
DEFINE WHERE_CLAUSE="&&4"
COLUMN _owner NEW_VALUE owner NOPRINT
COLUMN _object_name NEW_VALUE object_name NOPRINT
COLUMN _object_type NEW_VALUE object_type NOPRINT
set term off
SELECT DECODE(UPPER('&&owner'),'','%','&&owner') "_owner"
, DECODE(UPPER('&&object_name'),'','%','&&object_name') "_object_name"
, DECODE(UPPER('&&object_type'),'','%','&&object_type') "_object_type"
FROM DUAL;
SELECT CASE
WHEN INSTR('&&owner','.') != 0 THEN SUBSTR(UPPER('&&owner'),1,INSTR('&&owner','.')-1)
ELSE DECODE(UPPER('&&owner'),'','%',UPPER('&&owner'))
END "_owner"
, CASE
WHEN INSTR('&&owner','.') != 0 THEN SUBSTR(UPPER('&&owner'),INSTR('&&owner','.')+1)
ELSE DECODE(UPPER('&&object_name'),'','%',UPPER('&&object_name'))
END "_object_name"
FROM DUAL;
set term on
PROMPT **************************************************************
PROMPT * L O C K E D O B J E C T S
PROMPT *
PROMPT * Input Parameters
PROMPT * - Owner = '&&owner'
PROMPT * - Object Name = '&&object_name'
PROMPT * - Object Type = '&&object_type'
PROMPT * - Where Clause = "&&WHERE_CLAUSE"
PROMPT **************************************************************
COLUMN object_name HEADING "ObjectName" FORMAT a40
COLUMN object_type HEADING "ObjectType" FORMAT a10 TRUNCATED
COLUMN locked_mode HEADING "LockedMode" FORMAT a10
COLUMN sid HEADING "SID" FORMAT 99999
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN spid HEADING "SPID" FORMAT a6
COLUMN status HEADING "Status" FORMAT a8
COLUMN state HEADING "State" FORMAT a12 TRUNCATED
COLUMN logon_time HEADING "Logon Time" FORMAT a18
COLUMN username HEADING "UserName" FORMAT a20
COLUMN osuser HEADING "OS User" FORMAT a15 TRUNCATED
COLUMN MACHINE HEADING "Machine" FORMAT a20 TRUNCATED
COLUMN process HEADING "Process" FORMAT a11
COLUMN program HEADING "Program" FORMAT a18 TRUNCATED
COLUMN event HEADING "Event" FORMAT a30 TRUNCATED
COLUMN last_call_et HEADING "LastCall|(sec)" FORMAT a12
COLUMN sql_child_number HEADING "SQL|Child|No" FORMAT 99
SELECT o.owner || '.' || o.object_name object_name
, o.object_type
, DECODE(l.lmode,
0, 'None', /* Mon Lock equivalent */
1, 'Null', /* N */
2, 'Row-S (SS)', /* L */
3, 'Row-X (SX)', /* R */
4, 'Share', /* S */
5, 'S/Row-X (SSX)', /* C */
6, 'Exclusive', /* X */
TO_CHAR(l.lmode)) locked_mode
, s.sid sid
, s.inst_id
, s.status
, s.username
, s.machine
, s.osuser
, s.program
, s.process
, s.event
FROM gv$lock l
JOIN dba_objects o ON o.object_id = l.id1
JOIN gv$session s ON s.inst_id = l.inst_id AND s.sid = l.sid
WHERE o.owner like '&&owner' ESCAPE '\'
AND o.object_name like '&&object_name' ESCAPE '\'
AND o.object_type like '&&object_type' ESCAPE '\'
&&WHERE_CLAUSE
ORDER BY object_name
;
UNDEFINE owner
UNDEFINE object_name
UNDEFINE object_type
UNDEFINE WHERE_CLAUSE

88
star/locks.sql Normal file
View File

@@ -0,0 +1,88 @@
@@header
/*
Author : Vishal Gupta
Purpose : Displays currently locked objects in database
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 05-Aug-04 Vishal Gupta First Draft
* 25-Sep-09 Vishal Gupta Modified to use v$lock as DBA_LOCK might not
* exist in some databases if rdbms/admin/dbablock.sql
* has not been run.
*/
COLUMN Blocking HEADING "Bl'ing" FORMAT a6
COLUMN Blocked HEADING "Bl'ed" FORMAT a6
COLUMN Since FORMAT a18
COLUMN inst_id HEADING 'I#' FORMAT 99
rem COLUMN sid FORMAT 9999
COLUMN username FORMAT a15
COLUMN osuser FORMAT a11 TRUNC
COLUMN machine FORMAT a15
COLUMN lock_type FORMAT a22 TRUNC
COLUMN mode_held FORMAT a13
COLUMN mode_requested FORMAT a13
COLUMN mode_requested FORMAT a13
COLUMN owner FORMAT a15
COLUMN object_type FORMAT a10
COLUMN object_name FORMAT a25
SELECT /*+ RULE */
DECODE(lk.block,1,'Y',0,' ', lk.block) Blocking
, DECODE(s.lockwait,NULL,' ','Y') Blocked
-- , DECODE(block,
-- 0, 'Not Blocking', /* Not blocking any other processes */
-- 1, 'Blocking', /* This lock blocks other processes */
-- 2, 'Global', /* This lock is global, so we can't tell */
-- TO_CHAR(block)) blocking_others
, TO_CHAR(sysdate - (lk.ctime/24/60/60),'DD-MON-YY hh24:MI:SS') Since
, lk.inst_id
, lk.sid
, s.status
, s.username
, s.osuser
, NVL(t.name, lk.type) lock_type
, DECODE(lk.lmode,
0, 'None', /* Mon Lock equivalent */
1, 'Null', /* N */
2, 'Row-S (SS)', /* L */
3, 'Row-X (SX)', /* R */
4, 'Share', /* S */
5, 'S/Row-X (SSX)', /* C */
6, 'Exclusive', /* X */
TO_CHAR(lmode)) mode_held
, DECODE(request,
0, 'None', /* Mon Lock equivalent */
1, 'Null', /* N */
2, 'Row-S (SS)', /* L */
3, 'Row-X (SX)', /* R */
4, 'Share', /* S */
5, 'S/Row-X (SSX)', /* C */
6, 'Exclusive', /* X */
TO_CHAR(request)) mode_requested
, NVL(ob.object_type,' ') object_type
, NVL(ob.owner,' ') owner
, NVL(ob.object_name,' ') object_name
FROM gv$lock lk
, dba_objects ob
, gv$session s
, v$lock_type t
WHERE lk.inst_id = s.inst_id
AND lk.sid = s.sid
AND lk.id1 = ob.object_id (+)
AND lk.type = t.type (+)
AND lk.type NOT IN
(
'MR' -- Media Recovery
, 'AE' -- Edition Lock
)
-- AND (lk.block = 1 OR s.lockwait IS NOT NULL )
ORDER BY lk.block desc, s.lockwait desc , s.sid, ob.object_name
/
@@footer

96
star/locks_blocking.sql Normal file
View File

@@ -0,0 +1,96 @@
/*
Author : Vishal Gupta
Purpose : Displays blocking locks in database
* Revision History:
* ===================
* Date Author Description
* --------- ------------ --------------------------------------------------------
* 19-Oct-12 Vishal Gupta Added ClientProcess in output and changed column sizing
* 18-Apr-12 Vishal Gupta Replace with gv$session with materialize hinted
* sub-query factoring (CTE - common table extression)
* 27-Feb-12 Vishal Gupta Created
*
*/
PROMPT
PROMPT *********************************
PROMPT * B L O C K I N G L O C K S
PROMPT *********************************
PROMPT
COLUMN INST_ID HEADING "I#" FORMAT 99
COLUMN SID FORMAT a30
COLUMN username HEADING "UserName" FORMAT a20 TRUNC
COLUMN lock_type HEADING "Lock|type" FORMAT a4 TRUNC
COLUMN lock_Name HEADING "Lock Name" FORMAT a22 TRUNC
COLUMN lmode HEADING "Lock|Held" FORMAT a10
COLUMN request HEADING "Lock|Request" FORMAT a10
COLUMN osuser HEADING "OSUser" FORMAT a20 TRUNC
COLUMN machine HEADING "Client|Machine" FORMAT a20 TRUNC
COLUMN process HEADING "Client|Process" FORMAT a10
COLUMN program HEADING "Program" FORMAT a30 TRUNC
COLUMN event HEADING "Event" FORMAT a30 TRUNC
--
-- Need to use Subquery for gv$session, otherwise session is disconnected with
-- ORA-07445 [qksopCheckPropOpt] when joining dynamic performance views in heirarichal query.
--
WITH sess as
( select /*+ RULE NO_MERGE */ s1.* from gv$session s1
)
, locks as
(select /*+ RULE NO_MERGE */ *
from gv$lock where lmode = 0
--AND ( lmode = 0 OR (lmode > 0 AND block > 0))
)
SELECT /*+ RULE */
s.inst_id
, DECODE(level
,1 , s.sid || ' (Blocker)'
, ' ' || LPAD('-',(level-1)*4,'|---') || '> ' || s.sid
)
sid
, s.status
, NVL2(lt.type,lt.type || ': ' , NULL)|| lt.name lock_name
, DECODE(l.lmode
,0,'None'
,1,'Null'
,2,'Row-S (SS)'
,3,'Row-X (SX)'
,4,'Share (S)'
,5,'S/Row-X (SSX)'
,6,'Excl (X)'
, l.lmode
) lmode
, DECODE(l.request
,0,'None'
,1,'Null'
,2,'Row-S (SS)'
,3,'Row-X (SX)'
,4,'Share (S)'
,5,'S/Row-X (SSX)'
,6,'Excl (X)'
, l.request
) request
, s.username
, s.sql_id
, s.machine
, s.osuser
, s.process
, s.program
, s.event
FROM sess s
LEFT OUTER JOIN locks l ON l.inst_id = s.inst_id AND l.sid = s.sid
LEFT OUTER JOIN v$lock_type lt ON l.type = lt.type
WHERE ( s.blocking_session IS NOT NULL
OR exists (select 1 from sess s2 where s2.blocking_instance = s.inst_id and s2.blocking_session = s.sid)
)
CONNECT BY PRIOR s.inst_id = s.blocking_instance
AND PRIOR s.sid = s.blocking_session
START WITH s.blocking_session IS NULL
;

10
star/log.sql Normal file
View File

@@ -0,0 +1,10 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
prompt Show redo log layout from V$LOG, V$STANDBY_LOG and V$LOGFILE...
col log_member head MEMBER for a100
select * from v$log order by group#;
select * from v$standby_log order by group#;
select group#, status, type, is_recovery_dest_file, member log_member from v$logfile order by group#,member;

11
star/login.sql Normal file
View File

@@ -0,0 +1,11 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
-- calling init.sql which will set up sqlpus variables
@init.sql
-- i.sql is the "who am i" script which shows your session/instance info and
-- also sets command prompt window/xterm title
@i.sql
-- you can put your own login scripts here

60
star/nonshared.sql Normal file
View File

@@ -0,0 +1,60 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: nonshared.sql
-- Purpose: Print reasons for non-shared child cursors from v$sql_shared_cursor
-- in a readable format
--
-- Author: Tanel Poder
-- Copyright: (c) http://www.tanelpoder.com
--
-- Usage: @nonshared <sql_id>
-- @nonshared 7gf6xg9xfv3vb
--
-- Other: Uses modified version of Tom Kyte's printtab code
-- ( http://asktom.oracle.com )
--
--------------------------------------------------------------------------------
set serverout on size 1000000
prompt Show why existing SQL child cursors were not reused (V$SQL_SHARED_CURSOR)...
prompt
def cmd="select * from v$sql_shared_cursor where sql_id = ''&1''"
declare
l_theCursor integer default dbms_sql.open_cursor;
l_columnValue varchar2(4000);
l_status integer;
l_descTbl dbms_sql.desc_tab;
l_colCnt number;
procedure execute_immediate( p_sql in varchar2 )
is
BEGIN
dbms_sql.parse(l_theCursor,p_sql,dbms_sql.native);
l_status := dbms_sql.execute(l_theCursor);
END;
begin
dbms_sql.parse( l_theCursor, replace( '&cmd', '"', ''''), dbms_sql.native );
dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );
for i in 1 .. l_colCnt loop
dbms_sql.define_column( l_theCursor, i, l_columnValue, 4000 );
end loop;
l_status := dbms_sql.execute(l_theCursor);
while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
for i in 1 .. l_colCnt loop
dbms_sql.column_value( l_theCursor, i, l_columnValue );
if l_columnValue != 'N' then
dbms_output.put_line ( rpad( l_descTbl(i).col_name, 30 ) || ': ' || l_columnValue );
end if;
end loop;
dbms_output.put_line( '-----------------' );
end loop;
end;
/
set serverout off

4
star/o.sql Normal file
View File

@@ -0,0 +1,4 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
@@o2 "%&1%"

85
star/pardef.sql Normal file
View File

@@ -0,0 +1,85 @@
set lines 256 pages 50
col TABLE_OWNER for a25 heading "Owner"
col TABLE_NAME for a30 heading "Table"
col OWNER for a25 heading "Owner"
col INDEX_NAME for a30 heading "Index"
col INDEX_TYPE for a10 heading "Type"
col PARTITIONED for a3 heading "Par"
col PARTITION_POSITION for 999 heading "P#"
col PARTITION_NAME for a30 heading "Partition"
col SUBPARTITION_NAME for a30 heading "Subpartition"
col PART_HIGHVAL for a32 trunc heading "Partition|high value"
col PART_INTERVAL for a3 heading "Par|Int"
col SUBPART_HIGHVAL for a32 trunc heading "Subpartition|high value"
col SUBPART_INTERVAL for a3 heading "Sub|Int"
col NUM_ROWS heading "Rows"
col DISTINCT_KEYS heading "Dist|keys"
col CLUSTERING_FACTOR heading "CLUF"
define v_table_owner=&&1
define v_table_name=&&2
prompt
prompt Table
prompt =====
select
par.TABLE_OWNER
,par.TABLE_NAME
,par.PARTITION_POSITION
,par.PARTITION_NAME
,par.NUM_ROWS
,par.HIGH_VALUE PART_HIGHVAL
,par.INTERVAL PART_INTERVAL
,sub.SUBPARTITION_NAME
,sub.NUM_ROWS
,sub.HIGH_VALUE SUBPART_HIGHVAL
,sub.INTERVAL SUBPART_INTERVAL
from
dba_tab_partitions par
left outer join dba_tab_subpartitions sub
on (par.TABLE_OWNER=sub.TABLE_OWNER) and (par.TABLE_NAME=sub.TABLE_NAME) and(par.PARTITION_NAME=sub.PARTITION_NAME)
where
par.table_owner='&&v_table_owner'
and par.table_name='&&v_table_name'
order by
par.PARTITION_POSITION asc
,sub.SUBPARTITION_POSITION asc
;
prompt Index
prompt =====
select
ind.OWNER
,ind.INDEX_NAME
,ind.INDEX_TYPE
,ind.STATUS
,ind.PARTITIONED
,ind.NUM_ROWS
,ind.DISTINCT_KEYS
,ind.CLUSTERING_FACTOR
,indpar.PARTITION_NAME
,indpar.NUM_ROWS
,indpar.DISTINCT_KEYS
,indpar.CLUSTERING_FACTOR
,indsubpar.SUBPARTITION_NAME
,indsubpar.NUM_ROWS
,indsubpar.DISTINCT_KEYS
,indsubpar.CLUSTERING_FACTOR
from
dba_tables tab
left join dba_indexes ind on (tab.TABLE_NAME=ind.TABLE_NAME)
left outer join dba_ind_partitions indpar on (ind.OWNER=indpar.INDEX_OWNER and ind.INDEX_NAME=indpar.INDEX_NAME)
left outer join dba_ind_subpartitions indsubpar on (ind.OWNER=indsubpar.INDEX_OWNER and ind.INDEX_NAME=indsubpar.INDEX_NAME and indpar.PARTITION_NAME=indsubpar.PARTITION_NAME)
where
tab.owner='&&v_table_owner'
and tab.table_name='&&v_table_name'
order by
ind.INDEX_NAME asc
,indpar.PARTITION_POSITION asc
,indsubpar.SUBPARTITION_POSITION asc
;

1409
star/planx.sql Normal file

File diff suppressed because it is too large Load Diff

80
star/raclocks.sql Normal file
View File

@@ -0,0 +1,80 @@
-- https://easyteam.fr/dealing-with-lock-issues-in-oracle-rac-environnement/
@@myheader.sql
col running_session for a20
col machine for a30
col osuser for a20
col username for a20
col module for a20
col event for a30
col wait_class for a20
col inst_id for 9 head I#
WITH
-- global lock view
gl AS (
select
inst_id || '-' || sid instsid, id1, id2,
ctime, lmode, block, request
from
gv$lock
),
-- joins the global lock view on itself to identify locks
l AS (
SELECT
l1.instsid holding_session,
l2.instsid waiting_session
FROM
gl l1,
gl l2
WHERE
l1.block > 0
AND l2.request > 0
AND l1.id1=l2.id1
AND l1.id2=l2.id2
),
-- result view (tree of locked sessions)
rs AS (
SELECT
lpad(' ',3*(level-1),' ') || waiting_session running_session
FROM (
-- first insert as in utllockt
(SELECT
'-' holding_session, holding_session waiting_session
FROM
l
MINUS
SELECT
'-', waiting_session
FROM
l
)
UNION ALL
-- second insert as in utllockt
SELECT
holding_session, waiting_session
FROM
l
)
CONNECT BY PRIOR
waiting_session = holding_session
START WITH
holding_session = '-'
),
-- useful session informations
s AS (
SELECT
inst_id, sid,serial#, module,machine, osuser, username,
nvl(sql_id, '-') sql_id, event, wait_class
FROM gv$session
)
-- final tree
SELECT
*
FROM
rs
JOIN
s ON ltrim(rs.running_session)=s.inst_id || '-' || s.sid;
@@myfooter.sql

View File

@@ -0,0 +1,66 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display Recovery Area Usage
* Compatibility : 11.2 and above
* Parameters : NONE
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 22-Jan-16 Vishal Gupta Added total computation
* 02-May-13 Vishal Gupta Updated to display space used in GB
* 30-Jul-12 Vishal Gupta Created
*
*/
PROMPT *****************************************************************
PROMPT * R E C O V E R Y A R E A U S A G E
PROMPT *****************************************************************
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN name HEADING "Name" FORMAT a28
COLUMN value HEADING "Value" FORMAT a15
COLUMN type HEADING "Type" FORMAT a10
COLUMN ordinal HEADING "Ordinal" FORMAT 99
COLUMN isdefault HEADING "Def|ault?" FORMAT a5
COLUMN ismodified HEADING "Modi|fied?" FORMAT a8
COLUMN isadjusted HEADING "Adjus|ted?" FORMAT a5
SELECT p.inst_id
, p.name
, TRIM(TO_CHAR(ROUND(p.value / 1024 / 1024 / 1024),'999,999') || ' GB') value
FROM gv$system_parameter p
WHERE p.name = 'db_recovery_file_dest_size'
ORDER BY p.inst_id
;
COLUMN file_type HEADING "File Type" FORMAT a25
COLUMN number_of_files HEADING "Files (#)" FORMAT 999,999,999
COLUMN space_used HEADING "Space|Used|(MB)" FORMAT 999,999,999
COLUMN space_reclaimable HEADING "Space|Reclaimable|(MB)" FORMAT 999,999,999
COLUMN percent_space_used HEADING "Space|Used|(%)" FORMAT 999.99
COLUMN percent_space_reclaimable HEADING "Space|Reclaimable|(%)" FORMAT 999.99
BREAK ON REPORT
COMPUTE SUM LABEL 'Total' OF number_of_files FORMAT 999,999,999 ON REPORT
COMPUTE SUM LABEL 'Total' OF space_used FORMAT 999,999,999 ON REPORT
COMPUTE SUM LABEL 'Total' OF space_reclaimable FORMAT 999,999,999 ON REPORT
COMPUTE SUM LABEL 'Total' OF percent_space_used FORMAT 999.99 ON REPORT
COMPUTE SUM LABEL 'Total' OF percent_space_reclaimable FORMAT 999.99 ON REPORT
SELECT r.file_type
, r.number_of_files
, ROUND(r.percent_space_used * p.value / 100 / 1024 / 1024) space_used
, ROUND(r.percent_space_reclaimable * p.value / 100 / 1024 / 1024) space_reclaimable
, r.percent_space_used
, r.percent_space_reclaimable
FROM v$recovery_area_usage r
, v$system_parameter p
WHERE p.name = 'db_recovery_file_dest_size'
;

80
star/s.sql Normal file
View File

@@ -0,0 +1,80 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
--------------------------------------------------------------------------------
--
-- File name: s.sql
-- Purpose: Display current Session Wait and SQL_ID info (10g+)
--
-- Author: Tanel Poder
-- Copyright: (c) http://www.tanelpoder.com
--
-- Usage: @s <sid>
-- @s 52,110,225
-- @s "select sid from v$session where username = 'XYZ'"
-- @s &mysid
--
--------------------------------------------------------------------------------
col sw_event head EVENT for a40 truncate
col sw_p1transl head P1TRANSL for a42
col sw_sid head SID for 999999
col sw_p1 head P1 for a18 justify left word_wrap
col sw_p2 head P2 for a18 justify left word_wrap
col sw_p3 head P3 for a19 justify left word_wrap
col sw_blocking_session head BLOCKING_SID for a12
col sqlid_and_child for a20
select
sid sw_sid,
sql_id || ' '|| TO_CHAR( sql_child_number ) sqlid_and_child,
-- sql_exec_start,
status,
CASE WHEN state != 'WAITING' THEN 'WORKING'
ELSE 'WAITING'
END AS state,
CASE WHEN state != 'WAITING' THEN 'On CPU / runqueue'
ELSE event
END AS sw_event,
seq#,
seconds_in_wait sec_in_wait,
--wait_time_micro / 1000000 sec_in_wait2,
CASE WHEN blocking_session_status = 'VALID' THEN TO_CHAR(blocking_session)||CASE WHEN blocking_instance != USERENV('INSTANCE') THEN ' inst='||blocking_instance ELSE NULL END ELSE blocking_session_status END sw_blocking_session,
CASE state WHEN 'WAITING' THEN NVL2(p1text,p1text||'= ',null)||CASE WHEN P1 < 536870912 THEN to_char(P1) ELSE '0x'||rawtohex(P1RAW) END ELSE null END SW_P1,
CASE state WHEN 'WAITING' THEN NVL2(p2text,p2text||'= ',null)||CASE WHEN P2 < 536870912 THEN to_char(P2) ELSE '0x'||rawtohex(P2RAW) END ELSE null END SW_P2,
CASE state WHEN 'WAITING' THEN NVL2(p3text,p3text||'= ',null)||CASE WHEN P3 < 536870912 THEN to_char(P3) ELSE '0x'||rawtohex(P3RAW) END ELSE null END SW_P3,
CASE state WHEN 'WAITING' THEN
CASE
WHEN event like 'cursor:%' THEN
'0x'||trim(to_char(p1, 'XXXXXXXXXXXXXXXX'))
WHEN event like 'enq%' AND state = 'WAITING' THEN
'0x'||trim(to_char(p1, 'XXXXXXXXXXXXXXXX'))||': '||
chr(bitand(p1, -16777216)/16777215)||
chr(bitand(p1,16711680)/65535)||
' mode '||bitand(p1, power(2,14)-1)
WHEN event like 'latch%' AND state = 'WAITING' THEN
'0x'||trim(to_char(p1, 'XXXXXXXXXXXXXXXX'))||': '||(
select name||'[par'
from v$latch_parent
where addr = hextoraw(trim(to_char(p1,rpad('0',length(rawtohex(addr)),'X'))))
union all
select name||'[c'||child#||']'
from v$latch_children
where addr = hextoraw(trim(to_char(p1,rpad('0',length(rawtohex(addr)),'X'))))
)
WHEN event like 'library cache pin' THEN
'0x'||RAWTOHEX(p1raw)
ELSE NULL END
ELSE NULL END AS sw_p1transl
FROM
v$session
WHERE
sid IN (&1)
ORDER BY
state,
sw_event,
p1,
p2,
p3
/

72
star/sess.sql Normal file
View File

@@ -0,0 +1,72 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : sess_users.sql |
-- | CLASS : Session Management |
-- | PURPOSE : List all currently connected users. This script is RAC enabled. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : User Sessions (All) |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
-- SET LINESIZE 180
-- SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN instance_name FORMAT a8 HEADING 'Instance'
COLUMN sid FORMAT 999999 HEADING 'SID'
COLUMN serial_id FORMAT 99999999 HEADING 'Serial ID'
COLUMN session_status FORMAT a9 HEADING 'Status'
COLUMN oracle_username FORMAT a18 HEADING 'Oracle User'
COLUMN os_username FORMAT a18 HEADING 'O/S User'
COLUMN os_pid FORMAT a8 HEADING 'O/S PID'
COLUMN session_terminal FORMAT a10 HEADING 'Terminal' TRUNC
COLUMN session_machine FORMAT a30 HEADING 'Machine' TRUNC
COLUMN session_program FORMAT a40 HEADING 'Session Program' TRUNC
BREAK ON instance_name SKIP PAGE
SELECT
i.instance_name instance_name
, s.sid sid
, s.serial# serial_id
, s.status session_status
, s.username oracle_username
, s.osuser os_username
, p.spid os_pid
, s.terminal session_terminal
, s.machine session_machine
, s.program session_program
FROM
gv$session s
INNER JOIN gv$process p ON (s.paddr = p.addr AND s.inst_id = p.inst_id)
INNER JOIN gv$instance i ON (p.inst_id = i.inst_id)
ORDER BY
i.instance_name
, s.sid;

76
star/sessa.sql Normal file
View File

@@ -0,0 +1,76 @@
-- +----------------------------------------------------------------------------+
-- | Jeffrey M. Hunter |
-- | jhunter@idevelopment.info |
-- | www.idevelopment.info |
-- |----------------------------------------------------------------------------|
-- | Copyright (c) 1998-2012 Jeffrey M. Hunter. All rights reserved. |
-- |----------------------------------------------------------------------------|
-- | DATABASE : Oracle |
-- | FILE : sess_users_active.sql |
-- | CLASS : Session Management |
-- | PURPOSE : List all currently connected and active user sessions. This |
-- | script is RAC enabled. |
-- | NOTE : As with any code, ensure to test this script in a development |
-- | environment before attempting to run it in production. |
-- +----------------------------------------------------------------------------+
SET TERMOUT OFF;
COLUMN current_instance NEW_VALUE current_instance NOPRINT;
SELECT rpad(instance_name, 17) current_instance FROM v$instance;
SET TERMOUT ON;
PROMPT
PROMPT +------------------------------------------------------------------------+
PROMPT | Report : Active User Sessions (All) |
PROMPT | Instance : &current_instance |
PROMPT +------------------------------------------------------------------------+
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
-- SET LINESIZE 180
-- SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN instance_name FORMAT a8 HEADING 'Instance'
COLUMN sid FORMAT 999999 HEADING 'SID'
COLUMN serial_id FORMAT 99999999 HEADING 'Serial ID'
COLUMN session_status FORMAT a9 HEADING 'Status'
COLUMN oracle_username FORMAT a18 HEADING 'Oracle User'
COLUMN os_username FORMAT a18 HEADING 'O/S User'
COLUMN os_pid FORMAT a8 HEADING 'O/S PID'
COLUMN session_terminal FORMAT a10 HEADING 'Terminal' TRUNC
COLUMN session_machine FORMAT a30 HEADING 'Machine' TRUNC
COLUMN session_program FORMAT a40 HEADING 'Session Program' TRUNC
BREAK ON instance_name SKIP PAGE
SELECT
i.instance_name instance_name
, s.sid sid
, s.serial# serial_id
, s.status session_status
, s.username oracle_username
, s.osuser os_username
, p.spid os_pid
, s.terminal session_terminal
, s.machine session_machine
, s.program session_program
FROM
gv$session s
INNER JOIN gv$process p ON (s.paddr = p.addr AND s.inst_id = p.inst_id)
INNER JOIN gv$instance i ON (p.inst_id = i.inst_id)
WHERE
s.status = 'ACTIVE'
AND s.username IS NOT null
ORDER BY
i.instance_name
, s.sid;

675
star/sid_details.sql Normal file
View File

@@ -0,0 +1,675 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display Session Details
* Compatibility : 10.1 and above
* Parameters : 1 - SID
* 2 - INST_ID (optional, default to 1)
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ --------------------------------------------------
* 25-JUN-15 Vishal Gupta Changed exadata specific statistics section
* 03-JUN-15 Vishal Gupta Changed event history's average waits from sec to msec.
* 12-MAR-15 Vishal Gupta Added follwoing columns to the output
* command name,
* 05-SEP-14 Vishal Gupta In last 10 SQL statement, removed filter for SQL_EXEC_START IS NOT NULL
* 03-JUL-14 Vishal Gupta Change Top Session Events column formatting
Added PGA and Temp usage in Last 10 SQL statements section
* 20-MAY-14 Vishal Gupta Updated last 10 sql statements query
* 12-Feb-14 Vishal Gupta Changed session tranactions output layout to transpose
* columns to rows.
* 04-Oct-13 Vishal Gupta Added SQL's SQLProfile and sql_plan_baseline
* information to output
* 17-May-13 Vishal Gupta Added last 10 SQL statements from ASH
* 08-Jan-13 Vishal Gupta Added time since last wait in wait-history section
* 05-Sep-12 Vishal Gupta Changed output field layout again.
* 09-Aug-12 Vishal Gupta Changed output field layout
* 11-May-12 Vishal Gupta Change output layout. Instead of SELECT output
* now it display dbms_output lines.
* 27-Mar-12 Vishal Gupta Included the session wait history
* 05-Aug-04 Vishal Gupta Created
*
*/
/************************************
* INPUT PARAMETERS
************************************/
VARIABLE SID number ;
VARIABLE INST_ID number ;
BEGIN
:SID := '&&1';
:INST_ID := NVL('&&2',1);
IF :INST_ID = '' OR :INST_ID IS NULL THEN
:INST_ID := 1;
END IF;
END;
/
/************************************
* CONFIGURATION PARAMETERS
************************************/
UNDEFINE TOP_EVENT_COUNT
UNDEFINE BYTES_FORMAT
UNDEFINE BYTES_HEADING
UNDEFINE BYTES_DIVIDER
DEFINE TOP_EVENT_COUNT=10
DEFINE COUNT_SMALL_FORMAT=9,999
--DEFINE COUNT_SMALL_DIVIDER="1"
--DEFINE COUNT_SMALL_HEADING="#"
DEFINE COUNT_SMALL_DIVIDER="1000"
DEFINE COUNT_SMALL_HEADING="#1000"
DEFINE COUNT_FORMAT=999,999,999,999,999
--DEFINE COUNT_DIVIDER="1"
--DEFINE COUNT_HEADING="#"
DEFINE COUNT_DIVIDER="1000"
DEFINE COUNT_HEADING="#1000"
DEFINE BYTES_FORMAT="999,999,999"
--DEFINE BYTES_DIVIDER="1024"
--DEFINE BYTES_HEADING="KB"
DEFINE BYTES_DIVIDER="1024/1024"
DEFINE BYTES_HEADING="MB"
--DEFINE BYTES_DIVIDER="1024/1024/1024"
--DEFINE BYTES_HEADING="GB"
DEFINE TIME_FORMAT=999,999
DEFINE TIME_DIVIDER="1"
DEFINE TIME_HEADING="sec"
--DEFINE TIME_DIVIDER="60"
--DEFINE TIME_HEADING="min"
COLUMN session_details1 HEADING "Session Details" FORMAT a41
COLUMN session_details2 HEADING "Session Details" FORMAT a70
COLUMN sql_details HEADING "Session Details" FORMAT a151
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN SID HEADING "SID" FORMAT 99999
PROMPT
PROMPT ################# Session Details ##########################
set heading off
select /*+ORDERED */
/* First Column */
TRIM(SUBSTR('Instance : ' || s.inst_id ,1,70)) || chr(10)
|| TRIM(SUBSTR('SID : ' || s.sid ,1,70)) || chr(10)
|| TRIM(SUBSTR('Session Serial# : ' || s.serial# ,1,70)) || chr(10)
|| TRIM(SUBSTR('Status : ' || s.status ,1,70)) || chr(10)
|| TRIM(SUBSTR('State : ' || s.state ,1,70)) || chr(10)
|| TRIM(SUBSTR('Logon Time : ' || TO_CHAR(s.logon_time,'DD-MON-YY HH24:MI:SS') ,1,70)) || chr(10)
|| TRIM(SUBSTR('Session Duration : ' || FLOOR(sysdate-s.logon_time) || 'd '
|| FLOOR(MOD((sysdate-s.logon_time) ,1 ) * 24) || 'h '
|| FLOOR(MOD((sysdate-s.logon_time)*24 ,1 ) * 60) || 'm '
|| FLOOR(MOD((sysdate-s.logon_time)*24*60,1 ) * 60) || 's'
,1,70)) || chr(10)
|| TRIM(SUBSTR('LastCall(sec) : ' || FLOOR(s.last_call_et/ 3600) || 'h '
|| LPAD(FLOOR(MOD(s.last_call_et , 3600 ) / 60),2) || 'm '
|| LPAD(MOD(s.last_call_et, 60 ) ,2) || 's'
,1,70)) || chr(10)
|| TRIM('Failed Over : ' || s.failed_over ) || chr(10)
|| TRIM('Failover Type : ' || s.failover_type ) || chr(10)
|| TRIM('Failover Method : ' || s.failover_method ) || chr(10)
|| TRIM('Parallel Query : ' || s.pq_status ) || chr(10)
|| TRIM('PDML Enabled : ' || s.pdml_enabled ) || chr(10)
|| TRIM('PDML Status : ' || s.pdml_status ) || chr(10)
|| TRIM('PDDL Status : ' || s.pddl_status ) || chr(10)
|| TRIM('SQL Trace : ' || s.sql_trace ) || chr(10)
|| TRIM('SQL Trace Waits : ' || s.sql_trace_waits ) || chr(10)
|| TRIM('SQL Trace Binds : ' || s.sql_trace_binds ) || chr(10)
|| TRIM('SQL Trace PlanStats: ' || s.sql_trace_plan_stats ) || chr(10)
as session_details1
/* Second Column */
, TRIM(SUBSTR('OS Username : ' || s.osuser ,1,70)) || chr(10)
|| TRIM(SUBSTR('Client Machine : ' || s.machine ,1,70)) || chr(10)
|| TRIM(SUBSTR('Client Process : ' || s.process ,1,70)) || chr(10)
|| TRIM(SUBSTR('Program : ' || s.program ,1,70)) || chr(10)
|| TRIM(SUBSTR('Module : ' || s.module ,1,70)) || chr(10)
|| TRIM(SUBSTR('Action : ' || s.action ,1,70)) || chr(10)
|| TRIM(SUBSTR('Client Info : ' || s.client_info ,1,70)) || chr(10)
|| TRIM(SUBSTR('Client Identifier : ' || s.client_identifier ,1,70)) || chr(10)
|| TRIM(SUBSTR('DB UserName : ' || s.username ,1,70)) || chr(10)
|| TRIM(SUBSTR('Schema Name : ' || s.schemaname ,1,70)) || chr(10)
|| TRIM(SUBSTR('ServiceName : ' || s.service_name ,1,70)) || chr(10)
|| TRIM(SUBSTR('DB HostName : ' || i.host_name ,1,70)) || chr(10)
|| TRIM(SUBSTR('Oracle SPID : ' || p.spid ,1,70)) || chr(10)
|| TRIM(SUBSTR('Oracle PID : ' || p.pid ,1,70)) || chr(10)
|| TRIM(SUBSTR('Oracle Process Name: ' || p.pname ,1,70)) || chr(10)
|| TRIM(SUBSTR('Session Type : ' || s.type ,1,70)) || chr(10)
|| TRIM(SUBSTR('Command Name : ' || c.command_name ,1,70)) || chr(10)
|| TRIM(SUBSTR('Wait Event : ' || w.event ,1,70)) || chr(10)
|| TRIM(SUBSTR('Wait(sec) : ' || w.seconds_in_wait ,1,70)) || chr(10)
|| TRIM(SUBSTR('Wait Parameter 1 : ' || w.p1text || ' ' || w.p1 ,1,70)) || chr(10)
|| TRIM(SUBSTR('Wait Parameter 2 : ' || w.p2text || ' ' || w.p2 ,1,70)) || chr(10)
|| TRIM(SUBSTR('Wait Parameter 3 : ' || w.p3text || ' ' || w.p3 ,1,70)) || chr(10)
as session_details2
from gv$instance i
JOIN gv$session s ON i.inst_id = s.inst_id
LEFT OUTER JOIN gv$process p ON p.inst_id = s.inst_id AND p.ADDR = s.PADDR
LEFT OUTER JOIN gv$session_wait w ON w.inst_id = s.inst_id AND w.sid = s.sid
LEFT OUTER JOIN v$sqlcommand c ON c.command_type = s.command
where 1=1
AND s.sid = :SID
AND s.inst_id = :INST_ID
;
PROMPT
PROMPT ################# Currrent SQL Statement ####################
-- Get the SQL Statement being executed
select --+
TRIM(SUBSTR('Current SQL Exec Start : ' || TO_CHAR(s.sql_exec_start,'DD-MON-YY HH24:MI:SS') ,1,150)) || chr(10) ||
TRIM(SUBSTR('Current SQL Exec Duration: ' || NVL2(s.sql_exec_start,FLOOR(sysdate - s.sql_exec_start) || 'd '
|| LPAD(FLOOR(MOD((sysdate - s.sql_exec_start) , 1) * 24 ) ,2) || 'h '
|| LPAD(FLOOR(MOD((sysdate - s.sql_exec_start) * 24 , 1) * 60 ) ,2) || 'm '
|| LPAD(FLOOR(MOD((sysdate - s.sql_exec_start) * 24 * 60 , 1) * 60 ) ,2),'')
,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQL ID : ' || s.sql_id ,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQL Child Number : ' || s.sql_child_number ,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQL Plan : ' || sql.plan_hash_value ,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQL Profile : ' || sql.sql_profile ,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQL Plan Baseline: ' || sql.sql_plan_baseline,1,150)) || chr(10)
|| TRIM(SUBSTR('Current SQLText : ' || sql.sql_text ,1,150)) || chr(10)
|| chr(10)
|| TRIM(SUBSTR('Previous SQL Exec Start : ' || TO_CHAR(s.prev_exec_start,'DD-MON-YY HH24:MI:SS') ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQL ID : ' || s.prev_sql_id ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQL Child Number : ' || s.prev_child_number ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQL Plan : ' || prev_sql.plan_hash_value ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQL Profile : ' || prev_sql.sql_profile ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQL Plan Baseline: ' || prev_sql.sql_plan_baseline ,1,150)) || chr(10)
|| TRIM(SUBSTR('Previous SQLText : ' || prev_sql.sql_text ,1,150))
as sql_details
from gv$session s
, gv$sqlarea sql
, gv$sqlarea prev_sql
where s.inst_id = sql.inst_id (+)
AND s.sql_id = sql.sql_id (+)
AND s.inst_id = prev_sql.inst_id (+)
AND s.prev_sql_id = prev_sql.sql_id (+)
AND s.sid = :SID
AND s.inst_id = :INST_ID
;
PROMPT
PROMPT ############### Session Statistics #######################
COLUMN stat HEADING "Statisic" FORMAT a60
WITH stat1 AS
(
SELECT DECODE(sn.name
,'physical read total bytes' ,1
,'physical reads' ,2
,'physical reads direct' ,3
,'physical reads direct temporary tablespace' ,4
,'physical reads direct (lob)' ,5
,'redo size' ,6
,'redo size for direct writes' ,7
,'CPU used by this session' ,8
,'CPU used when call started' ,9
,'session logical reads' ,10
,'user calls' ,11
,'table fetch by rowid' ,12
,'table fetch continued row' ,13
, 99
) sr_no
, DECODE(sn.name
,'physical reads' ,RPAD('Physical Read Requests' ,35) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
,'redo size' ,RPAD('Redo Size' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/&&BYTES_DIVIDER),'&&BYTES_FORMAT')) || ' &&BYTES_HEADING'
,'redo size for direct writes' ,RPAD('Redo Size (For Direct Reads)' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/&&BYTES_DIVIDER),'&&BYTES_FORMAT')) || ' &&BYTES_HEADING'
,'physical read total bytes' ,RPAD('Physical Read Size' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/&&BYTES_DIVIDER),'&&BYTES_FORMAT')) || ' &&BYTES_HEADING'
,'CPU used when call started' ,RPAD('CPU used when call started',35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/100/&&TIME_DIVIDER),'&&TIME_FORMAT')) || ' &&TIME_HEADING'
,'CPU used by this session' ,RPAD('CPU used by this session' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/100/&&TIME_DIVIDER),'&&TIME_FORMAT')) || ' &&TIME_HEADING'
,'session logical reads' ,RPAD('Logical Reads' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND((ss.value*p.value)/&&BYTES_DIVIDER),'&&BYTES_FORMAT')) || ' &&BYTES_HEADING'
, RPAD(sn.name,35) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
) stat
FROM gv$sesstat ss
, v$statname sn
, v$system_parameter p
WHERE ss.statistic# = sn.statistic#
AND sn.name IN
(
'physical reads'
,'redo size'
,'redo size for direct writes'
,'physical read total bytes'
,'physical reads direct'
,'physical reads direct temporary tablespace'
,'physical reads direct (lob)'
,'user calls'
,'CPU used by this session'
,'CPU used when call started'
,'session logical reads'
,'table fetch by rowid'
,'table fetch continued row'
)
AND p.name = 'db_block_size'
AND ss.inst_id = :INST_ID
AND ss.sid = :SID
ORDER BY sr_no
)
, stat2 as
(
SELECT DECODE(sn.name
,'physical write total bytes' ,1
,'physical writes' ,2
,'physical writes direct' ,3
,'physical writes direct temporary tablespace',4
,'physical writes direct (lob)' ,5
,'temp space allocated (bytes)' ,6
,'session pga memory' ,7
,'session pga memory max' ,8
,'OS User time used' ,9
,'OS System time used' ,10
,'bytes sent via SQL*Net to client' ,11
,'bytes received via SQL*Net from client' ,12
, 99
) sr_no
, DECODE(sn.name
,'physical reads' ,RPAD('Physical Read Requests' ,35) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
,'physical writes' ,RPAD('Physical Write Requests' ,35) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
,'physical read total bytes' ,RPAD('Physical Read Size' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'physical write total bytes' ,RPAD('Physical Write Size' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'temp space allocated (bytes)' ,RPAD('Temp Space Allocated' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'session pga memory' ,RPAD('PGA Memory Used (HostRAM)' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'session pga memory max' ,RPAD('PGA Memory Max (HostRAM)' ,35) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'bytes sent via SQL*Net to client' ,RPAD('Data Sent to Client' ,35)|| ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'bytes received via SQL*Net from client' ,RPAD('Data received from Client' ,35)|| ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
, RPAD(sn.name,35) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
) stat
FROM gv$sesstat ss
, v$statname sn
WHERE ss.statistic# = sn.statistic#
AND sn.name IN
(
'physical writes'
,'physical write total bytes'
,'physical writes direct'
,'physical writes direct temporary tablespace'
,'physical writes direct (lob)'
,'session pga memory'
,'session pga memory max'
,'bytes sent via SQL*Net to client'
,'bytes received via SQL*Net from client'
,'OS User time used'
,'OS System time used'
,'temp space allocated (bytes)'
)
AND ss.inst_id = :INST_ID
AND ss.sid = :SID
ORDER BY sr_no
)
SELECT stat1.stat, stat2.stat
FROM stat1
FULL OUTER JOIN stat2 ON stat1.sr_no = stat2.sr_no
ORDER BY stat1.sr_no
;
PROMPT
PROMPT ######### Session Statistics (Exadata specific) ###########
COLUMN stat HEADING "Statistic" FORMAT a150
WITH stat1 AS
(
SELECT DECODE(sn.name
,'cell physical IO interconnect bytes' ,1
,'cell physical IO interconnect bytes returned by smart scan' ,2
,'physical read total bytes optimized' ,3
,'cell physical IO bytes eligible for predicate offload' ,4
,'cell physical IO bytes saved by storage index' ,5
,'cell physical IO bytes eligible for predicate offload' ,6
,'cell IO uncompressed bytes' ,7
,'cell overwrites in flash cache' ,8
,'cell partial writes in flash cache' ,9
,'cell writes to flash cache' ,10
,'cell num bytes in passthru during predicate offload' ,11
, 99
) sr_no
, DECODE(sn.name
,'cell physical IO interconnect bytes' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'cell physical IO interconnect bytes returned by smart scan' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'physical read total bytes optimized' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'cell physical IO bytes eligible for predicate offload' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'cell physical IO bytes saved by storage index' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'cell physical IO bytes eligible for predicate offload' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
,'cell IO uncompressed bytes' ,RPAD(sn.name ,60) || ' : ' || LTRIM(TO_CHAR(ROUND(ss.value/1024/1024),'&&COUNT_FORMAT')) || ' MB'
, RPAD(sn.name,60) || ' : ' || LTRIM(TO_CHAR(ss.value,'&&COUNT_FORMAT'))
) stat
FROM gv$sesstat ss
, v$statname sn
WHERE ss.statistic# = sn.statistic#
AND sn.name IN
(
'cell physical IO interconnect bytes'
,'cell physical IO interconnect bytes returned by smart scan'
,'physical read total bytes optimized'
,'cell physical IO bytes eligible for predicate offload'
,'cell physical IO bytes saved by storage index'
,'cell physical IO bytes eligible for predicate offload'
,'cell IO uncompressed bytes'
,'cell overwrites in flash cache'
,'cell partial writes in flash cache'
,'cell writes to flash cache'
,'cell num bytes in passthru during predicate offload'
)
AND ss.inst_id = :INST_ID
AND ss.sid = :SID
ORDER BY sr_no
)
SELECT stat1.stat
FROM stat1
ORDER BY stat1.sr_no
;
set heading on
PROMPT
PROMPT ################# Session Transactions ####################
COLUMN xid HEADING "XID" FORMAT a16
COLUMN transaction_status HEADING "Tran|Status" FORMAT a8
COLUMN transaction_start_date HEADING "Tran|StartDate" FORMAT a18
COLUMN tran_duration HEADING "Tran|Duration" FORMAT a15
COLUMN space HEADING "Space|Tran" FORMAT a5
COLUMN recursive HEADING "Recu|rsive|Tran" FORMAT a5
COLUMN noundo HEADING "No|Undo|Tran" FORMAT a4
COLUMN ptx HEADING "Par'l|Tran" FORMAT a5
COLUMN used_undo HEADING "Undo|(&&BYTES_HEADING)" FORMAT &&BYTES_FORMAT
COLUMN log_io HEADING "Logical|IO" FORMAT 999,999,999
COLUMN phy_io HEADING "Physical|IO" FORMAT 999,999,999
COLUMN cr_get HEADING "Consistent|Gets" FORMAT 999,999,999
COLUMN name HEADING "Tran Name" FORMAT a15 WRAP
set heading off
SELECT 'Transaction Name : ' || TRIM(t.name) || chr(10)
|| 'XID : ' || TRIM(t.xid) || chr(10)
|| 'Parent XID : ' || TRIM(t.ptx_xid) || chr(10)
|| 'Tran Status : ' || TRIM(t.status) || chr(10)
|| 'Tran Start Time : ' || TO_CHAR(t.start_date,'DD-MON-YY HH24:MI:SS') || chr(10)
|| 'Tran Duration : ' || FLOOR(sysdate - t.start_date) || 'd '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) , 1) * 24 ) ,2) || 'h '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) * 24 , 1) * 60 ) ,2) || 'm '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) * 24 * 60 , 1) * 60 ) ,2) || 's ' || chr(10)
|| 'Parallel Tran : ' || TRIM(t.ptx) || chr(10)
|| 'Space Tran : ' || TRIM(t.space) || chr(10)
|| 'Recursive Tran : ' || TRIM(t.recursive) || chr(10)
|| 'No UNDO Tran : ' || TRIM(t.noundo) || chr(10)
|| 'Undo : ' || TRIM(TO_CHAR(ROUND((t.used_ublk * p.value)/&&BYTES_DIVIDER),'&&BYTES_FORMAT')) || ' &&BYTES_HEADING' || chr(10)
|| 'Logical IO : ' || TRIM(TO_CHAR(t.log_io,'999,999,999')) || chr(10)
|| 'Physical IO : ' || TRIM(TO_CHAR(t.phy_io,'999,999,999')) || chr(10)
|| 'Consistent Gets : ' || TRIM(TO_CHAR(t.cr_get,'999,999,999')) || chr(10)
FROM gv$transaction t
INNER JOIN gv$session s ON t.inst_id = s.inst_id AND t.ses_addr = s.saddr
INNER JOIN v$parameter p ON p.name = 'db_block_size'
WHERE s.inst_id = :INST_ID
AND s.sid = :SID
ORDER BY t.start_date
;
set heading on
PROMPT
PROMPT ######### Locked Objects ##########################
COLUMN object_name HEADING "ObjectName" FORMAT a40
COLUMN object_type HEADING "ObjectType" FORMAT a10 TRUNCATED
COLUMN locked_mode HEADING "LockedMode" FORMAT a10
SELECT o.owner || '.' || o.object_name object_name
, o.object_type
, DECODE(l.locked_mode,
0, 'None', /* Mon Lock equivalent */
1, 'Null', /* N */
2, 'Row-S (SS)', /* L */
3, 'Row-X (SX)', /* R */
4, 'Share', /* S */
5, 'S/Row-X (SSX)', /* C */
6, 'Exclusive', /* X */
TO_CHAR(l.locked_mode)) locked_mode
FROM gv$locked_object l
JOIN dba_objects o ON o.object_id = l.object_id
JOIN gv$session s ON s.inst_id = l.inst_id AND s.sid = l.session_id
WHERE s.sid = :SID
AND s.inst_id = :INST_ID
ORDER BY object_name
;
PROMPT
PROMPT ######### Session Lock Information #################
COLUMN Block HEADING "Block" FORMAT a10
COLUMN blocking_instance HEADING "Blocking|I#" FORMAT 999999999
COLUMN blocking_instance HEADING "Blocking|I#" FORMAT 999999999
COLUMN blocking_session_status HEADING "Blocking|SID Status" FORMAT a10
COLUMN final_blocking_instance HEADING "Final|Blocking|I#" FORMAT 999999999
COLUMN final_blocking_session HEADING "Final|Blocking|SID" FORMAT 999999999
COLUMN final_blocking_session_status HEADING "Final|Blocking|SID Status" FORMAT a10
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN username HEADING "DBUser" FORMAT a15
COLUMN osuser HEADING "OSUser" FORMAT a15
COLUMN status HEADING "Status" FORMAT a10
COLUMN state HEADING "State" FORMAT a10
COLUMN logon_time HEADING "LogonTime" FORMAT a18
COLUMN service_name HEADING "ServiceName" FORMAT a20
select 'Blocked By' Block
, s.blocking_instance
, s.blocking_session
, s.blocking_session_status
, s.final_blocking_instance
, s.final_blocking_session
, s.final_blocking_session_status
FROM gv$session s
where s.sid = :SID
AND s.inst_id = :INST_ID
and s.blocking_session is NOT NULL
order by 1;
select 'Blocking' Block
, s.inst_id
, s.SID
--, s.SERIAL#
, s.username
, s.osuser
, s.status
, s.state
, CASE
WHEN s.status = 'ACTIVE' THEN s.last_call_et
ELSE NULL
END last_call_et
, TO_CHAR(s.LOGON_TIME,'DD-Mon-YY HH24:MI:SS') logon_time
, s.service_name
, s.sql_id
FROM gv$session s
where (s.blocking_session = :SID
AND s.blocking_instance = :INST_ID)
OR (s.final_blocking_session = :SID
AND s.final_blocking_instance = :INST_ID)
;
PROMPT
PROMPT ######### Session Events (Top &&TOP_EVENT_COUNT) ###
COLUMN wait_class HEAD "WaitClass" FORMAT a20 TRUNCATE
COLUMN event HEAD "EventName" FORMAT a40
COLUMN total_waits HEAD "TotalWaits" FORMAT 9,999,999
COLUMN total_timeouts HEAD "TotalTimeOuts" FORMAT 9,999,999
COLUMN time_waited HEAD "TimeWaited (s)" FORMAT 9,999,999
COLUMN average_wait HEAD "AvgWait (ms)" FORMAT 9,999,999
COLUMN max_wait HEAD "MaxWait (s)" FORMAT 9,999,999
select * from
(
SELECT e.sid
, e.inst_id
, e.wait_class
, e.event
, e.total_waits
, e.total_timeouts
, e.time_waited / 100 time_waited
, e.average_wait * 10 average_wait
, e.max_wait / 100 max_wait
FROM gv$session_event e
WHERE e.sid = :SID
AND e.inst_id = :INST_ID
order by e.time_waited desc, e.total_waits desc
)
where rownum <= &&TOP_EVENT_COUNT
/
PROMPT
PROMPT ######### Session Wait History #####################
COLUMN seq# FORMAT 999
COLUMN state FORMAT a10
COLUMN event HEADING "EventName" FORMAT a40
COLUMN wait_time HEADING "Wait(ms)" FORMAT 99,999
COLUMN TIME_SINCE_LAST_WAIT HEADING "TimeSince|LastWait|(ms)" FORMAT 999,999
COLUMN p1 FORMAT 9999999999
COLUMN p2 FORMAT 9999999999
COLUMN p3 FORMAT 9999999999
COLUMN p1text FORMAT a20
COLUMN p2text FORMAT a20
COLUMN p3text FORMAT a20
SELECT w.sid
, w.inst_id
, w.seq#
, w.event
, w.wait_time * 10 wait_time
, w.TIME_SINCE_LAST_WAIT_MICRO/1000 TIME_SINCE_LAST_WAIT
, w.p1
, w.p1text
, w.p2
, w.p2text
, w.p3
, w.p3text
FROM gv$session_wait_history w
WHERE w.sid = :SID
AND w.inst_id = :INST_ID
ORDER BY seq#
/
PROMPT
PROMPT ######### Last 10 SQL Statements ##################
COLUMN session_id HEADING "SID" FORMAT 99999
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN "session_serial#" HEADING "Serial#" FORMAT 999999
COLUMN FORCE_MATCHING_SIGNATURE FORMAT 99999999999999999999999
COLUMN sql_plan_hash_value HEADING "Plan|Hash|Value" FORMAT 9999999999
COLUMN sql_exec_start FORMAT a19
COLUMN sql_exec_end HEADING "MaxSampleTime" FORMAT a19
COLUMN duration FORMAT a15
COLUMN sql_opname HEADING "SQL|Operation" FORMAT a15 TRUNCATE
COLUMN sql_child_number HEADING "SQL|Ch#" FORMAT 999
COLUMN current_dop HEADING "DOP" FORMAT 999
COLUMN phyread HEADING "Phy|Read|(GB)" FORMAT 9999
COLUMN phywrite HEADING "Phy|Write|(GB)" FORMAT 9999
COLUMN interconnect_io HEADING "Inter|Connect|IO|(GB)" FORMAT 9999
COLUMN pga_allocated HEADING "PGA|(GB)" FORMAT 99.00
COLUMN temp_space_allocated HEADING "Temp|Space|(GB)" FORMAT 999.00
-- Get the SQL Statements from ASH
SELECT * FROM
(
SELECT --ash.sql_exec_id,
--TO_CHAR(NVL(ash.sql_exec_start,MIN(ash.sample_time)),'DD-MON-YY HH24:MI:SS') sql_exec_start
NVL(ash.qc_session_id,ash.session_id) session_id
, NVL(ash.qc_instance_id,ash.inst_id) inst_id
, NVL(ash.qc_session_serial#,ash.session_serial#) session_serial#
, TO_CHAR(NVL(ash.sql_exec_start,MIN(ash.sample_time)),'DD-MON-YY HH24:MI:SS') sql_exec_start
, TO_CHAR(max(ash.sample_time) ,'DD-MON-YY HH24:MI:SS') sql_exec_end
, REPLACE(max(ash.sample_time) - NVL(ash.sql_exec_start,MIN(ash.sample_time)),'+00000000','+') duration
, ash.sql_opname
, ash.sql_id
, ash.sql_child_number
, ash.sql_plan_hash_value
, max(trunc(ash.px_flags / 2097152)) current_dop
, ash.force_matching_signature
, NVL(ash_parent.top_level_sql_id,ash.top_level_sql_id) top_level_sql_id
, ROUND(SUM(ash.delta_read_io_bytes)/power(1024,3)) phyread
, ROUND(SUM(ash.delta_write_io_bytes)/power(1024,3)) phywrite
, ROUND(SUM(ash.delta_interconnect_io_bytes)/power(1024,3)) interconnect_io
, ROUND(MAX(ash.pga_allocated)/power(1024,3),2) pga_allocated
, ROUND(MAX(ash.temp_space_allocated)/power(1024,3),2) temp_space_allocated
FROM gv$session s
JOIN gv$active_session_history ash
ON s.inst_id = NVL(ash.qc_instance_id,ash.inst_id)
AND s.sid = NVL(ash.qc_session_id,ash.session_id)
AND s.serial# = NVL(ash.qc_session_serial#,ash.session_serial#)
LEFT OUTER JOIN gv$active_session_history ash_parent
ON ash_parent.inst_id = ash.qc_instance_id
AND ash_parent.session_id = ash.qc_session_id
AND ash_parent.session_serial# = ash.qc_session_serial#
AND CAST(ash_parent.sample_time as DATE) = ash.sql_exec_start
WHERE s.inst_id = :INST_ID
AND s.sid = :SID
--AND ash.sql_exec_id IS NOT NULL
GROUP BY NVL(ash.qc_session_id,ash.session_id)
, NVL(ash.qc_instance_id,ash.inst_id)
, NVL(ash.qc_session_serial#,ash.session_serial#)
, ash.sql_exec_id
, ash.sql_exec_start
, ash.sql_id
, ash.sql_child_number
, ash.sql_plan_hash_value
, ash.FORCE_MATCHING_SIGNATURE
, ash.sql_opname
, NVL(ash_parent.top_level_sql_id,ash.top_level_sql_id)
ORDER BY
-- max(ash.sample_time) asc
--,
NVL(ash.sql_exec_start,MIN(ash.sample_time)) DESC
, max(ash.sample_time) DESC
)
WHERE ROWNUM <= 10
ORDER BY sql_exec_end
;
PROMPT
PROMPT ######### Kill/Disconnect Command ##################
COLUMN command HEADING "Disconnect Command" FORMAT a60
COLUMN command2 HEADING "Kill Command" FORMAT a60
BEGIN
FOR i IN (select 'alter system disconnect session ''' || s.sid || ',' || s.serial# || ',@' || s.inst_id || ''' immediate ; ' Command
, 'alter system kill session ''' || s.sid || ',' || s.serial# || ',@' || s.inst_id || ''' immediate ; ' Command2
from gv$session s
, gv$process p
where s.inst_id = p.inst_id (+)
AND s.PADDR = p.ADDR (+)
AND s.sid = :SID
AND s.inst_id = :INST_ID)
LOOP
DBMS_OUTPUT.PUT_LINE( i.command || chr(10)
|| i.command2 );
END LOOP;
END;
/

View File

@@ -0,0 +1,52 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display all SQL PLAN Baselines
* Parameters :
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 12-Jun-12 Vishal Gupta First created
*
*/
COLUMN sql_handle HEADING "SQL Handle" FORMAT a20
COLUMN enabled HEADING "Ena|bled" FORMAT a4
COLUMN accepted HEADING "Accep|ted" FORMAT a5
COLUMN fixed HEADING "Fixed" FORMAT a5
COLUMN reproduced HEADING "Repro|duced" FORMAT a5
COLUMN autopurge HEADING "Auto|Purge" FORMAT a5
COLUMN optimizer_cost HEADING "Optimizer|Cost" FORMAT 99999999
COLUMN creator HEADING "Creator" FORMAT a12
COLUMN created HEADING "Created" FORMAT a15
COLUMN last_modified HEADING "LastModified" FORMAT a15
COLUMN last_executed HEADING "LastExecuted" FORMAT a15
COLUMN last_verified HEADING "LastVerified" FORMAT a15
COLUMN force_matching HEADING "Force|Match" FORMAT a5
COLUMN signature HEADING "Signature" FORMAT 999999999999999999999
COLUMN description HEADING "Description" FORMAT a50
BREAK ON name ON CATEGORY ON created ON last_modified ON type ON status ON force_matching ON signature ON description
SELECT spb.sql_handle
, spb.plan_name
, spb.origin
, spb.enabled
, spb.accepted
, spb.fixed
, spb.reproduced
, spb.autopurge
, spb.optimizer_cost
, spb.creator
, to_char(spb.created,'DD-MON-YY HH24:MI') created
, to_char(spb.last_modified,'DD-MON-YY HH24:MI') last_modified
, to_char(spb.last_executed,'DD-MON-YY HH24:MI') last_executed
, to_char(spb.last_verified,'DD-MON-YY HH24:MI') last_verified
, spb.description
FROM dba_sql_plan_baselines spb
ORDER BY spb.last_modified DESC
;

47
star/sql_profile.sql Normal file
View File

@@ -0,0 +1,47 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display all SQL Profiles
* Parameters :
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 13-Jan-14 Vishal Gupta Add additional columns
* 16-May-12 Vishal Gupta Created
*/
COLUMN name HEADING "Name" FORMAT a30
COLUMN category HEADING "Category" FORMAT a15
COLUMN creator HEADING "Creator" FORMAT a15
COLUMN created HEADING "Created" FORMAT a18
COLUMN last_modified HEADING "LastModified" FORMAT a18
COLUMN last_executed HEADING "LastExecuted" FORMAT a18
COLUMN force_matching HEADING "Force|Match" FORMAT a5
COLUMN signature HEADING "Signature" FORMAT 999999999999999999999
COLUMN description HEADING "Description" FORMAT a50
BREAK ON name ON CATEGORY ON created ON last_modified ON type ON status ON force_matching ON signature ON description
SELECT /*+ ORDERED */
sp.name
, sp.category
, ad.creator
, to_char(sp.created,'DD-MON-YY HH24:MI:SS') created
, to_char(sp.last_modified,'DD-MON-YY HH24:MI:SS') last_modified
-- Last executed is display NULL for all the rows
-- , to_char(so.last_executed,'DD-MON-YY HH24:MI:SS') last_executed
, sp.type
, sp.status
, sp.force_matching
, sp.signature
, sp.description
FROM dba_sql_profiles sp
JOIN sys.sqlobj$ so ON so.signature = sp.signature AND so.category = sp.category AND so.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
JOIN sys.sqlobj$auxdata ad ON so.signature = ad.signature AND so.category = ad.category AND ad.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
WHERE 1=1
ORDER BY sp.last_modified DESC
;

View File

@@ -0,0 +1,55 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display all SQL Profiles
* Parameters :
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 16-May-12 Vishal Gupta Created
*/
COLUMN column1 FORMAT a120
UNDEFINE sql_profile_name
DEFINE sql_profile_name="&&1"
DEFINE rpad_length=15
PROMPT *****************************************************************
PROMPT * Profile Details
PROMPT *****************************************************************
set heading off
SELECT /*+ ORDERED */
RPAD('Name',&&rpad_length) || ' : ' || so.name || chr(10) ||
RPAD('Description',&&rpad_length) || ' : ' || sp.description || chr(10) ||
RPAD('Version',&&rpad_length) || ' : ' || ad.version || chr(10) ||
RPAD('Category',&&rpad_length) || ' : ' || sp.category || chr(10) ||
RPAD('Force Matching',&&rpad_length)|| ' : ' || sp.force_matching || chr(10) ||
RPAD('Type',&&rpad_length) || ' : ' || sp.type || chr(10) ||
RPAD('Status',&&rpad_length) || ' : ' || sp.status || chr(10) ||
RPAD('Signature',&&rpad_length) || ' : ' || so.signature || chr(10) ||
RPAD('Creator',&&rpad_length) || ' : ' || ad.creator || chr(10) ||
RPAD('Creation Time',&&rpad_length) || ' : ' || to_char(sp.created,'DD-MON-YY HH24:MI:SS') || chr(10) ||
RPAD('Last Modified',&&rpad_length) || ' : ' || to_char(sp.last_modified,'DD-MON-YY HH24:MI:SS') || chr(10) ||
RPAD('Last Executed',&&rpad_length) || ' : ' || to_char(so.last_executed,'DD-MON-YY HH24:MI:SS') || chr(10) ||
RPAD('Last Verified',&&rpad_length) || ' : ' || to_char(ad.last_verified,'DD-MON-YY HH24:MI:SS') || chr(10) ||
RPAD('SQL Text',&&rpad_length) || ' : ' || chr(10) ||
sp.sql_text || chr(10) ||
' ' column1
FROM dba_sql_profiles sp
JOIN sys.sqlobj$ so ON so.signature = sp.signature AND so.category = sp.category AND so.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
JOIN sys.sqlobj$auxdata ad ON so.signature = ad.signature AND so.category = ad.category AND ad.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
JOIN sys.sql$text st ON so.signature = st.signature
JOIN sys.sql$ sq ON so.signature = sq.signature
WHERE 1=1
AND upper(sp.name) = upper('&&sql_profile_name')
ORDER BY sp.last_modified DESC
;
set heading on

View File

@@ -0,0 +1,35 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display SQL Profile hints
* Parameters : 1 - SQL Profile Name
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 23-Mar-15 Vishal Gupta Created
*
*/
UNDEFINE SQLPROFILENAME
DEFINE SQLPROFILENAME="&&1"
COLUMN outline_hints HEADING "SQL Profile Hints" FORMAT a150
SELECT extractvalue(value(d), '/hint') AS outline_hints
FROM xmltable('/outline_data/hint' passing
(SELECT xmltype(sd.comp_data) as xmlval
FROM dba_sql_profiles sp
JOIN sys.sqlobj$ so ON so.signature = sp.signature AND so.category = sp.category AND so.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
JOIN sys.sqlobj$data sd ON sd.signature = so.signature AND sd.category = so.category AND sd.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
--JOIN sys.sqlobj$auxdata ad ON ad.signature = so.signature AND ad.category = so.category AND ad.obj_type = 1 /* 1 = SQLProfile, 2=SQL Plan */
WHERE 1=1
AND sp.name = '&&SQLPROFILENAME'
)
) d
;

76
star/sqlid.sql Normal file
View File

@@ -0,0 +1,76 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
col sql_sql_text head SQL_TEXT format a150 word_wrap
col sql_child_number head CH# for 9999
col cpu_sec_exec FOR 999999.999
col ela_sec_exec FOR 999999.999
col lios_per_exec FOR 9999999999
col pios_per_exec FOR 9999999999
prompt Show SQL text, child cursors and execution stats for SQLID &1 child &2
select
hash_value,
plan_hash_value,
child_number sql_child_number,
sql_text sql_sql_text
from
v$sql
where
sql_id = ('&1')
and child_number like '&2'
order by
sql_id,
hash_value,
child_number
/
select
child_number sql_child_number,
plan_hash_value plan_hash,
parse_calls parses,
loads h_parses,
executions,
fetches,
rows_processed,
rows_processed/nullif(fetches,0) rows_per_fetch,
ROUND(cpu_time/NULLIF(executions,0)/1000000,3) cpu_sec_exec,
ROUND(elapsed_time/NULLIF(executions,0)/1000000,3) ela_sec_exec,
ROUND(buffer_gets/NULLIF(executions,0),3) lios_per_exec,
ROUND(disk_reads/NULLIF(executions,0),3) pios_per_exec,
ROUND(cpu_time/1000000,3) total_cpu_sec,
ROUND(elapsed_time/1000000,3) total_ela_sec,
user_io_wait_time/1000000 total_iowait_sec,
buffer_gets total_LIOS,
disk_reads total_pios,
sorts
-- address,
-- sharable_mem,
-- persistent_mem,
-- runtime_mem,
-- , PHYSICAL_READ_REQUESTS
-- , PHYSICAL_READ_BYTES
-- , PHYSICAL_WRITE_REQUESTS
-- , PHYSICAL_WRITE_BYTES
-- , IO_CELL_OFFLOAD_ELIGIBLE_BYTES
-- , IO_INTERCONNECT_BYTES
-- , IO_CELL_UNCOMPRESSED_BYTES
-- , IO_CELL_OFFLOAD_RETURNED_BYTES
, users_executing
, last_active_time
, address parent_handle
, child_address object_handle
from
v$sql
where
sql_id = ('&1')
and child_number like '&2'
order by
sql_id,
hash_value,
child_number
/

7
star/sqlid_sign.sql Normal file
View File

@@ -0,0 +1,7 @@
col FORCE_MATCHING_SIGNATURE for 99999999999999999999
select FORCE_MATCHING_SIGNATURE from gv$sql where sql_id='&&1'
union all
select FORCE_MATCHING_SIGNATURE from DBA_HIST_SQLSTAT where sql_id='&&1'
fetch first 1 rows only;

49
star/sqlidtabstat.sql Normal file
View File

@@ -0,0 +1,49 @@
-- https://blogs.oracle.com/optimizer/post/check-sql-stale-statistics
set pagesize 100
set linesize 150
set trims off
set tab off
set verify off
column table_name format a50
column index_name format a50
column object_type format a40
column owner format a40
with plan_tables as (
select distinct object_name,object_owner, object_type
from gv$sql_plan
where object_type like 'TABLE%'
and sql_id = '&1')
select t.object_owner owner,
t.object_name table_name,
t.object_type object_type,
decode(stale_stats,'NO','OK',NULL, 'NO STATS!', 'STALE!') staleness
from dba_tab_statistics s,
plan_tables t
where s.table_name = t.object_name
and s.owner = t.object_owner
and s.partition_name is null
and s.subpartition_name is null
order by t.object_owner, t.object_name;
PROMPT ==========
PROMPT Indexes
PROMPT ==========
with plan_indexes as (
select distinct object_name,object_owner, object_type
from gv$sql_plan
where object_type like 'INDEX%'
and sql_id = '&1')
select i.object_owner owner,
i.object_name index_name,
i.object_type object_type,
decode(stale_stats,'NO','OK',NULL, 'NO STATS!', 'STALE!') staleness
from dba_ind_statistics s,
plan_indexes i
where s.index_name = i.object_name
and s.owner = i.object_owner
and s.partition_name is null
and s.subpartition_name is null
order by i.object_owner, i.object_name;

38
star/sqltt_sqlid.sql Normal file
View File

@@ -0,0 +1,38 @@
set serveroutput ON
variable max_secs NUMBER
begin
:max_secs:=to_number(&2)*60;
end;
/
variable c_tt refcursor
DECLARE
r CLOB;
t varchar2(30) := 'SQLTT_&1';
BEGIN
BEGIN
dbms_sqltune.drop_tuning_task(t);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
r := dbms_sqltune.create_tuning_task(task_name => t, sql_id => '&1', time_limit => :max_secs);
dbms_sqltune.execute_tuning_task(t);
open :c_tt for select dbms_sqltune.report_tuning_task(t) recommendations from dual;
if :c_tt is NULL then
begin
open :c_tt for select 'N/A' recommendations from dual;
end;
end if;
END;
/
print :c_tt

273
star/stats_history.sql Normal file
View File

@@ -0,0 +1,273 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display table statistics history
* Parameters : 1 - OWNER (% - wildchar, \ - escape char)
* 2 - Object Name (% - wildchar, \ - escape char)
* 3 - Partition Name (% - wildchar, \ - escape char)
* 5 - Object Type (% - wildchar, \ - escape char)
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 08-Jul-15 Vishal Gupta Removed savetime column from output
* 19-JUN-14 Vishal Gupta Updated AvgRowLength heading
* 28-FEB-14 Vishal Gupta Changed the ordering
* 02-Jul-12 Vishal Gupta Added partition, sub-partition and objecttype as input
* 30-Apr-12 Vishal Gupta Created
*
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE owner
UNDEFINE object_name
UNDEFINE subobject_name
UNDEFINE object_type
DEFINE owner="&&1"
DEFINE object_name="&&2"
DEFINE subobject_name="&&3"
DEFINE object_type="&&4"
COLUMN _owner NEW_VALUE owner NOPRINT
COLUMN _object_name NEW_VALUE object_name NOPRINT
COLUMN _subobject_name NEW_VALUE subobject_name NOPRINT
COLUMN _object_type NEW_VALUE object_type NOPRINT
set term off
SELECT CASE
WHEN INSTR('&&owner','.') != 0 THEN SUBSTR(UPPER('&&owner'),1,INSTR('&&owner','.')-1)
ELSE DECODE(UPPER('&&owner'),'','%',UPPER('&&owner'))
END "_owner"
, CASE
WHEN INSTR('&&owner','.') != 0 THEN SUBSTR(UPPER('&&owner'),INSTR('&&owner','.')+1)
ELSE DECODE(UPPER('&&object_name'),'','%',UPPER('&&object_name'))
END "_object_name"
, DECODE('&&subobject_name','','%','&&subobject_name') "_subobject_name"
, DECODE('&&object_type','','%','&&object_type') "_object_type"
FROM DUAL
;
set term on
PROMPT
PROMPT ***********************************************************************
PROMPT * S T A T I S T I C S H I S T O R Y
PROMPT *
PROMPT * Input Parameters
PROMPT * - Object Owner = '&&owner'
PROMPT * - Object Name = '&&object_name'
PROMPT * - SubObject Name = '&&subobject_name'
PROMPT * - Object Type = '&&object_type'
PROMPT ***********************************************************************
COLUMN object_name HEADING "ObjectName" FORMAT a60
COLUMN subobject_name HEADING "SubObjectName" FORMAT a30
COLUMN object_type HEADING "Object|Type" FORMAT a18
COLUMN object_type_sort_order NOPRINT
COLUMN savtime HEADING "SaveTime" FORMAT a18
COLUMN ANALYZETIME HEADING "AnalyzeTime" FORMAT a18
COLUMN samplesize HEADING "SampleSize" FORMAT 999,999,999,999
COLUMN rowcnt HEADING "RowCount" FORMAT 999,999,999,999
COLUMN blkcnt HEADING "BlockCount" FORMAT 999,999,999
COLUMN avgrln HEADING "Avg|Row|Length" FORMAT 999,999
COLUMN SizeMB HEADING "Size (MB)" FORMAT 9,999,999
select object_name
, object_type
, object_type_sort_order
--, to_char(savtime,'DD-MON-YY HH24:MI:SS') savtime
, to_char(ANALYZETIME,'DD-MON-YY HH24:MI:SS') ANALYZETIME
, SizeMB
, rowcnt
, avgrln
--, blkcnt
, samplesize
FROM
(
select o.owner || '.' || o.object_name
|| NVL2(o.subobject_name,':' || o.subobject_name, '')
object_name
, o.object_type
, DECODE (o.object_type
, 'TABLE' ,1
, 'TABLE PARTITION' ,2
, 'TABLE SUBPARTITION' ,3
, 'INDEX' ,4
, 'INDEX PARTITION' ,5
, 'INDEX SUBPARTITION' ,6
,9
) object_type_sort_order
, h.savtime
, h.ANALYZETIME
, h.samplesize
, h.rowcnt
, h.avgrln
, (h.blkcnt * p.value) /1024/1024 SizeMB
, h.blkcnt
FROM sys.wri$_optstat_tab_history h
, dba_objects o
, v$system_parameter p
WHERE h.obj# = o.object_id
AND p.name = 'db_block_size'
AND o.owner LIKE upper('&&owner') ESCAPE '\'
AND o.object_name LIKE upper('&&object_name') ESCAPE '\'
AND NVL(o.subobject_name,'%') LIKE upper('&&subobject_name') ESCAPE '\'
AND NVL(DECODE(o.object_type
,'PARTITION','TABLE PARTITION'
,'SUBPARTITION','TABLE SUBPARTITION'
,o.object_type),'%') LIKE upper('&&object_type') ESCAPE '\'
UNION
select s.owner || '.' || s.table_name
|| NVL2(s.partition_name,':' || s.partition_name, '')
object_name
, DECODE(s.object_type
,'PARTITION','TABLE PARTITION'
,'SUBPARTITION','TABLE SUBPARTITION'
,s.object_type) object_type
, DECODE (s.object_type
, 'TABLE' ,1
, 'TABLE PARTITION' ,2
, 'TABLE SUBPARTITION' ,3
, 'INDEX' ,4
, 'INDEX PARTITION' ,5
, 'INDEX SUBPARTITION' ,6
,9
) object_type_sort_order
, NULL savtime
, last_analyzed ANALYZETIME
, sample_size
, num_rows
, avg_row_len
, (s.blocks * p.value) /1024/1024 SizeMB
, s.blocks
FROM dba_tab_statistics s
, v$system_parameter p
WHERE p.name = 'db_block_size'
AND s.owner LIKE upper('&&owner') ESCAPE '\'
AND s.table_name LIKE upper('&&object_name') ESCAPE '\'
AND NVL(s.partition_name,'%') LIKE upper('&&subobject_name') ESCAPE '\'
AND NVL(DECODE(s.object_type
,'PARTITION','TABLE PARTITION'
,'SUBPARTITION','TABLE SUBPARTITION'
,s.object_type),'%') LIKE upper('&&object_type') ESCAPE '\'
) a
ORDER BY a.object_name
, a.object_type_sort_order
, a.savtime NULLS LAST
--, a.ANALYZETIME
/
COLUMN table_name HEADING "IndexName" FORMAT a40
COLUMN object_name HEADING "IndexName" FORMAT a50
COLUMN distinct_keys HEADING "DistinctKeys" FORMAT 99,999,999,999
COLUMN blevel HEADING "BLevel" FORMAT 99999
COLUMN leaf_blocks HEADING "Leaf|Blocks" FORMAT 99,999,999
COLUMN clustering_factor HEADING "Clustering|Factor" FORMAT 99,999,999,999
COLUMN avg_leaf_blocks_per_key HEADING "Avg|LeafBlocks|PerKey" FORMAT 999,999,999
COLUMN avg_data_blocks_per_key HEADING "Avg|DataBlocks|PerKey" FORMAT 999,999,999
select object_name
, object_type
, object_type_sort_order
--, to_char(savtime,'DD-MON-YY HH24:MI:SS') savtime
, to_char(ANALYZETIME,'DD-MON-YY HH24:MI:SS') ANALYZETIME
, SizeMB
, rowcnt
, samplesize
, distinct_keys
, blevel
, clustering_factor
, leaf_blocks
, avg_leaf_blocks_per_key
, avg_data_blocks_per_key
FROM
(
select o.owner || '.' || o.object_name
|| NVL2(o.subobject_name,':' || o.subobject_name, '')
object_name
, o.object_type
, DECODE (o.object_type
, 'TABLE' ,1
, 'TABLE PARTITION' ,2
, 'TABLE SUBPARTITION' ,3
, 'INDEX' ,4
, 'INDEX PARTITION' ,5
, 'INDEX SUBPARTITION' ,6
,9
) object_type_sort_order
, h.savtime
, h.ANALYZETIME
, (h.leafcnt * p.value) /1024/1024 SizeMB
, h.rowcnt
, h.samplesize
, h.distkey distinct_keys
, h.blevel
, h.clufac clustering_factor
, h.leafcnt leaf_blocks
, h.lblkkey avg_leaf_blocks_per_key
, h.dblkkey avg_data_blocks_per_key
--, h.avgrln
FROM sys.wri$_optstat_ind_history h
, dba_objects o
, v$system_parameter p
WHERE h.obj# = o.object_id
AND p.name = 'db_block_size'
AND o.owner LIKE upper('&&owner') ESCAPE '\'
AND o.object_name LIKE upper('&&object_name') ESCAPE '\'
AND NVL(o.subobject_name,'%') LIKE upper('&&subobject_name') ESCAPE '\'
AND NVL(o.object_type,'%') LIKE upper('&&object_type') ESCAPE '\'
UNION ALL
select s.owner || '.' || s.index_name
|| NVL2(s.partition_name,':' || s.partition_name, '')
object_name
, DECODE(s.object_type
,'PARTITION','TABLE PARTITION'
,'SUBPARTITION','TABLE SUBPARTITION'
,s.object_type) object_type
, DECODE (s.object_type
, 'TABLE' ,1
, 'TABLE PARTITION' ,2
, 'TABLE SUBPARTITION' ,3
, 'INDEX' ,4
, 'INDEX PARTITION' ,5
, 'INDEX SUBPARTITION' ,6
,9
) object_type_sort_order
, null savtime
, s.last_analyzed ANALYZETIME
, ROUND((s.leaf_blocks * p.value) /1024/1024 ) SizeMB
, s.num_rows
, s.sample_size
, s.distinct_keys
, s.blevel
, s.clustering_factor
, s.leaf_blocks
, s.avg_leaf_blocks_per_key
, s.avg_data_blocks_per_key
FROM dba_ind_statistics s
, v$system_parameter p
WHERE p.name = 'db_block_size'
AND s.owner LIKE upper('&&owner') ESCAPE '\'
AND s.index_name LIKE upper('&&object_name') ESCAPE '\'
AND NVL(s.partition_name,'%') LIKE upper('&&subobject_name') ESCAPE '\'
AND NVL(DECODE(s.object_type
,'PARTITION','INDEX PARTITION'
,'SUBPARTITION','INDEX SUBPARTITION'
,s.object_type),'%') LIKE upper('&&object_type') ESCAPE '\'
) a
ORDER BY a.object_name
, a.object_type_sort_order
, a.savtime NULLS LAST
--, a.ANALYZETIME
/

359
star/tab_details.sql Normal file
View File

@@ -0,0 +1,359 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display Tables details
* Parameters : 1 - Owner (Use % as wild card, \ as ESCAPE)
* 2 - TableName (Use % as wild card, \ as ESCAPE)
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 22-Aug-16 Vishal Gupta Added child foreign key constrainst list
* 30-Apr-15 Vishal Gupta Added join to dba_objects to get creation date
* 13-Mar-15 Vishal Gupta Added table's indexes in output
* 24-Apr-13 Vishal Gupta Created
*
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE owner
UNDEFINE table_name
DEFINE owner="&&1"
DEFINE table_name="&&2"
COLUMN _owner NEW_VALUE owner NOPRINT
COLUMN _table_name NEW_VALUE table_name NOPRINT
set term off
SELECT SUBSTR(UPPER('&&owner'), 1 , CASE INSTR('&&owner','.') WHEN 0 THEN LENGTH ('&&owner') ELSE INSTR('&&owner','.') - 1 END) "_owner"
, CASE
WHEN INSTR('&&owner','.') != 0 THEN SUBSTR(UPPER('&&owner'),INSTR('&&owner','.')+1)
ELSE UPPER('&&table_name')
END "_table_name"
FROM DUAL;
set term on
PROMPT ************************************
PROMPT * T A B L E D E T A I L S
PROMPT ************************************
COLUMN col1 FORMAT a60
COLUMN col2 FORMAT a60
set head off
SELECT 'Owner : ' || t.owner
|| chr(10) || 'Table Name : ' || t.table_name
|| chr(10) || 'Table Comments : ' || c.comments
|| chr(10) || 'Tablespace Name : ' || t.tablespace_name
|| chr(10) || 'Status : ' || t.status
|| chr(10) || 'Temporary : ' || t.temporary
|| chr(10) || 'Partitioned : ' || t.partitioned
|| chr(10) || 'Compression : ' || t.compression
|| chr(10) || 'Compress For : ' || t.compress_for
|| chr(10) || 'Segment Created : ' || t.segment_created
|| chr(10) || 'Degree : ' || TRIM(t.degree)
|| chr(10) || 'IOT Type : ' || t.iot_type
|| chr(10) || 'IOT Name : ' || t.iot_name
|| chr(10) || 'Logging : ' || t.logging
|| chr(10) || 'Backed Up : ' || t.backed_up
|| chr(10) || 'Instances : ' || TRIM(t.instances)
|| chr(10) || 'Table Lock : ' || t.table_lock
|| chr(10) || 'Secondary : ' || t.secondary
|| chr(10) || 'Nested : ' || t.nested
|| chr(10) || 'Row Movement : ' || t.row_movement
|| chr(10) || 'Duration : ' || t.duration
|| chr(10) || 'Skip Corrupt : ' || t.skip_corrupt
|| chr(10) || 'Monitoring : ' || t.monitoring
|| chr(10) || 'Cluster Owner : ' || t.cluster_owner
|| chr(10) || 'Cluster Name : ' || t.cluster_name
|| chr(10) || 'Dependencies : ' || t.dependencies
|| chr(10) || 'Dropped : ' || t.dropped
|| chr(10) || 'Read Only : ' || t.read_only
|| chr(10) || ' '
|| chr(10) || '[ Cache ] '
|| chr(10) || 'Cache : ' || TRIM(t.cache)
|| chr(10) || 'Buffer Pool : ' || t.buffer_pool
|| chr(10) || 'Flash Cache : ' || t.flash_cache
|| chr(10) || 'Cell Flash Cache : ' || t.cell_flash_cache
|| chr(10) || 'Result Cache : ' || t.result_cache
col1
,
'[ Dates ] '
|| chr(10) || 'Created : ' || TO_CHAR(o.created,'DD-MON-YYYY HH24:MI:SS')
|| chr(10) || 'Last DDL : ' || TO_CHAR(o.last_ddl_time,'DD-MON-YY HH24:MI:SS')
|| chr(10) || 'Last Spec Change : ' || TO_CHAR(TO_DATE(o.timestamp,'YYYY-MM-DD HH24:MI:SS'),'DD-MON-YY HH24:MI:SS')
|| chr(10) || ' '
|| chr(10) || '[ Storage ] '
|| chr(10) || 'PCT Free : ' || t.pct_free
|| chr(10) || 'PCT Used : ' || t.pct_used
|| chr(10) || 'PCT Increase : ' || t.pct_increase
|| chr(10) || 'INI Trans : ' || t.ini_trans
|| chr(10) || 'Max Trans : ' || t.max_trans
|| chr(10) || 'Initial Extent Size : ' || t.initial_extent
|| chr(10) || 'Next Extent Size : ' || t.next_extent
|| chr(10) || 'Mininum Extents : ' || t.min_extents
|| chr(10) || 'Max Extents : ' || t.max_extents
|| chr(10) || 'Freelists : ' || t.freelists
|| chr(10) || 'Freelists Group : ' || t.freelist_groups
|| chr(10) || ' '
|| chr(10) || '[ Statistics ] '
|| chr(10) || 'Last Analyzed : ' || to_char(t.last_analyzed,'DD-MON-YY HH24:MI:SS')
|| chr(10) || 'Global Stats : ' || t.global_stats
|| chr(10) || 'User Stats : ' || t.user_stats
|| chr(10) || 'Sample Size : ' || TRIM(TO_CHAR(t.sample_size,'999,999,999,999,999'))
|| chr(10) || 'Num Rows : ' || TRIM(TO_CHAR(t.num_rows,'999,999,999,999,999'))
|| chr(10) || 'Table Size : ' || TRIM(TO_CHAR((t.blocks * (select BLOCK_SIZE from dba_tablespaces tbs where tbs.tablespace_name = t.tablespace_name) )/power(1024,2),'999,999,999,999,999' )) || ' MB'
|| chr(10) || 'Blocks : ' || t.blocks
|| chr(10) || 'Empty Blocks : ' || t.empty_blocks
|| chr(10) || 'Average Row Length : ' || t.avg_row_len
|| chr(10) || 'Average Space : ' || t.avg_space
|| chr(10) || 'Chain Count : ' || t.chain_cnt
|| chr(10) || 'Freelist Blocks : ' || t.num_freelist_blocks
|| chr(10) || 'Avg Space Freelists Blocks: ' || t.avg_space_freelist_blocks
col2
FROM dba_tables t
JOIN dba_objects o ON o.owner = t.owner AND o.object_name = t.table_name AND o.object_type = 'TABLE'
LEFT OUTER JOIN dba_tab_comments c ON c.owner = t.owner AND c.table_name = t.table_name
WHERE t.owner = '&&owner'
AND t.table_name = '&&table_name'
;
set head on
/* Taken from tab_parts_summary.sql */
PROMPT *******************************
PROMPT * Table's Partitions Details
PROMPT *******************************
COLUMN table_name HEADING "Table Name" FORMAT a40
COLUMN partitioning_type HEADING "Part|Type" FORMAT a7
COLUMN partitioning_key_count HEADING "Part|Key|Count" FORMAT 99999
COLUMN interval HEADING "Interval" FORMAT a30
COLUMN subpartitioning_type HEADING "SubPart|Type" FORMAT a10
COLUMN subpartitioning_key_count HEADING "SubPart|Key|Count" FORMAT 99999
COLUMN def_subpartition_count HEADING "Default|Subpart|Count|PerPart" FORMAT 999
COLUMN status HEADING "Status" FORMAT a8
COLUMN partition_count HEADING "Part|Count" FORMAT 999,999
COLUMN subpartition_count HEADING "SubPart|Count" FORMAT 999,999
COLUMN total_count HEADING "Total|Count" FORMAT 999,999
SELECT pt.owner || '.' || pt.table_name table_name
, pt.status
, pt.partitioning_type
, pt.partitioning_key_count
-- for interval RANGE partition, dba_part_tables.partition_count is always 1048575
-- , so we need to take actual partition count from dba_tab_partitions
, count(distinct p.partition_name) partition_count
, pt.interval
, pt.subpartitioning_type
, pt.subpartitioning_key_count
, pt.def_subpartition_count
, count(s.subpartition_name) subpartition_count
, GREATEST(count(distinct p.partition_name) , count(s.subpartition_name)) total_count
FROM dba_part_tables pt
JOIN dba_tab_partitions p ON p.table_owner = pt.owner AND p.table_name = pt.table_name
LEFT OUTER JOIN dba_tab_subpartitions s ON s.table_owner = pt.owner AND s.table_name = pt.table_name AND p.partition_name = s.partition_name
WHERE 1=1
AND pt.owner LIKE '&&owner' ESCAPE '\'
AND pt.table_name LIKE '&&table_name' ESCAPE '\'
GROUP BY
pt.owner
, pt.table_name
, pt.partitioning_type
, pt.interval
, pt.subpartitioning_type
, pt.def_subpartition_count
, pt.partitioning_key_count
, pt.subpartitioning_key_count
, pt.status
--ORDER BY total_count desc
ORDER BY pt.owner
, pt.table_name
;
/* Taken from tab_indexes.sql */
PROMPT
PROMPT ********************
PROMPT * Table's Indices
PROMPT ********************
COLUMN owner HEADING "Index Owner" FORMAT a20
COLUMN table_name HEADING "Table Name" FORMAT a40
COLUMN index_owner HEADING "Index Owner" FORMAT a20
COLUMN index_name HEADING "Index Name" FORMAT a40
COLUMN index_type HEADING "Index Type" FORMAT a10
COLUMN status HEADING "Status" FORMAT a8
COLUMN visibility HEADING "Visible" FORMAT a10
COLUMN uniqueness HEADING "Uniqueness" FORMAT a15
COLUMN Columns HEADING "Index columns" FORMAT a90
BREAK ON TABLE_NAME
SELECT /*+ */
-- i.table_owner || '.' || i.table_name table_name
--,
i.owner || '.' || i.index_name index_name
, i.uniqueness
, i.index_type
, i.status
, i.visibility
-- , column_name
-- , column_position
-- , CONNECT_BY_ISLEAF
-- , LEVEL
--, SUBSTR(SYS_CONNECT_BY_PATH ( NVL(to_char(ie.column_expression),ic.column_name) || DECODE(ic.descend,'ASC','',' (desc) ') , ' , ' ),4) Columns
, SUBSTR(SYS_CONNECT_BY_PATH ( ic.column_name || DECODE(ic.descend,'ASC','',' (desc) ') , ' , ' ),4) Columns
FROM dba_indexes i
, dba_ind_columns ic
, dba_ind_expressions ie
WHERE i.owner = ic.index_owner
AND i.index_name = ic.index_name
AND i.table_owner = ic.table_owner
AND i.table_name = ic.table_name
AND ic.index_owner = ie.index_owner (+)
AND ic.index_name = ie.index_name (+)
AND ic.table_owner = ie.table_owner (+)
AND ic.table_name = ie.table_name (+)
AND ic.column_position = ie.column_position (+)
AND i.table_owner LIKE upper('&&owner') ESCAPE '\'
AND i.table_name LIKE upper('&&table_name') ESCAPE '\'
AND CONNECT_BY_ISLEAF = 1
AND LEVEL = ic.column_position
CONNECT BY ic.table_owner = PRIOR ic.table_owner
AND ic.table_name = PRIOR ic.table_name
AND ic.index_owner = PRIOR ic.index_owner
AND ic.index_name = PRIOR ic.index_name
AND ic.column_position - 1 = PRIOR ic.column_position
START WITH ic.table_owner LIKE upper('&&owner') ESCAPE '\'
AND ic.table_name LIKE upper('&&table_name') ESCAPE '\'
ORDER BY ic.table_owner
, ic.table_name
, ic.index_owner
, ic.index_name
;
-- Taken from columns.sql
/*
PROMPT
PROMPT ********************
PROMPT * Table's Columns
PROMPT ********************
COLUMN object_name HEADING "ObjectName" FORMAT a45
COLUMN object_type HEADING "ObjectType" FORMAT a17
COLUMN column_id HEADING "ColumnId" FORMAT 9999
COLUMN column_name HEADING "ColumnName" FORMAT a30
COLUMN nullable HEADING "Null?" FORMAT a8
COLUMN Type HEADING "ColumnType" FORMAT a20
COLUMN data_default HEADING "Default|Value" FORMAT a40
COLUMN comments HEADING "Comments" FORMAT a60
SELECT
--c.owner || '.' || c.table_name object_name,
c.column_id
, c.column_name
, DECODE(c.nullable,'N','NOT NULL','') nullable
, CASE
WHEN c.data_type = 'NUMBER'
THEN c.data_type || NVL2(c.data_precision||c.data_scale, '(' || NVL(c.data_precision,'38') || ',' || NVL(c.data_scale,'127') || ')','')
WHEN c.data_type = 'FLOAT'
THEN c.data_type || NVL2(c.data_precision,'(' || c.data_precision || ')','')
WHEN c.data_type = 'VARCHAR2' OR c.data_type = 'CHAR'
THEN c.data_type || '(' || c.char_length || ' ' || DECODE(c.char_used,'B','BYTE','CHAR') || ')'
WHEN c.data_type = 'NVARCHAR2' OR c.data_type = 'NCHAR'
THEN c.data_type || '(' || c.char_length || ')'
WHEN c.data_type = 'RAW' OR c.data_type = 'UROWID'
THEN c.data_type || '(' || c.data_length || ')'
ELSE c.data_type
END Type
, c.data_default
, cc.comments
FROM dba_tab_columns c
LEFT OUTER JOIN dba_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name AND cc.column_name = c.column_name
WHERE UPPER(c.owner) like UPPER('&&owner') ESCAPE '\'
AND UPPER(c.table_name) like UPPER('&&table_name') ESCAPE '\'
AND c.table_name NOT LIKE 'BIN$%'
ORDER BY c.column_id ;
*/
PROMPT
PROMPT ****************************
PROMPT * Table's Constraints
PROMPT ****************************
COLUMN constraint_name HEADING "ConstraintName" FORMAT a30
COLUMN constraint_type HEADING "Type" FORMAT a4
COLUMN status HEADING "Status" FORMAT a8
COLUMN delete_rule HEADING "Delete|Rule" FORMAT a9
COLUMN validated HEADING "Validated"
COLUMN generated HEADING "Generated"
COLUMN last_change HEADING "LastChange" FORMAT a18
COLUMN search_condition HEADING "SearchCondition" FORMAT a50
select *
from
xmltable( '/ROWSET/ROW'
passing dbms_xmlgen.getXMLType('
SELECT c.constraint_name
, c.constraint_type
, c.status
, c.delete_rule
, c.validated
, c.generated
, TO_CHAR(last_change,''DD-MON-YY HH24:MI:SS'') last_change
, c.search_condition /* <---- Long Column type*/
FROM dba_constraints c
WHERE UPPER(c.owner) like UPPER(''' || '&&owner' || ''') ESCAPE ''\''
AND UPPER(c.table_name) like UPPER(''' || '&&table_name' || ''') ESCAPE ''\''
')
columns
constraint_name varchar2(30)
, constraint_type varchar2(30)
, status varchar2(30)
, delete_rule varchar2(9)
, validated varchar2(30)
, generated varchar2(30)
, last_change varchar2(30)
, search_condition varchar2(2000)
)
WHERE 1=1
AND NOT (constraint_type = 'C' AND search_condition LIKE '%NOT NULL%' )
;
PROMPT
PROMPT ********************************************
PROMPT * Child Foreign Key Constraints
PROMPT ********************************************
SELECT c.owner
, c.constraint_name
, c.table_name
, c.r_constraint_name
, c.delete_rule
FROM dba_constraints c
WHERE (c.r_owner, c.r_constraint_name) IN (SELECT c2.owner, c2.constraint_name
FROM dba_constraints c2
WHERE UPPER(c2.owner) like UPPER('&&owner') ESCAPE '\'
AND UPPER(c2.table_name) like UPPER('&&table_name') ESCAPE '\'
AND c2.constraint_type in ('P','U')
)
;

46
star/tabstat.sql Normal file
View File

@@ -0,0 +1,46 @@
/* Statistics details for table partitions/subpartitios
Usage: @tabstat <owner> <table>
vplesnila 2024-01-29: creation
*/
col owner for a20 head "Owner"
col table_name for a25 head "Table name"
col last_DML for a20 head "Last DML"
col last_analyzed for a20 head "Last Analyzed"
col STALE_STATS for a7 head "Stale"
col NUM_ROWS head "#Rows"
col INSERTS head "Table|INS"
col UPDATES head "Table|UPD"
col DELETES head "Table|DEL"
col TRUNCATED head "Table|TRUN"
break on report skip 1
compute sum of INSERTS on report
compute sum of UPDATES on report
compute sum of DELETES on report
select
tabstat.OWNER
,tabstat.TABLE_NAME
,tabstat.NUM_ROWS
,tabstat.STALE_STATS
,tabstat.LAST_ANALYZED
,tabmod.INSERTS
,tabmod.UPDATES
,tabmod.DELETES
,tabmod.TRUNCATED
,tabmod.TIMESTAMP last_DML
from
dba_tab_statistics tabstat
,dba_tab_modifications tabmod
WHERE
tabstat.owner = '&&1'
AND tabstat.table_name = '&&2'
AND tabstat.owner = tabmod.table_owner(+)
AND tabstat.table_name = tabmod.table_name(+)
AND tabstat.partition_name = tabmod.partition_name(+)
AND tabstat.subpartition_name = tabmod.subpartition_name(+)
/

50
star/tabstats.sql Normal file
View File

@@ -0,0 +1,50 @@
col owner for a20 head "Owner"
col table_name for a25 head "Table name"
col PARTITION_NAME for a25 head "Partition name"
col SUBPARTITION_NAME for a25 head "Subpartition name"
col last_DML for a20 head "Last DML"
col last_analyzed for a20 head "Last Analyzed"
col STALE_STATS for a7 head "Stale"
col NUM_ROWS head "#Rows"
col INSERTS head "Table|INS"
col UPDATES head "Table|UPD"
col DELETES head "Table|DEL"
col TRUNCATED head "Table|TRUN"
break on report skip 1
compute sum of INSERTS on report
compute sum of UPDATES on report
compute sum of DELETES on report
select
tabstat.OWNER
,tabstat.TABLE_NAME
,tabstat.PARTITION_NAME
,tabstat.SUBPARTITION_NAME
,tabstat.NUM_ROWS
,tabstat.STALE_STATS
,tabstat.LAST_ANALYZED
,tabmod.INSERTS
,tabmod.UPDATES
,tabmod.DELETES
,tabmod.TRUNCATED
,tabmod.TIMESTAMP last_DML
from
dba_tab_statistics tabstat
,dba_tab_modifications tabmod
WHERE
tabstat.owner = '&&1'
AND tabstat.table_name = '&&2'
AND (tabstat.partition_name like '%&&3%' or tabstat.partition_name is NULL)
AND (tabstat.subpartition_name like '%&&4%' or tabstat.subpartition_name is NULL)
AND tabstat.owner = tabmod.table_owner(+)
AND tabstat.table_name = tabmod.table_name(+)
AND tabstat.partition_name = tabmod.partition_name(+)
AND tabstat.subpartition_name = tabmod.subpartition_name(+)
ORDER BY
tabstat.owner asc,
tabstat.table_name asc,
tabstat.partition_position asc,
tabstat.subpartition_position asc
/

182
star/tbs.sql Normal file
View File

@@ -0,0 +1,182 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display Tablespace usage
* Parameters : 1 - tablespace_name (Use % as wildcard, Default value '%')
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 14-Jul-15 Vishal Gupta Added tablespace creation_time (Approximated from earliest datafile time)
* 11-Mar-13 Vishal Gupta Fixed temp space calculations
* 02-Apr-12 Vishal Gupta Bug fixes
* 05-Aug-04 Vishal Gupta First Draft
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE tablespace_name
DEFINE tablespace_name="&&1"
set term off
COLUMN _TABLESPACE_NAME NEW_VALUE TABLESPACE_NAME NOPRINT
SELECT UPPER(DECODE('&&TABLESPACE_NAME','','%','&&TABLESPACE_NAME')) "_TABLESPACE_NAME"
FROM DUAL;
set term on
/************************************
* CONFIGURATION PARAMETERS
************************************/
DEFINE BYTES_FORMAT="999,999"
--DEFINE BYTES_HEADING="KB"
--DEFINE BYTES_DIVIDER="1024"
--DEFINE BYTES_HEADING="MB"
--DEFINE BYTES_DIVIDER="1024/1024"
DEFINE BYTES_HEADING="GB"
DEFINE BYTES_DIVIDER="1024/1024/1024"
DEFINE ROUND_PRECISION=2
DEFINE STAR=4 --Defines how much %usage is represented by one star on Graph
set term off
SET FEED OFF
SELECT (100/&&STAR+2) UsageGraphWidth
FROM DUAL;
SET FEED ON
set term on
PROMPT *****************************************************************
PROMPT * T A B L E S P A C E U S A G E R E P O R T
PROMPT *
PROMPT * Input Parameters
PROMPT * - Tablespace Name = '&&TABLESPACE_NAME'
PROMPT *****************************************************************
COLUMN UsageGraphWidth NOPRINT old_value UGWidth
COLUMN tablespace_name FORMAT a23
COLUMN creation_time HEADING "Creation Time" FORMAT a15
COLUMN alloc HEADING "Alloc(&&BYTES_HEADING)" FORMAT 9,999,999 ON
COLUMN used HEADING "Used&&BYTES_HEADING)" FORMAT 9,999,999 ON
COLUMN free HEADING "Free|(&&BYTES_HEADING)" FORMAT 999,999 ON
COLUMN pct_Used HEADING "%Used" FORMAT 999 ON
COLUMN pct_Free HEADING "%Free" FORMAT 999 ON
COLUMN MAXSIZE HEADING "MaxSize|(&&BYTES_HEADING)" FORMAT 9,999,999 ON
COLUMN Maxfree HEADING "MaxFree|(&&BYTES_HEADING)" FORMAT 9,999,999 ON
COLUMN Max_pct_Used HEADING "MAX|%Used" FORMAT 999 ON
COLUMN Max_pct_Free HEADING "MAX|%Free" FORMAT 999 ON
COLUMN "Usage Graph" FORMAT a27
COLUMN "MaxUsage Graph" FORMAT a27
BREAK ON REPORT
COMPUTE SUM LABEL 'Total' OF alloc FORMAT 99,999,999 ON REPORT
COMPUTE SUM LABEL 'Total' OF used FORMAT 99,999,999.9 ON REPORT
COMPUTE SUM LABEL 'Total' OF free FORMAT 99,999,999.9 ON REPORT
COMPUTE SUM LABEL 'Total' OF maxsize FORMAT 9,999,999.9 ON REPORT
COMPUTE SUM LABEL 'Total' OF maxfree FORMAT 9,999,999.9 ON REPORT
SELECT /*+ CHOOSE */ c.tablespace_name
, c.alloc
, c.used
, c.free
, c.pct_used
, c.pct_free
, '|' || RPAD(NVL(LPAD(' ',CEIL(NVL(c.pct_used,0)/&&STAR),'*'),' '),CEIL(100/&&STAR)) || '|' "Usage Graph"
, c.MAXSIZE
, c.maxfree
, c.max_pct_used
, c.max_pct_free
, '|' || RPAD(NVL(LPAD(' ',CEIL(NVL(c.max_pct_used,0)/&&STAR),'*'),' '),CEIL(100/&&STAR)) || '|' "MaxUsage Graph"
, TO_CHAR(c.creation_time,'DD-MON-YY HH24:MI') creation_time
FROM (
SELECT /*+ CHOOSE */ a.tablespace_name
, c.creation_time
, ROUND(a.bytes_alloc / &&BYTES_DIVIDER, &&ROUND_PRECISION) alloc
, ROUND((a.bytes_alloc - NVL(b.bytes_free, 0)) / &&BYTES_DIVIDER, &&ROUND_PRECISION ) used
, ROUND(NVL(b.bytes_free, 0) / &&BYTES_DIVIDER, &&ROUND_PRECISION) free
, 100 - ROUND((NVL(b.bytes_free, 0) / a.bytes_alloc) * 100, &&ROUND_PRECISION) pct_Used
, ROUND((NVL(b.bytes_free, 0) / a.bytes_alloc) * 100, &&ROUND_PRECISION) pct_Free
, ROUND(a.maxbytes/ &&BYTES_DIVIDER, &&ROUND_PRECISION) MAXSIZE
, ROUND( (maxbytes - a.bytes_alloc + NVL(b.bytes_free, 0) ) / &&BYTES_DIVIDER , &&ROUND_PRECISION) Maxfree
, ROUND(((a.bytes_alloc - NVL(b.bytes_free, 0)) / a.maxbytes) * 100, &&ROUND_PRECISION) Max_pct_Used
, ROUND( ((a.maxbytes - a.bytes_alloc + NVL(b.bytes_free, 0) ) / a.maxbytes) * 100, &&ROUND_PRECISION) Max_pct_Free
FROM ( SELECT /*+ CHOOSE */
f.tablespace_name
, SUM(f.bytes) bytes_alloc
, SUM(DECODE(f.autoextensible, 'YES',GREATEST(f.maxbytes,f.bytes),'NO', f.bytes)) maxbytes
FROM DBA_DATA_FILES f
WHERE f.tablespace_name LIKE '&&tablespace_name'
GROUP BY tablespace_name
) a
, ( SELECT /*+ CHOOSE */
f.tablespace_name
, SUM(f.bytes) bytes_free
FROM DBA_FREE_SPACE f
WHERE f.tablespace_name LIKE '&&tablespace_name'
GROUP BY tablespace_name
) b
, (SELECT t.name tablespace_name, min(creation_time) creation_time
FROM v$tablespace t , v$datafile f
WHERE t.ts# = f.ts#
GROUP BY t.name) c
WHERE a.tablespace_name = b.tablespace_name (+)
AND a.tablespace_name = c.tablespace_name (+)
UNION ALL
SELECT /*+ CHOOSE */
ts.tablespace_name
, c.creation_time
--, ROUND((ts.bytes_used + ts.bytes_free) / &&BYTES_DIVIDER , &&ROUND_PRECISION) alloc
, ROUND( tf.bytes / &&BYTES_DIVIDER , &&ROUND_PRECISION) alloc
, ROUND((ts.bytes_used - ss.free_bytes) / &&BYTES_DIVIDER , &&ROUND_PRECISION) used
, ROUND(((ts.bytes_free) + ss.free_bytes ) / &&BYTES_DIVIDER , &&ROUND_PRECISION) free
, ROUND(((ts.bytes_used - ss.free_bytes ) / (ts.bytes_used + ts.bytes_free))
* 100, &&ROUND_PRECISION) pct_Used
, 100 - ROUND(((ts.bytes_used - ss.free_bytes) / (ts.bytes_used + ts.bytes_free)) * 100, &&ROUND_PRECISION) pct_Free
, ROUND( tf.max_bytes / &&BYTES_DIVIDER , &&ROUND_PRECISION) MaxSize
, ROUND( ((ts.bytes_free) + ss.free_bytes + (tf.max_bytes - (ts.bytes_used + ts.bytes_free) )
) / &&BYTES_DIVIDER , &&ROUND_PRECISION) Maxfree
, ROUND( ( (ts.bytes_used - ss.free_bytes )/tf.max_bytes) * 100, &&ROUND_PRECISION) Max_pct_Used
, 100 - ROUND( ((ts.bytes_used - ss.free_bytes ) /tf.max_bytes )* 100, &&ROUND_PRECISION ) Max_pct_Free
FROM (SELECT tablespace_name
, sum(bytes_used) bytes_used
, sum(bytes_free) bytes_free
FROM v$temp_space_header
WHERE tablespace_name LIKE '&&tablespace_name'
GROUP BY tablespace_name
) ts
, (SELECT tablespace_name
, SUM(bytes) bytes
, SUM(DECODE(autoextensible, 'YES',GREATEST(maxbytes,bytes),'NO', bytes)) max_bytes
FROM dba_temp_files
WHERE tablespace_name LIKE '&&tablespace_name'
GROUP BY tablespace_name
) tf
, (SELECT ss.tablespace_name
, sum(ss.free_blocks * t.block_size) free_bytes
FROM gv$sort_segment ss
, dba_tablespaces t
WHERE ss.tablespace_name = t.tablespace_name
AND ss.tablespace_name LIKE '&&tablespace_name'
GROUP BY ss.tablespace_name
) ss
, dba_tablespaces t
, (SELECT t.name tablespace_name, min(creation_time) creation_time
FROM v$tablespace t , v$tempfile f
WHERE t.ts# = f.ts#
GROUP BY t.name) c
WHERE t.tablespace_name = ts.tablespace_name
AND t.tablespace_name = tf.tablespace_name
AND t.tablespace_name = ss.tablespace_name (+)
AND t.tablespace_name = c.tablespace_name (+)
AND t.tablespace_name LIKE '&&tablespace_name'
) c
ORDER BY 1 asc;
UNDEFINE tablespace_name

42
star/tpardef.sql Normal file
View File

@@ -0,0 +1,42 @@
col TABLE_OWNER for a25 heading "Owner"
col TABLE_NAME for a30 heading "Table"
col OWNER for a25 heading "Owner"
col INDEX_NAME for a30 heading "Index"
col INDEX_TYPE for a10 heading "Type"
col PARTITIONED for a3 heading "Par"
col PARTITION_POSITION for 999 heading "P#"
col PARTITION_NAME for a30 heading "Partition"
col SUBPARTITION_NAME for a30 heading "Subpartition"
col PART_HIGHVAL for a32 trunc heading "Partition|high value"
col PART_INTERVAL for a3 heading "Par|Int"
col SUBPART_HIGHVAL for a32 trunc heading "Subpartition|high value"
col SUBPART_INTERVAL for a3 heading "Sub|Int"
col NUM_ROWS heading "Rows"
define v_table_owner=&&1
define v_table_name=&&2
select
par.TABLE_OWNER
,par.TABLE_NAME
,par.PARTITION_POSITION
,par.PARTITION_NAME
,par.NUM_ROWS
,par.HIGH_VALUE PART_HIGHVAL
,par.INTERVAL PART_INTERVAL
,sub.SUBPARTITION_NAME
,sub.NUM_ROWS
,sub.HIGH_VALUE SUBPART_HIGHVAL
,sub.INTERVAL SUBPART_INTERVAL
from
dba_tab_partitions par
left outer join dba_tab_subpartitions sub
on (par.TABLE_OWNER=sub.TABLE_OWNER) and (par.TABLE_NAME=sub.TABLE_NAME) and(par.PARTITION_NAME=sub.PARTITION_NAME)
where
par.table_owner='&&v_table_owner'
and par.table_name='&&v_table_name'
order by
par.PARTITION_POSITION asc
,sub.SUBPARTITION_POSITION asc
;

55
star/tpstat.sql Normal file
View File

@@ -0,0 +1,55 @@
/* Statistics details for table partitions
Usage: @tpstat <owner> <table> <partition>
vplesnila 2024-01-29: creation
*/
col owner for a20 head "Owner"
col table_name for a30 head "Table name"
col PARTITION_NAME for a20 head "Partition name"
col last_DML for a20 head "Last DML"
col last_analyzed for a20 head "Last Analyzed"
col STALE_STATS for a7 head "Stale"
col NUM_ROWS head "#Rows"
col PARTITION_POSITION head "P#" for 999
col INSERTS head "Table|INS"
col UPDATES head "Table|UPD"
col DELETES head "Table|DEL"
col TRUNCATED head "Table|TRUN"
break on report skip 1
compute sum of INSERTS on report
compute sum of UPDATES on report
compute sum of DELETES on report
select
tabstat.OWNER
,tabstat.TABLE_NAME
,tabstat.PARTITION_POSITION
,tabstat.PARTITION_NAME
,tabstat.NUM_ROWS
,tabstat.STALE_STATS
,tabstat.LAST_ANALYZED
,tabmod.INSERTS
,tabmod.UPDATES
,tabmod.DELETES
,tabmod.TRUNCATED
,tabmod.TIMESTAMP last_DML
from
dba_tab_statistics tabstat
,dba_tab_modifications tabmod
WHERE
tabstat.owner = '&&1'
AND tabstat.table_name = '&&2'
AND (tabstat.partition_name like '%&&3%' or tabstat.partition_name is NULL)
AND tabstat.owner = tabmod.table_owner(+)
AND tabstat.table_name = tabmod.table_name(+)
AND tabstat.partition_name = tabmod.partition_name(+)
ORDER BY
tabstat.owner asc,
tabstat.table_name asc,
tabstat.partition_position asc,
tabstat.subpartition_position asc
/

View File

@@ -0,0 +1,135 @@
/*
*
* Author : Vishal Gupta
* Purpose : Displays long running transactions
* Parameter: 1 - Where Clause
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 04-May-15 Vishal Gupta Created
*
*/
/************************************
* INPUT PARAMETERS
************************************/
UNDEFINE WHERE_CLAUSE
DEFINE WHERE_CLAUSE="&&1"
/************************************
* CONFIGURATION PARAMETERS
************************************/
DEFINE BYTES_FORMAT="999,999"
--DEFINE BYTES_DIVIDER="1024"
--DEFINE BYTES_HEADING="KB"
DEFINE BYTES_DIVIDER="1024/1024"
DEFINE BYTES_HEADING="MB"
--DEFINE BYTES_DIVIDER="1024/1024/1024"
--DEFINE BYTES_HEADING="GB"
DEFINE COUNT_FORMAT=999,999
--DEFINE COUNT_DIVIDER="1"
--DEFINE COUNT_HEADING="#"
DEFINE COUNT_DIVIDER="1000"
DEFINE COUNT_HEADING="#1000"
PROMPT
PROMPT *********************************************
PROMPT * D A T A B A S E T R A N S A C T I O N S
PROMPT *********************************************
COLUMN xid HEADING "XID" FORMAT a16
COLUMN sid HEADING "SID" FORMAT 99999
COLUMN inst_id HEADING "I#" FORMAT 99
COLUMN spid HEADING "SPID" FORMAT a6
COLUMN transaction_start_date HEADING "Transaction|StartTime" FORMAT a18
COLUMN tran_duration HEADING "Transaction|Duration" FORMAT a15
COLUMN transaction_status HEADING "Tran|Status" FORMAT a8
COLUMN space HEADING "Space|Tran" FORMAT a5
COLUMN recursive HEADING "Recu|rsive|Tran" FORMAT a5
COLUMN noundo HEADING "No|Undo|Tran" FORMAT a4
COLUMN ptx HEADING "Par'l|Tran" FORMAT a5
COLUMN used_undo HEADING "Undo|(&&BYTES_HEADING)" FORMAT &&BYTES_FORMAT
COLUMN username HEADING "UserName" FORMAT a20
COLUMN osuser HEADING "OS User" FORMAT a15 TRUNCATED
COLUMN status HEADING "Session|Status" FORMAT a8
COLUMN state HEADING "Session|State" FORMAT a12 TRUNCATED
COLUMN logon_time HEADING "Logon Time" FORMAT a18
COLUMN MACHINE HEADING "Machine" FORMAT a20 TRUNCATED
COLUMN process HEADING "Process" FORMAT a11
COLUMN program HEADING "Program" FORMAT a20 TRUNCATED
COLUMN event HEADING "Event" FORMAT a30 TRUNCATED
--COLUMN last_call_et HEADING "LastCall|(sec)" FORMAT 999,999
COLUMN last_call_et HEADING "LastCall" FORMAT a12
COLUMN sql_child_number HEADING "SQL|Child|No" FORMAT 99
COLUMN log_io HEADING "Logical|IO|(&&COUNT_HEADING)" FORMAT &&COUNT_FORMAT
COLUMN phy_io HEADING "Physical|IO|(&&COUNT_HEADING)" FORMAT &&COUNT_FORMAT
COLUMN cr_get HEADING "Consistent|Gets|(&&COUNT_HEADING)" FORMAT &&COUNT_FORMAT
COLUMN locked_mode HEADING "Lock Mode" FORMAT a10
COLUMN object_name HEADING "ObjectName" FORMAT a35
SELECT
-- t.xid xid
--, t.ptx_xid
s.sid sid
, t.inst_id
, p.spid
, s.status
, TO_CHAR(t.start_date,'DD-MON-YY HH24:MI:SS') transaction_start_date
, FLOOR(sysdate - t.start_date) || 'd '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) , 1) * 24 ) ,2) || 'h '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) * 24 , 1) * 60 ) ,2) || 'm '
|| LPAD(FLOOR(MOD((sysdate - t.start_date) * 24 * 60 , 1) * 60 ) ,2) || 's ' tran_duration
, t.status transaction_status
, t.space
, t.recursive
, t.noundo
, t.ptx
, DECODE(lo.locked_mode,
0, 'None', /* Mon Lock equivalent */
1, 'Null', /* N */
2, 'Row-S (SS)', /* L */
3, 'Row-X (SX)', /* R */
4, 'Share', /* S */
5, 'S/Row-X (SSX)', /* C */
6, 'Exclusive', /* X */
TO_CHAR(lo.locked_mode)
) locked_mode
, NVL2(o.owner,o.owner|| '.' || o.object_name || NVL2(o.subobject_name,'(' || o.subobject_name || ')','') , '' ) object_name
, ROUND((t.used_ublk * p.value)/&&BYTES_DIVIDER) used_undo
, t.log_io/&&COUNT_DIVIDER log_io
, t.phy_io/&&COUNT_DIVIDER phy_io
, t.cr_get/&&COUNT_DIVIDER cr_get
, s.username
, s.osuser
-- , s.sql_id
-- , s.sql_child_number
, s.program
FROM gv$transaction t
INNER JOIN gv$session s ON t.inst_id = s.inst_id AND t.ses_addr = s.saddr
INNER JOIN gv$process p ON p.inst_id = s.inst_id AND p.addr = s.paddr
INNER JOIN v$parameter p ON p.name = 'db_block_size'
LEFT OUTER JOIN gv$locked_object lo ON t.inst_id = lo.inst_id
AND s.sid = lo.session_id
AND t.xidusn = lo.xidusn
AND t.xidslot = lo.xidslot
AND t.xidsqn = lo.xidsqn
LEFT OUTER JOIN dba_objects o ON lo.object_id = o.object_id
WHERE 1=1 and 2=2
-- had to put AND clause other when no where clause is passed it was giving following error
-- SP2-0341: line overflow during variable substitution (>3000 characters at line 53)
&&WHERE_CLAUSE
ORDER BY transaction_start_date asc
;

59
star/tspstat.sql Normal file
View File

@@ -0,0 +1,59 @@
/* Statistics details for table partitions/subpartitios
Usage: @tspstat <owner> <table> <partition>
vplesnila 2024-01-29: creation
*/
col owner for a20 head "Owner"
col table_name for a25 head "Table name"
col PARTITION_POSITION for 999 heading "P#"
col PARTITION_NAME for a25 head "Partition name"
col SUBPARTITION_NAME for a25 head "Subpartition name"
col last_DML for a20 head "Last DML"
col last_analyzed for a20 head "Last Analyzed"
col STALE_STATS for a7 head "Stale"
col NUM_ROWS head "#Rows"
col INSERTS head "Table|INS"
col UPDATES head "Table|UPD"
col DELETES head "Table|DEL"
col TRUNCATED head "Table|TRUN"
break on report skip 1
compute sum of INSERTS on report
compute sum of UPDATES on report
compute sum of DELETES on report
select
tabstat.OWNER
,tabstat.TABLE_NAME
,tabstat.PARTITION_POSITION
,tabstat.PARTITION_NAME
,tabstat.SUBPARTITION_NAME
,tabstat.NUM_ROWS
,tabstat.STALE_STATS
,tabstat.LAST_ANALYZED
,tabmod.INSERTS
,tabmod.UPDATES
,tabmod.DELETES
,tabmod.TRUNCATED
,tabmod.TIMESTAMP last_DML
from
dba_tab_statistics tabstat
,dba_tab_modifications tabmod
WHERE
tabstat.owner = '&&1'
AND tabstat.table_name = '&&2'
AND (tabstat.partition_name like '%&&3%' or tabstat.partition_name is NULL)
AND (tabstat.subpartition_name like '%&&4%' or tabstat.subpartition_name is NULL)
AND tabstat.owner = tabmod.table_owner(+)
AND tabstat.table_name = tabmod.table_name(+)
AND tabstat.partition_name = tabmod.partition_name(+)
AND tabstat.subpartition_name = tabmod.subpartition_name(+)
ORDER BY
tabstat.owner asc,
tabstat.table_name asc,
tabstat.partition_position asc,
tabstat.subpartition_position asc
/

61
star/usess.sql Normal file
View File

@@ -0,0 +1,61 @@
/*
based on Jeffrey M. Hunter jhunter@idevelopment.info script / www.idevelopment.info
*/
SET ECHO OFF
SET FEEDBACK 6
SET HEADING ON
SET LINESIZE 256
SET PAGESIZE 50000
SET TERMOUT ON
SET TIMING OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET VERIFY OFF
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
COLUMN inst_id FORMAT 9 HEADING 'I'
COLUMN sid FORMAT 999999 HEADING 'SID'
COLUMN serial_id FORMAT 99999999 HEADING 'Serial#'
COLUMN session_status FORMAT a9 HEADING 'Status'
COLUMN sql_id FORMAT a13 HEADING 'SQL_ID'
COLUMN event FORMAT a30 HEADING 'Event' TRUNC
COLUMN oracle_username FORMAT a15 HEADING 'Oracle User'
COLUMN os_username FORMAT a15 HEADING 'O/S User'
COLUMN os_pid FORMAT a8 HEADING 'O/S PID'
COLUMN session_machine FORMAT a25 HEADING 'Machine' TRUNC
COLUMN session_program FORMAT a40 HEADING 'Session Program' TRUNC
COLUMN module FORMAT a30 HEADING 'Module' TRUNC
COLUMN action FORMAT a30 HEADING 'Action' TRUNC
BREAK ON inst_id SKIP PAGE
SELECT
s.inst_id inst_id
, s.sid sid
, s.serial# serial_id
, s.status session_status
, s.sql_id sql_id
, s.username oracle_username
, s.osuser os_username
, s.machine session_machine
, s.program session_program
, p.spid os_pid
, s.event event
, s.module module
, s.action action
FROM
gv$session s
INNER JOIN gv$process p ON (s.paddr = p.addr AND s.inst_id = p.inst_id)
INNER JOIN gv$instance i ON (p.inst_id = i.inst_id)
WHERE
(&1)
AND s.username IS NOT null
AND s.username not in ('SYS','SYSRAC')
ORDER BY
i.instance_name
, s.sid;

44
star/wrka.sql Normal file
View File

@@ -0,0 +1,44 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
-- Purpose: List ACTIVE SQL workarea memory usage details at session/workarea level.
-- Show both PGA workarea usage and TEMP usage by workareas (workareas don't include
-- other PGA/TEMP use like PL/SQL arrays and global temporary tables)
--
-- Usage: @wrka 1=1
-- @wrka sid=123
-- @wrka username='APPUSER'
-- @wrka "sid IN (123,234,456)"
-- @wrka "program LIKE '%BatchRunner.exe%' AND machine='host123'"
-- @wrka "sid in (SELECT sid FROM v$session WHERE ....)"
prompt Show Active workarea memory usage for where &1....
COL wrka_operation_type HEAD OPERATION_TYPE FOR A30
SELECT
inst_id
, sid
, qcinst_id
, qcsid
, sql_id
-- , sql_exec_start -- 11g+
, operation_type wrka_operation_type
, operation_id plan_line
, policy
, ROUND(active_time/1000000,1) active_sec
, actual_mem_used
, max_mem_used
, work_area_size
, number_passes
, tempseg_size
, tablespace
FROM
gv$sql_workarea_active
WHERE
&1
ORDER BY
sid
, sql_hash_value
, operation_id
/

71
star/wrkasum.sql Normal file
View File

@@ -0,0 +1,71 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
-- Purpose: Show a summary of ACTIVE SQL workareas grouped by operation type (SORT, HASH, etc)
-- Show both PGA workarea usage and TEMP usage by workareas (workareas don't include
-- other PGA/TEMP use like PL/SQL arrays and global temporary tables)
--
-- Usage: @wrkasum 1=1
-- @wrkasum username='APPUSER'
-- @wrkasum "program LIKE '%BatchRunner.exe%' AND machine='host123'"
PROMPT Total PGA allocation from V$PROCESS (excluding MGA)
SELECT
inst_id
, ROUND(SUM(pga_alloc_mem)/1048576,1) total_alloc_pga
, ROUND(SUM(pga_used_mem) /1048576,1) total_used_pga
FROM
gv$process
GROUP BY
inst_id
ORDER BY
inst_id
/
PROMPT Top allocation reason by PGA memory usage
COL wrkasum_operation_type FOR A30
SELECT
operation_type wrkasum_operation_type
, policy
, ROUND(SUM(actual_mem_used)/1048576) actual_pga_mb
, ROUND(SUM(work_area_size)/1048576) allowed_pga_mb
, ROUND(SUM(tempseg_size)/1048576) temp_mb
, MAX(number_passes) num_passes
, COUNT(DISTINCT qcinst_id||','||qcsid) num_qc
, COUNT(DISTINCT inst_id||','||sid) num_sessions
FROM
gv$sql_workarea_active
WHERE
&1
GROUP BY
operation_type
, policy
ORDER BY
actual_pga_mb DESC NULLS LAST
/
PROMPT Top SQL_ID by TEMP usage...
SELECT
sql_id
, policy
, ROUND(SUM(actual_mem_used)/1048576) actual_pga_mb
, ROUND(SUM(work_area_size)/1048576) allowed_pga_mb
, ROUND(SUM(tempseg_size)/1048576) temp_mb
, MAX(number_passes) num_passes
, COUNT(DISTINCT qcinst_id||','||qcsid) num_qc
, COUNT(DISTINCT inst_id||','||sid) num_sessions
FROM
gv$sql_workarea_active
WHERE
&1
GROUP BY
sql_id
, policy
ORDER BY
temp_mb DESC NULLS LAST
/

4
star/xawr.sql Normal file
View File

@@ -0,0 +1,4 @@
-- Copyright 2018 Tanel Poder. All rights reserved. More info at http://tanelpoder.com
-- Licensed under the Apache License, Version 2.0. See LICENSE.txt for terms & conditions.
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR('&1', CASE WHEN '&2' = '%' THEN null ELSE '&2' END, format=>'+PEEKED_BINDS'));

5
star/xlast.sql Normal file
View File

@@ -0,0 +1,5 @@
prompt Display execution plan for last statement for this session from library cache...
select * from table(dbms_xplan.display_cursor(null,null,'ALLSTATS LAST +ALIAS +PEEKED_BINDS +PARALLEL +PARTITION +COST +BYTES +HINT_REPORT'));

48
star/xplan.sql Normal file
View File

@@ -0,0 +1,48 @@
/*
*
* Author : Vishal Gupta
* Purpose : Display Execution plan from cursor cache
* Parameters : 1 - SQL_ID
*
*
* Revision History:
* ===================
* Date Author Description
* --------- ------------ -----------------------------------------
* 18-Mar-12 Vishal Gupta Intial version
*
*
*/
DEFINE sql_id="&&1"
DEFINE child_number="&&2"
COLUMN _sql_id NEW_VALUE sql_id NOPRINT
COLUMN _child_number NEW_VALUE child_number NOPRINT
SELECT DECODE('&&sql_id','','%','&&sql_id') "_sql_id"
, DECODE('&&child_number','','NULL','&&child_number') "_child_number"
FROM DUAL
;
SET long 4000
SET longchunksize 4000
SET pagesize 0
SELECT *
FROM table(DBMS_XPLAN.display_cursor( sql_id => '&&sql_id'
, cursor_child_no => &&child_number
, format => 'ADVANCED ALLSTATS LAST'
)
)
;
UNDEFINE sql_id
UNDEFINE child_number