Script:列出本会话的细节信息

以下脚本可以用于列出本会话(local session)的sid、pid、spid、trace 路径等有用信息; 因为不依赖于dbms_session等包体,所以仅需要select_catalog_role的角色即可执行,更为灵活。

 

 

set serveroutput on
set linesize 200 pagesize 1400
set time on
declare
  l_audsid number;
  l_sid    number;
  l_serial number;
  l_module varchar2(128);
  l_pid    number;
  l_spid   number;
  l_trace  varchar2(2000);
  l_user   varchar2(128);
begin
  DBMS_APPLICATION_INFO.SET_MODULE(module_name => 'Maclean Liu OppO',
                                   action_name => 'ACTIVE');
  select audsid, sid, SERIAL#, module,username
    into l_audsid, l_sid, l_serial, l_module,l_user
    from v$session
   where sid = (select distinct sid from v$mystat);
  select pid, spid
    into l_pid, l_spid
    from v$process
   where addr = (select paddr
                   from v$session
                  where sid = l_sid
                    and serial# = l_serial);
  SELECT d.VALUE || '/' || LOWER(RTRIM(i.INSTANCE, CHR(0))) || '_ora_' ||
         p.spid || '.trc'
    into l_trace
    FROM (SELECT p.spid
            FROM v$mystat m, v$session s, v$process p
           WHERE m.statistic# = 1
             AND s.SID = m.SID
             AND p.addr = s.paddr) p,
         (SELECT t.INSTANCE
            FROM v$thread t, v$parameter v
           WHERE v.NAME = 'thread'
             AND (v.VALUE = 0 OR t.thread# = TO_NUMBER(v.VALUE))) i,
         (SELECT VALUE FROM v$parameter WHERE NAME = 'user_dump_dest') d;

  dbms_output.enable(9999999);
  dbms_output.put_line('===============================================');
  dbms_output.put_line(' USERNAME=' || l_user);
  dbms_output.put_line(' SESSION ID=' || l_sid || '  SERIAL#=' || l_serial);
  dbms_output.put_line(' AUDSID=' || l_audsid || '      MODULE#=' ||
                       l_module);
  dbms_output.put_line(' PID=' || l_pid || '          SPID#=' || l_spid);
  dbms_output.put_line(' TRACE_FILE_LOCATION=' || l_trace);
  dbms_output.put_line('===============================================');
  commit;
end;
/

Script:计算Oracle Streams进程所占用的内存大小

以下脚本可以用于收集Oracle Streams进程的内存使用信息, 便于诊断因memory leak引起的内存问题:

 

ps auxgw | sort  -n +5 | tail -10

select a.apply_name,
       a.server_id,
       b.sid,
       b.program,
       c.spid,
       trunc(c.pga_used_mem / (1024 * 1024), 2) PGA_USED,
       trunc(c.pga_alloc_mem / (1024 * 1024), 2) PGA_ALLOC,
       trunc(c.pga_freeable_mem / (1024 * 1024), 2) PGA_FREE,
       trunc(c.pga_max_mem / (1024 * 1024), 2) PGA_MAX
  from v$streams_apply_server a, v$process c, v$session b
 where a.sid = b.sid
   and b.paddr = c.addr
 order by 1, 2;

SELECT p.spid spid,
       'C00' || c.capture# || ' ' || upper(lp.role) as process,
       c.capture_name "Capture Name",
       s.sid,
       s.program,
       trunc(p.pga_used_mem / (1024 * 1024), 2) PGA_USED,
       trunc(p.pga_alloc_mem / (1024 * 1024), 2) PGA_ALLOC,
       trunc(p.pga_freeable_mem / (1024 * 1024), 2) PGA_FREE,
       trunc(p.pga_max_mem / (1024 * 1024), 2) PGA_MAX
  FROM v$streams_capture c, v$logmnr_process lp, v$session s, v$process p
 WHERE c.logminer_id = lp.session_id
   AND lp.role in ('reader', 'preparer', 'builder')
   AND lp.sid = s.sid
   AND lp.serial# = s.serial#
   AND s.paddr = p.addr
 order by capture_name, process;

sqlplus / as sysdba
oradebug setospid $PID
oradebug unlimit
oradebug dump heapdump 536870917
oradebug tracefile_name

Script:利用外部表实现SQL查询Oracle告警日志Alert.log

有同学问是否可以用SQL语句直接查询告警日志的内容,即创建一张包含Alert.log内容的表或视图。 实际上之前已经有人这样做了(http://t.cn/SwGvq9),只需要运行一个存储过程即可达到目的, 这里我对原有的语句做了一些改良, 直接执行PL/SQL块即可无需创建存储过程了,而且现在支持RAC了。

 

--drop table alert_log_view;
--drop directory bdump;

declare
  path_bdump varchar2(4000);
  name_alert varchar2(4000);
  ins_name   varchar2(200);
begin

  select value
    into path_bdump
    from sys.v_$parameter
   where name = 'background_dump_dest';
  select 'alert_' || value || '.log'
    into name_alert
    from sys.v_$parameter
   where name = 'instance_name';

  select value
    into ins_name
    from sys.v_$parameter
   where name = 'instance_number';

  if ins_name = '0' then
    ins_name := '';
  end if;

  execute immediate 'create or replace directory bdump'||ins_name||' as ''' || path_bdump || '''';
  execute immediate 'create table ALERT_LOG_VIEW' || ins_name ||
                    '  (MSG_line varchar2(4000)   ) ' ||
                    ' organization external ' || ' (type oracle_loader ' ||
                    ' default directory bdump' || ins_name ||
                    ' access parameters ( ' ||
                    ' records delimited by newline ' || ' nobadfile ' ||
                    ' nologfile ' || ' nodiscardfile ' || ' skip 0 ' ||
                    ' READSIZE 10485760 ' || ' FIELDS LDRTRIM ' ||
                    ' REJECT ROWS WITH ALL NULL FIELDS ' ||
                    ' (MSG_LINE (1:1000) CHAR(1000)) ' || ' ) ' ||
                    ' location (''' || name_alert || ''') )' ||
                    ' reject limit unlimited ' ||
                    ' noparallel nomonitoring ';

end;
/

 

执行以上PL/SQL代码,会创建名为bdump$SID的目录 和ALERT_LOG_VIEW$SID的外部表(如RAC中的1号实例PROD1,则为ALERT_LOG_VIEW1,单实例single instance则为 ALERT_LOG_VIEW), 需要时直接查询ALERT_LOG_VIEW即可,譬如要从告警信息中找出最近三天ORA-错误的记录:

 

col lineno noprint
col ora_error noprint
col msg_line format a132
set pages 0 lines 300 trimspool on trim on
alter session set nls_date_language = 'american';
alter session set nls_date_format='dd/mm/yyyy hh24:mi:ss';
alter session set sql_trace=false;
break on thedate
prompt
prompt ERROR IN ALERT LOG FILE - LAST 3 DAYS
prompt =====================================
select "LINENO", "THEDATE", "ORA_ERROR", "MSG_LINE"
  from (select *
          from (select lineno,
                       msg_line,
                       thedate,
                       max(case
                             when (ora_error like 'ORA-%' or
                                  ora_error like 'PLS-%') then
                              rtrim(substr(ora_error, 1, instr(ora_error, ' ') - 1),
                                    ':')
                             else
                              null
                           end) over(partition by thedate) ora_error
                  from (select lineno,
                               msg_line,
                               max(thedate) over(order by lineno) thedate,
                               lead(msg_line) over(order by lineno) ora_error
                          from (select rownum lineno,
                                       substr(msg_line, 1, 132) msg_line,
                                       case
                                         when msg_line like
                                              '___ ___ __ __:__:__ ____' then
                                          to_date(msg_line,
                                                  'Dy Mon DD hh24:mi:ss yyyy')
                                         else
                                          null
                                       end thedate
                                  from ALERT_LOG_VIEW))))
 where ora_error is not null
   and thedate >= (trunc(sysdate) - 3)
 order by thedate

示例输出

10/11/2011 03:15:49 Thu Nov 10 03:15:49 2011
                    Errors in file /s01/orabase/diag/rdbms/vprod/VPROD1/trace/VPROD1_ora_5547.trc  (incident=11105):
                    ORA-00700: soft internal error, arguments: [kgerev1], [600], [600], [700], [], [], [], [], [], [], [], []
                    Incident details in: /s01/orabase/diag/rdbms/vprod/VPROD1/incident/incdir_11105/VPROD1_ora_5547_i11105.trc
                    Errors in file /s01/orabase/diag/rdbms/vprod/VPROD1/trace/VPROD1_ora_5547.trc  (incident=11106):
                    ORA-00600: internal error code, arguments: [], [], [], [], [], [], [], [], [], [], [], []
                    Incident details in: /s01/orabase/diag/rdbms/vprod/VPROD1/incident/incdir_11106/VPROD1_ora_5547_i11106.trc
10/11/2011 03:15:52 Thu Nov 10 03:15:52 2011
                    Dumping diagnostic data in directory=[cdmp_20111110031552], requested by (instance=1, osid=5547), summary=[incident=11105].

Script: 收集RAC DRM 诊断信息

以下脚本可以用于收集 11gR2中 RAC DRM 动态资源管理 特性的诊断信息:

 

REM for 11.2 only
REM written by Maclean.Liu

set linesize 140 pagesize 1400

select DRMS, AVG_DRM_TIME, QUIESCE_T,FRZ_T,CLEANUP_T,REPLAY_T,FIXWRITE_T,SYNC_T from X$KJDRMAFNSTATS
/

select * from GV$DYNAMIC_REMASTER_STATS
/

select object, node, sopens, xopens, xfers
from x$object_policy_statistics
-- where object=&object_id
/

select data_object_id, current_master, previous_master, remaster_cnt from gv$gcspfmaster_info
/

select * from gv$policy_history
-- where object=&object_id
order by EVENT_DATE
/

select name, value
from v$sysstat
where name in ('gc local grants',
'gc remote grants')
/

Script:10g中不用EM显示Active Session Count by Wait Class

<11g中AWR新快照视图>一文中我介绍了作为新特性加入11g的一些动态性能视图,另外也提及了通过一个SQL脚本就可以不打开EM界面而显示ASH的按等待类型(Wait Class)累计的Active Session Count,实际在EM中图形化的效果是这样的:

 

 

在11g 中可以使用如下SQL从命令行获得实例每分钟的AAS信息(注意没有对后台进程做过滤,所以是Foreground + Background 的模式):

 

set echo off;
set verify off;
alter session set nls_date_format='HH24:MI';
select *
  from (select nvl(wait_class, 'CPU') activity,
               trunc(sample_time, 'MI') time
          from v$active_session_history) v pivot(count(*) for activity in('CPU' as
                                                                          "CPU",
                                                                          'Concurrency' as
                                                                          "Concurrency",
                                                                          'System I/O' as
                                                                          "System I/O",
                                                                          'User I/O' as
                                                                          "User I/O",
                                                                          'Administrative' as
                                                                          "Administrative",
                                                                          'Configuration' as
                                                                          "Configuration",
                                                                          'Application' as
                                                                          "Application",
                                                                          'Network' as
                                                                          "Network",
                                                                          'Commit' as
                                                                          "Commit",
                                                                          'Scheduler' as
                                                                          "Scheduler",
                                                                          'Cluster' as
                                                                          "Cluster",
                                                                          'Queueing' as
                                                                          "Queueing",
                                                                          'Other' as
                                                                          "Other"))
 where time > sysdate - interval '&last_min' minute
 order by time;

 

因为以上这段SQL脚本使用了11g 才引入的pivot函数,所以在10g 中是无法运行的。Google 了以下似乎没有可用的10g版本(大约化了一个小时),寻思着还是自己给改以下吧,结果5分钟搞定。。

现在共享出来给经常不能使用EM的乙方同学(Foreground only 和 Foreground + background 2种模式都有):

 

REM created by Maclean Liu
REM www.askmac.cn & www.askmac.cn
REM released 2011-10-27 Version 1.0

REM Foreground + Background mode

set echo off;
set verify off;
alter session set nls_date_format='HH24:MI';

select time,
       sum(case activity
             when 'CPU' then
              1
             else
              0
           end) CPU,
       sum(case activity
             when 'Concurrency' then
              1
             else
              0
           end) Concurrency,
       sum(case activity
             when 'System I/O' then
              1
             else
              0
           end) "System I/O",
       sum(case activity
             when 'User I/O' then
              1
             else
              0
           end) "User I/O",
       sum(case activity
             when 'Administrative' then
              1
             else
              0
           end) "Administrative",
       sum(case activity
             when 'Configuration' then
              1
             else
              0
           end) "Configuration",
       sum(case activity
             when 'Application' then
              1
             else
              0
           end) "Application",
       sum(case activity
             when 'Network' then
              1
             else
              0
           end) "Network",
       sum(case activity
             when 'Commit' then
              1
             else
              0
           end) "Commit",
       sum(case activity
             when 'Scheduler' then
              1
             else
              0
           end) "Scheduler",
       sum(case activity
             when 'Cluster' then
              1
             else
              0
           end) "Cluster",
       sum(case activity
             when 'Queueing' then
              1
             else
              0
           end) "Queueing",
       sum(case activity
             when 'Other' then
              1
             else
              0
           end) "Other"
  from (select trunc(sample_time, 'MI') time,
               nvl(wait_class, 'CPU') activity
          from v$active_session_history)
 where time > sysdate - interval '&last_min' minute
 group by time
 order by time;

REM Foreground  mode

set echo off;
set verify off;
alter session set nls_date_format='HH24:MI';
select time,
       sum(case activity
             when 'CPU' then
              1
             else
              0
           end) CPU,
       sum(case activity
             when 'Concurrency' then
              1
             else
              0
           end) Concurrency,
       sum(case activity
             when 'System I/O' then
              1
             else
              0
           end) "System I/O",
       sum(case activity
             when 'User I/O' then
              1
             else
              0
           end) "User I/O",
       sum(case activity
             when 'Administrative' then
              1
             else
              0
           end) "Administrative",
       sum(case activity
             when 'Configuration' then
              1
             else
              0
           end) "Configuration",
       sum(case activity
             when 'Application' then
              1
             else
              0
           end) "Application",
       sum(case activity
             when 'Network' then
              1
             else
              0
           end) "Network",
       sum(case activity
             when 'Commit' then
              1
             else
              0
           end) "Commit",
       sum(case activity
             when 'Scheduler' then
              1
             else
              0
           end) "Scheduler",
       sum(case activity
             when 'Cluster' then
              1
             else
              0
           end) "Cluster",
       sum(case activity
             when 'Queueing' then
              1
             else
              0
           end) "Queueing",
       sum(case activity
             when 'Other' then
              1
             else
              0
           end) "Other"
  from (select trunc(sample_time, 'MI') time,
               nvl(wait_class, 'CPU') activity
          from v$active_session_history
         where session_type = 'FOREGROUND')
 where time > sysdate - interval '&last_min' minute
 group by time
 order by time;

 

使用方法如下:

 

SQL> @ashwc

Session altered.

Enter value for last_min: 10

TIME         CPU CONCURRENCY System I/O   User I/O Administrative Configuration
----- ---------- ----------- ---------- ---------- -------------- -------------
Application    Network     Commit  Scheduler    Cluster   Queueing      Other
----------- ---------- ---------- ---------- ---------- ---------- ----------
20:40          1           0          0          0              0             0
          0          0          0          0          0          0          0

Script:数据库最近的性能度量

以下SQL脚本可以用于列出数据库最近1分钟的性能度量信息(performance metric):

set linesize 80 pagesize 1400


SELECT /*+ ORDERED USE_MERGE(m) */
 TO_CHAR(FROM_TZ(CAST(m.end_time AS TIMESTAMP),
                 TO_CHAR(systimestamp, 'tzr')) AT TIME ZONE sessiontimezone,
         'YYYY-MM-DD HH24:MI:SS'),
 SUM(CASE
       WHEN a.internal_metric_name = 'transactions_ps' THEN
        m.value
       ELSE
        0
     END) transactions_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreads_ps' THEN
        m.value
       ELSE
        0
     END) physreads_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreads_pt' THEN
        m.value
       ELSE
        0
     END) physreads_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwrites_ps' THEN
        m.value
       ELSE
        0
     END) physwrites_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwrites_pt' THEN
        m.value
       ELSE
        0
     END) physwrites_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreadsdir_ps' THEN
        m.value
       ELSE
        0
     END) physreadsdir_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreadsdir_pt' THEN
        m.value
       ELSE
        0
     END) physreadsdir_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwritesdir_ps' THEN
        m.value
       ELSE
        0
     END) physwritesdir_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwritesdir_pt' THEN
        m.value
       ELSE
        0
     END) physwritesdir_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreadslob_ps' THEN
        m.value
       ELSE
        0
     END) physreadslob_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physreadslob_pt' THEN
        m.value
       ELSE
        0
     END) physreadslob_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwriteslob_ps' THEN
        m.value
       ELSE
        0
     END) physwriteslob_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'physwriteslob_pt' THEN
        m.value
       ELSE
        0
     END) physwriteslob_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'redosize_ps' THEN
        m.value
       ELSE
        0
     END) redosize_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'logons_ps' THEN
        m.value
       ELSE
        0
     END) logons_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'logons_pt' THEN
        m.value
       ELSE
        0
     END) logons_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'opncurs_ps' THEN
        m.value
       ELSE
        0
     END) opncurs_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'opncurs_pt' THEN
        m.value
       ELSE
        0
     END) opncurs_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'commits_ps' THEN
        m.value
       ELSE
        0
     END) commits_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'commits_pt' THEN
        m.value
       ELSE
        0
     END) commits_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'rollbacks_ps' THEN
        m.value
       ELSE
        0
     END) rollbacks_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'rollbacks_pt' THEN
        m.value
       ELSE
        0
     END) rollbacks_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'usercalls_ps' THEN
        m.value
       ELSE
        0
     END) usercalls_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'usercalls_pt' THEN
        m.value
       ELSE
        0
     END) usercalls_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'recurscalls_ps' THEN
        m.value
       ELSE
        0
     END) recurscalls_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'recurscalls_pt' THEN
        m.value
       ELSE
        0
     END) recurscalls_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'logreads_ps' THEN
        m.value
       ELSE
        0
     END) logreads_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'logreads_pt' THEN
        m.value
       ELSE
        0
     END) logreads_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbwrcheckpoints_ps' THEN
        m.value
       ELSE
        0
     END) dbwrcheckpoints_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'bgcheckpoints_ps' THEN
        m.value
       ELSE
        0
     END) bgcheckpoints_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'redowrites_ps' THEN
        m.value
       ELSE
        0
     END) redowrites_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'redowrites_pt' THEN
        m.value
       ELSE
        0
     END) redowrites_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'tabscanslong_ps' THEN
        m.value
       ELSE
        0
     END) tabscanslong_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'tabscanslong_pt' THEN
        m.value
       ELSE
        0
     END) tabscanslong_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'tabscanstotal_ps' THEN
        m.value
       ELSE
        0
     END) tabscanstotal_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'tabscanstotal_pt' THEN
        m.value
       ELSE
        0
     END) tabscanstotal_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'indxscansfull_pt' THEN
        m.value
       ELSE
        0
     END) indxscansfull_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'indxscansfull_ps' THEN
        m.value
       ELSE
        0
     END) indxscansfull_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'indxscanstotal_ps' THEN
        m.value
       ELSE
        0
     END) indxscanstotal_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'indxscanstotal_pt' THEN
        m.value
       ELSE
        0
     END) indxscanstotal_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'parses_ps' THEN
        m.value
       ELSE
        0
     END) parses_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'parses_pt' THEN
        m.value
       ELSE
        0
     END) parses_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'hardparses_ps' THEN
        m.value
       ELSE
        0
     END) hardparses_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'hardparses_pt' THEN
        m.value
       ELSE
        0
     END) hardparses_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'failedparses_ps' THEN
        m.value
       ELSE
        0
     END) failedparses_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'failedparses_pt' THEN
        m.value
       ELSE
        0
     END) failedparses_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'executions_ps' THEN
        m.value
       ELSE
        0
     END) executions_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'sortsdisk_ps' THEN
        m.value
       ELSE
        0
     END) sortsdisk_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'sortsdisk_pt' THEN
        m.value
       ELSE
        0
     END) sortsdisk_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'rows_psort' THEN
        m.value
       ELSE
        0
     END) rows_psort,
 SUM(CASE
       WHEN a.internal_metric_name = 'executeswoparse_pct' THEN
        m.value
       ELSE
        0
     END) executeswoparse_pct,
 SUM(CASE
       WHEN a.internal_metric_name = 'softparse_pct' THEN
        m.value
       ELSE
        0
     END) softparse_pct,
 SUM(CASE
       WHEN a.internal_metric_name = 'usercall_pct' THEN
        m.value
       ELSE
        0
     END) usercall_pct,
 SUM(CASE
       WHEN a.internal_metric_name = 'networkbytes_ps' THEN
        m.value
       ELSE
        0
     END) networkbytes_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqtimeouts_ps' THEN
        m.value
       ELSE
        0
     END) enqtimeouts_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqtimeouts_pt' THEN
        m.value
       ELSE
        0
     END) enqtimeouts_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqwaits_ps' THEN
        m.value
       ELSE
        0
     END) enqwaits_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqwaits_pt' THEN
        m.value
       ELSE
        0
     END) enqwaits_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqdeadlocks_ps' THEN
        m.value
       ELSE
        0
     END) enqdeadlocks_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqdeadlocks_pt' THEN
        m.value
       ELSE
        0
     END) enqdeadlocks_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqreqs_ps' THEN
        m.value
       ELSE
        0
     END) enqreqs_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'enqreqs_pt' THEN
        m.value
       ELSE
        0
     END) enqreqs_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbblkgets_ps' THEN
        m.value
       ELSE
        0
     END) dbblkgets_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbblkgets_pt' THEN
        m.value
       ELSE
        0
     END) dbblkgets_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'consistentreadgets_ps' THEN
        m.value
       ELSE
        0
     END) consistentreadgets_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'consistentreadgets_pt' THEN
        m.value
       ELSE
        0
     END) consistentreadgets_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbblkchanges_ps' THEN
        m.value
       ELSE
        0
     END) dbblkchanges_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbblkchanges_pt' THEN
        m.value
       ELSE
        0
     END) dbblkchanges_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'consistentreadchanges_ps' THEN
        m.value
       ELSE
        0
     END) consistentreadchanges_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'consistentreadchanges_pt' THEN
        m.value
       ELSE
        0
     END) consistentreadchanges_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'crblks_ps' THEN
        m.value
       ELSE
        0
     END) crblks_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'crblks_pt' THEN
        m.value
       ELSE
        0
     END) crblks_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'crundorecs_pt' THEN
        m.value
       ELSE
        0
     END) crundorecs_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'userrollbackundorec_ps' THEN
        m.value
       ELSE
        0
     END) userrollbackundorec_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'userrollbackundorec_pt' THEN
        m.value
       ELSE
        0
     END) userrollbackundorec_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'leafnodesplits_ps' THEN
        m.value
       ELSE
        0
     END) leafnodesplits_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'leafnodesplits_pt' THEN
        m.value
       ELSE
        0
     END) leafnodesplits_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'branchnodesplits_ps' THEN
        m.value
       ELSE
        0
     END) branchnodesplits_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'branchnodesplits_pt' THEN
        m.value
       ELSE
        0
     END) branchnodesplits_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'redosize_pt' THEN
        m.value
       ELSE
        0
     END) redosize_pt,
 SUM(CASE
       WHEN a.internal_metric_name = 'crundorecs_ps' THEN
        m.value
       ELSE
        0
     END) crundorecs_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'dbtime_ps' THEN
        m.value
       ELSE
        0
     END) dbtime_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'avg_active_sessions' THEN
        m.value
       ELSE
        0
     END) avg_active_sessions,
 SUM(CASE
       WHEN a.internal_metric_name = 'avg_sync_singleblk_read_latency' THEN
        m.value
       ELSE
        0
     END) avg_block_read_latency,
 SUM(CASE
       WHEN a.internal_metric_name = 'iombs_ps' THEN
        m.value
       ELSE
        0
     END) iombs_ps,
 SUM(CASE
       WHEN a.internal_metric_name = 'iorequests_ps' THEN
        m.value
       ELSE
        0
     END) iorequests_ps
  FROM v$alert_types a, v$threshold_types t, v$sysmetric m
 WHERE a.internal_metric_category = 'instance_throughput'
   AND a.reason_id = t.alert_reason_id
   AND t.metrics_id = m.metric_id
   AND m.group_id = 2
   AND m.end_time <= SYSDATE
 GROUP BY m.end_time
 ORDER BY m.end_time ASC
/

使用方法:


SQL> @metric

TO_CHAR(FROM_TZ(CAS TRANSACTIONS_PS PHYSREADS_PS PHYSREADS_PT PHYSWRITES_PS
------------------- --------------- ------------ ------------ -------------
PHYSWRITES_PT PHYSREADSDIR_PS PHYSREADSDIR_PT PHYSWRITESDIR_PS PHYSWRITESDIR_PT
------------- --------------- --------------- ---------------- ----------------
PHYSREADSLOB_PS PHYSREADSLOB_PT PHYSWRITESLOB_PS PHYSWRITESLOB_PT REDOSIZE_PS
--------------- --------------- ---------------- ---------------- -----------
 LOGONS_PS  LOGONS_PT OPNCURS_PS OPNCURS_PT COMMITS_PS COMMITS_PT ROLLBACKS_PS
---------- ---------- ---------- ---------- ---------- ---------- ------------
ROLLBACKS_PT USERCALLS_PS USERCALLS_PT RECURSCALLS_PS RECURSCALLS_PT LOGREADS_PS
------------ ------------ ------------ -------------- -------------- -----------
LOGREADS_PT DBWRCHECKPOINTS_PS BGCHECKPOINTS_PS REDOWRITES_PS REDOWRITES_PT
----------- ------------------ ---------------- ------------- -------------
TABSCANSLONG_PS TABSCANSLONG_PT TABSCANSTOTAL_PS TABSCANSTOTAL_PT
--------------- --------------- ---------------- ----------------
INDXSCANSFULL_PT INDXSCANSFULL_PS INDXSCANSTOTAL_PS INDXSCANSTOTAL_PT  PARSES_PS
---------------- ---------------- ----------------- ----------------- ----------
 PARSES_PT HARDPARSES_PS HARDPARSES_PT FAILEDPARSES_PS FAILEDPARSES_PT
---------- ------------- ------------- --------------- ---------------
EXECUTIONS_PS SORTSDISK_PS SORTSDISK_PT ROWS_PSORT EXECUTESWOPARSE_PCT
------------- ------------ ------------ ---------- -------------------
SOFTPARSE_PCT USERCALL_PCT NETWORKBYTES_PS ENQTIMEOUTS_PS ENQTIMEOUTS_PT
------------- ------------ --------------- -------------- --------------
ENQWAITS_PS ENQWAITS_PT ENQDEADLOCKS_PS ENQDEADLOCKS_PT ENQREQS_PS ENQREQS_PT
----------- ----------- --------------- --------------- ---------- ----------
DBBLKGETS_PS DBBLKGETS_PT CONSISTENTREADGETS_PS CONSISTENTREADGETS_PT
------------ ------------ --------------------- ---------------------
DBBLKCHANGES_PS DBBLKCHANGES_PT CONSISTENTREADCHANGES_PS
--------------- --------------- ------------------------
CONSISTENTREADCHANGES_PT  CRBLKS_PS  CRBLKS_PT CRUNDORECS_PT
------------------------ ---------- ---------- -------------
USERROLLBACKUNDOREC_PS USERROLLBACKUNDOREC_PT LEAFNODESPLITS_PS
---------------------- ---------------------- -----------------
LEAFNODESPLITS_PT BRANCHNODESPLITS_PS BRANCHNODESPLITS_PT REDOSIZE_PT
----------------- ------------------- ------------------- -----------
CRUNDORECS_PS  DBTIME_PS AVG_ACTIVE_SESSIONS AVG_BLOCK_READ_LATENCY   IOMBS_PS
------------- ---------- ------------------- ---------------------- ----------
IOREQUESTS_PS
-------------
2011-10-27 20:02:23      .349533955   2.69640479   7.71428571    .116511318
   .333333333      .199733688      .571428571       .116511318       .333333333
     .116511318      .333333333       .116511318       .333333333  16212.0506
.016644474 .047619048 19.0745672 54.5714286 .349533955        100            0
           0   .349533955            1     81.1917443     232.285714   130.54261
  373.47619                  0                0    .515978695    1.47619048
              0               0       .216378162       .619047619
               0                0        19.4573901        55.6666667 4.92676431
14.0952381    1.89747004    5.42857143               0               0
   20.4560586            0            0  22.026087          75.9153784
   61.4864865    .42865891      995.838881              0              0
          0           0               0               0  8.9713715 25.6666667
  44.9400799   128.571429              85.60253            244.904762
     45.1398136      129.142857               .249667111
              .714285714          0          0             0
                     0                      0        .199733688
       .571428571                   0                   0  46381.9048
            0 .023586884          .000235869             .032960413 3.09587217
   195.489348

PS Per Second
PT Per Transaction

Script:收集数据库中用户的角色和表空间等信息

以下脚本可以用于收集数据库中用户的角色和表空间等信息(user_role_tbs.sql):

 

SET pagesize 50  linesize 115
REM
COLUMN username                 format a10 heading User
COLUMN default_tablespace       format a12 heading Default
COLUMN temporary_tablespace     format a12 heading Temporary
COLUMN granted_role             format a25 heading Roles
COLUMN default_role             format a10 heading Default?
COLUMN admin_option             format a7  heading Admin?
COLUMN profile                  format a12 heading Profile
REM
BREAK on username skip 1 on account_status on default_tablespace on temporary_tablespace on profile
REM
SELECT username,
       default_tablespace,
       temporary_tablespace,
       profile,
       granted_role,
       admin_option,
       default_role
  FROM sys.dba_users a, sys.dba_role_privs b
 WHERE a.username = b.grantee
 ORDER BY username,
          default_tablespace,
          temporary_tablespace,
          profile,
          granted_role;
REM
SET termout on flush on feedback on verify on
CLEAR columns
CLEAR breaks

 

Sample Output:

 

User       Default      Temporary    Profile      Roles                     Admin?  Default?
---------- ------------ ------------ ------------ ------------------------- ------- ----------
SCOTT      USERS        TEMP         DEFAULT      CONNECT                   NO      YES
                                                  RESOURCE                  NO      YES
SYS        SYSTEM       TEMP         DEFAULT      AQ_ADMINISTRATOR_ROLE     YES     YES
                                                  AQ_USER_ROLE              YES     YES
                                                  CONNECT                   YES     YES
                                                  DBA                       YES     YES
                                                  DELETE_CATALOG_ROLE       YES     YES
                                                  EXECUTE_CATALOG_ROLE      YES     YES
                                                  EXP_FULL_DATABASE         YES     YES
                                                  HS_ADMIN_ROLE             YES     YES
                                                  IMP_FULL_DATABASE         YES     YES
                                                  OEM_MONITOR               YES     YES
                                                  RECOVERY_CATALOG_OWNER    YES     YES
                                                  RESOURCE                  YES     YES
                                                  SELECT_CATALOG_ROLE       YES     YES

SYSTEM     SYSTEM       TEMP         DEFAULT      AQ_ADMINISTRATOR_ROLE     YES     YES
                                                  DBA                       YES     YES

Script:收集介质恢复诊断信息

以下脚本可以用于收集介质恢复诊断信息(recovery_info.sql):


--- begin [recovery_info.sql] ---
define spoolfile = &1
spool &spoolfile
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
alter session set timed_statistics = true;
alter session set max_dump_file_size = UNLIMITED;
set feedback on
set term on
set wrap on
set trimspool on
set pagesize 1000
set linesize 100
set numwidth 10
select to_char(sysdate) start_time from dual;
column host_name format a20 tru
select instance_name, host_name, version, status, startup_time from v$instance;
set echo on
select * from v$database;
select * from v$controlfile;
select * from v$tablespace;
select * from v$datafile;
select * from v$datafile_header;
select * from v$tempfile;
select * from v$thread;
select * from v$log;
select * from v$logfile;
select * from v$archived_log;
alter session set events 'immediate trace name file_hdrs level 3';
alter session set events 'immediate trace name redohdr level 3';
set echo off
Prompt;
Prompt Output file name is:;
define spoolfile
Prompt;
Prompt ALERT.LOG and TRACE FILES are located in:;
column host_name format a12 tru
column name format a20 tru
column value format a60 tru
select distinct i.host_name, p.name, p.value from v$instance i, v$parameter p
 where p.name like '%_dump_dest'
   and p.name != 'core_dump_dest';
select to_char(sysdate) end_time from dual;
spool off
exit
--- end [recovery_info.sql] ---

脚本:Segment Space Usage Explorer

Script:以下脚本可以用于诊断segement space usage问题:

set serveroutput on;

      declare
        v_unformatted_blocks number;
        v_unformatted_bytes number;
        v_fs1_blocks number;
        v_fs1_bytes number;
        v_fs2_blocks number;
        v_fs2_bytes number;
        v_fs3_blocks number;
        v_fs3_bytes number;
       v_fs4_blocks number;
       v_fs4_bytes number;
       v_full_blocks number;
       v_full_bytes number;
     begin
     dbms_space.space_usage ('&OWNER', '&TABNAME', 'TABLE', v_unformatted_blocks,
     v_unformatted_bytes, v_fs1_blocks, v_fs1_bytes, v_fs2_blocks, v_fs2_bytes,
     v_fs3_blocks, v_fs3_bytes, v_fs4_blocks, v_fs4_bytes, v_full_blocks, v_full_bytes);
     dbms_output.put_line('Unformatted Blocks = '||v_unformatted_blocks);
     dbms_output.put_line('FS1 Blocks              = '||v_fs1_blocks);
     dbms_output.put_line('FS2 Blocks              = '||v_fs2_blocks);
     dbms_output.put_line('FS3 Blocks              = '||v_fs3_blocks);
     dbms_output.put_line('FS4 Blocks              = '||v_fs4_blocks);
     dbms_output.put_line('Full Blocks              = '||v_full_blocks);
     end;
     / 

SELECT TABLE_NAME ,  (BLOCKS *8192 / 1024/1024 ) - (NUM_ROWS*AVG_ROW_LEN/1024/1024)
"Data lower than HWM in MB"   FROM  DBA_TABLES WHERE  UPPER(owner) =UPPER('&OWNER') order by 2 desc;

 select tablespace_name, allocated_space, reclaimable_space from table(dbms_space.asa_recommendations('TRUE', 'TRUE', 'ALL'))

Script:收集Flashback Database Log诊断信息

以下脚本可以用于收集10g以后的闪回数据库日志Flashback Database Log的诊断信息:

WITH flashback_database_log AS
 (SELECT ROUND((SYSDATE - oldest_flashback_time) * 24 * 60, 2) oldest_log_minutes,
         retention_target retention_target_minutes,
         flashback_size / 1048576 flashback_size_mb,
         estimated_flashback_size / 1048576 estimated_flashback_size_mb
    FROM v$flashback_database_log),
flashback_database_logfile AS
 (SELECT COUNT(*) logs,
         SUM(BYTES / 1048576) size_mb,
         MIN(first_time) oldest_log,
         MAX(first_time) latest_log
    FROM v$flashback_database_logfile),
flashback_usage AS
 (SELECT file_type,
         ROUND(mb_used, 2) mb_used,
         ROUND(mb_reclaimable, 2) mb_reclaimable,
         DECODE(total_mb, 0, 0, ROUND(mb_used * 100 / total_mb, 2)) percent_space_used,
         DECODE(total_mb, 0, 0, ROUND(mb_reclaimable * 100 / total_mb, 2)) percent_space_reclaimable,
         number_of_files,
         total_mb db_recovery_file_dest_mb,
         flashback_retention_target,
         oldest_record,
         ROUND((sysdate - oldest_record) * 24 * 60, 2) oldest_record_age_sec
    FROM (SELECT SUM(DECODE(NAME,
                            'db_recovery_file_dest_size',
                            VALUE / 1048576,
                            0)) total_mb,
                 SUM(DECODE(NAME, 'db_flashback_retention_target', VALUE, 0)) flashback_retention_target
            FROM v$parameter
           WHERE NAME IN ('db_recovery_file_dest_size',
                          'db_flashback_retention_target')),
         (SELECT 'FLASHBACKLOG' file_type,
                 NVL(SUM(BYTES) / 1048576, 0) mb_used,
                 sum(CASE
                       WHEN last_time <= (sysdate - (tgt.value / 1440)) THEN
                        bytes / 1048576
                       ELSE
                        0
                     END) mb_reclaimable,
                 COUNT(*) number_of_files,
                 MIN(first_time) oldest_record
            FROM (select bytes,
                         lead(first_time) over(order by first_time asc) last_time,
                         first_time
                    from v$flashback_database_logfile) fla_log,
                 (SELECT value value
                    FROM v$parameter
                   WHERE name = 'db_flashback_retention_target') tgt
          UNION
          SELECT 'BACKUPPIECE' file_type,
                 NVL(SUM(BYTES / 1048576), 0) mb,
                 SUM(CASE
                       WHEN dl.rectype = 13 THEN
                        (BYTES / 1048576)
                       ELSE
                        0
                     END) reclaimable_mb,
                 COUNT(*) no_of_files,
                 MIN(start_time) oldest_record
            FROM v$backup_piece bp, x$kccagf dl
           WHERE is_recovery_dest_file = 'YES'
             AND deleted = 'NO'
             AND bp.recid = dl.recid(+)
             AND dl.rectype(+) = 13
          UNION
          SELECT 'ARCHIVELOG' file_type,
                 NVL(SUM(blocks * block_size) / 1048576, 0) mb,
                 SUM(CASE
                       WHEN dl.rectype = 11 THEN
                        (LOG.blocks * LOG.block_size / 1048576)
                       ELSE
                        0
                     END) reclaimable_mb,
                 COUNT(*) no_of_files,
                 MIN(first_time) oldest_record
            FROM v$archived_log log, x$kccagf dl
           WHERE deleted = 'NO'
             AND is_recovery_dest_file = 'YES'
             AND dl.recid(+) = log.recid
             AND dl.rectype(+) = 11
          UNION
          SELECT 'ONLINELOG' file_type,
                 SUM(BYTES / 1048576) mb,
                 0 reclaimable,
                 COUNT(*) no_of_files,
                 MIN(first_time) oldest_record
            FROM v$logfile lf,
                 (SELECT group#, BYTES, first_time
                    FROM v$standby_log
                  UNION
                  SELECT group#, BYTES, first_time FROM v$log) l
           WHERE l.group# = lf.group#
             AND lf.is_recovery_dest_file = 'YES'
          UNION
          SELECT 'IMAGECOPY',
                 NVL(SUM(blocks * (block_size / 1048576)), 0) mb,
                 0 reclaimable_mb,
                 COUNT(*) no_of_files,
                 MIN(creation_time) oldest_record
            FROM v$datafile_copy
           WHERE deleted = 'NO'
             AND is_recovery_dest_file = 'YES'
          UNION
          SELECT 'CONTROLFILE',
                 NVL(SUM(block_size * file_size_blks) / 1048576, 0) mb,
                 0 reclaimable,
                 COUNT(*) no_of_files,
                 NULL oldest_record
            FROM v$controlfile
           WHERE is_recovery_dest_file = 'YES'))
SELECT order_, NAME, VALUE
  FROM(
SELECT 0 order_, NAME, VALUE
  FROM v$parameter
 WHERE NAME LIKE 'db_recovery_file%'
UNION
SELECT 3, 'oldest flashback log (minutes)', TO_CHAR(ROUND(oldest_log_minutes, 2))
  FROM flashback_database_log
UNION
SELECT 1, 'retention target (minutes)', TO_CHAR(ROUND(retention_target_minutes, 2))
  FROM flashback_database_log
UNION
SELECT 2, 'estimated size for flashback logs (MB)', TO_CHAR(ROUND(estimated_flashback_size_mb, 2))
  FROM flashback_database_log
UNION
SELECT 2, 'Current flashback log count', TO_CHAR(logs)
  FROM flashback_database_logfile
UNION
SELECT 3, 'Most recent flashback log (minutes)', TO_CHAR(ROUND((SYSDATE - latest_log) * 24 * 60, 2))
  FROM flashback_database_logfile
UNION
SELECT 4, 'Total size of all files in MB', TO_CHAR(ROUND(SUM(mb_used), 2))
  FROM flashback_usage
UNION
SELECT 5, 'Total size of reclaimable files in MB', TO_CHAR(ROUND(SUM(mb_reclaimable), 2))
  FROM flashback_usage
UNION
SELECT 6, 'unused space in MB', TO_CHAR(ROUND(MIN(db_recovery_file_dest_mb) - SUM(mb_used)))
  FROM flashback_usage)
 ORDER BY order_, NAME
/

Sample Output:

    ORDER_ NAME                                                                             VALUE
---------- -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
         0 db_recovery_file_dest                                                            +SYSTEMDG
         0 db_recovery_file_dest_size                                                       5218762752
         1 retention target (minutes)                                                       1440
         2 Current flashback log count                                                      33
         2 estimated size for flashback logs (MB)                                           142.15
         3 Most recent flashback log (minutes)                                              164.03
         3 oldest flashback log (minutes)                                                   5846.35
         4 Total size of all files in MB                                                    1963.11
         5 Total size of reclaimable files in MB                                            534.47
         6 unused space in MB                                                               3014

沪ICP备14014813号-2

沪公网安备 31010802001379号