oracle常用查询sql

#!/bin/sh
## create by Gordon Chen

echo "\n=============`date`===================\n"

if [ "$LOGNAME" = "oracle" ]; then
   SQLPLUS_CMD="/ as sysdba";
else
   SQLPLUS_CMD="/ as sysdba";
fi

case $1 in
   si)
     if [ "$LOGNAME" = "oracle" ]; then
        sqlplus "/ as sysdba"
     else
        sqlplus "/ as sysdba"
     fi
     ;;
   res)
         sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 140
         set pagesize 200
         set serveroutput on
         alter session set cursor_sharing=force;
         exec xj_exp_data.PRC_RSCTL_M('$2',$3);
         exit;
EOF
  ;;
difplan_1000_times)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set line 300;
         col new_cpu format 999999.999;
         col old_cpu format 999999.999;
         col new_etime format 999999.999;
         col old_etime format 999999.999;
         col new_buff format 99999999.9;
         col old_buff format 99999999.9;  
         set pagesize 300;
         col username for a18;
select distinct  a.username,a.SQL_ID,a.PLAN_HASH_VALUE new_plan,b.PLAN_HASH_VALUE old_plan,a.AVG_CTIME new_cpu,b.AVG_CTIME old_cpu,a.AVG_LIO new_buff,b.AVG_LIO old_buff,a.avg_etime new_etime,b.AVG_ETIME old_etime
from
(select a.username,a.sql_id,b.plan_hash_value,(cpu_time/executions)/1000000 avg_ctime,buffer_gets/executions avg_lio,(elapsed_time/executions)/1000000 avg_etime
from v\$session a,v\$sql b where a.sql_id=b.sql_id and b.executions>1000 ) a left join xj_exp_data.xj_sql_baseline b
on a.sql_id = b.sql_id
where a.PLAN_HASH_VALUE <> b.PLAN_HASH_VALUE AND ((a.AVG_LIO-b.AVG_LIO)/b.AVG_LIO>1000 OR (A.AVG_CTIME-B.AVG_CTIME)/B.AVG_CTIME>1000)
order by 5,1,2;
     exit
EOF
     ;;
 log)
     sqlplus -s "$SQLPLUS_CMD" << EOF
spool /tmp/oralog.txt
select value from v\$parameter where name='background_dump_dest' or name='instance_name';
spool off
!cat /tmp/oralog.txt |grep -v -i value |grep -v '\-\-' |grep "\/"
exit
EOF
  ;;
 undo)
     sqlplus -s "$SQLPLUS_CMD" << EOF
    set line 200 pages 2000
    ALTER SESSION SET NLS_DATE_FORMAT='YYYY/MM/DD HH24:MI:SS' ;
    show parameter undo
    col tablespace_name for a20
    col file_name for a80
  select tablespace_name,file_name,bytes/1024/1024/1024 sizeG,status,autoextensible
    from dba_data_files where tablespace_name like '%UNDO%' order by 1;    
    col tablespace_name for a25
    select t.tablespace_name,
       total_GB,
       free_GB,
       round(100 * (1 - (free_GB / total_GB)), 3) || '%' "used_ts%"
  from (select tablespace_name, sum(bytes) / 1024 / 1024 / 1024 total_GB
          from dba_data_files
         group by tablespace_name) t,
       (select tablespace_name, sum(bytes) / 1024 / 1024 / 1024 free_GB
          from dba_free_space
         group by tablespace_name) f
 where t.tablespace_name = f.tablespace_name(+)
   and t.tablespace_name like '%UNDO%'
 order by tablespace_name;
select tablespace_name, status, sum(bytes / 1024 / 1024 / 1024) GB
  from dba_undo_extents
 group by tablespace_name, status;
 
select u.begin_time,
       u.end_time,
       t.name         "undo_tbs_name",
       u.undoblks     "blocks_used",
       u.txncount     "transactions",
       u.maxquerylen  "longest query",
       u.expblkreucnt "expired blocks"
  from v\$undostat u, v\$tablespace t
 where u.undotsn = t.ts#
 and rownum < 21
 order by undoblks desc, maxquerylen;
!echo ****************undo advice******************
col UNDO_RETENTION for a15
col DB_BLOCK_SIZE for a15
select ur undo_retention, dbs db_block_size, ((ur * (ups * dbs))+(dbs * 24))/1024/1024 as "Average_Mb"
from (select value as ur from v\$parameter where name = 'undo_retention'),
(select (sum(undoblks) / sum(((end_time - begin_time) * 86400))) ups from v\$undostat),
(select value as dbs from v\$parameter where name = 'db_block_size');

col UNDO_RETENTION for a15
col DB_BLOCK_SIZE for a15
select ur undo_retention, dbs db_block_size, ((ur * (ups * dbs)) + (dbs * 24)) / 1024 / 1024 as "Peak_Mb"
from (select value as ur from v\$parameter where name = 'undo_retention'),
(select (undoblks / ((end_time - begin_time) * 86400)) ups from v\$undostat where undoblks in (select max(undoblks) from v\$undostat)),
(select value as dbs from v\$parameter where name = 'db_block_size');

!echo ****************undo detail******************
select s.sid,s.serial#,s.sql_id,v.usn,segment_name,r.status, v.rssize/1024/1024 mb
From dba_rollback_segs r, v\$rollstat v,v\$transaction t,v\$session s
Where r.segment_id = v.usn and v.usn=t.xidusn and t.addr=s.taddr
order by segment_name ;

select * from (select begin_time,txncount,maxquerylen,unexpiredblks,expiredblks,tuned_undoretention from v\$undostat order by begin_time) where rownum < 31;   
!echo ***********transactions rollback*************
select usn, state, undoblockstotal "Total", undoblocksdone "Done", undoblockstotal-undoblocksdone "ToDo",decode(cputime,0,'unknown',sysdate+(((undoblockstotal-undoblocksdone) / (undoblocksdone / cputime)) / 86400)) "Estimated time to complete"
  from v\$fast_start_transactions;
exit
EOF
   ;;
   ke)
    sqlplus -s "$SQLPLUS_CMD" << EOF
        set lines 150 pages 2000
        select sid,serial#,username,program,sql_id from v\$session where event#='$2' order by sql_id;
                select 'alter system kill session '''|| sid ||','||serial# ||''' immediate;' from v\$session where event#='$2';
                select 'ps -ef|grep '||to_char(spid)||'|grep LOCAL=NO|awk ''{print " -9 "\$2}''|xargs kill' kill_sh from v\$process p,v\$session s where s.paddr=p.addr and s.type='USER' and s.event#='$2';
                exit    
                         
EOF
     ;;
   active)
         sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col sid format 9999
         col s# format 99999
         col spid format a10
         col username format a10
         col event format a30
         col machine format a20
         col p123 format a18
         col wt format 999
         col SQL_ID for a18
         alter session set cursor_sharing=force;
            SELECT /* LEADING(S) FIRST_ROWS */
             S.SID,
             S.SERIAL# S#,
             S.SQL_ID,
             P.SPID,
             NVL(S.USERNAME, SUBSTR(P.PROGRAM, LENGTH(P.PROGRAM) - 6)) USERNAME,
             S.MACHINE,
             S.EVENT,
             S.P1 || '/' || S.P2 || '/' || S.P3 P123,
             S.WAIT_TIME WT,
             NVL(SQL_ID, S.PREV_SQL_ID) SQL_ID
              FROM V\$PROCESS P, V\$SESSION S
             WHERE P.ADDR = S.PADDR
               AND S.STATUS = 'ACTIVE'
               AND P.BACKGROUND IS NULL;
         exit
EOF
     ;;
 highpara)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set linesize 150
     col sql_t format a50;                                       
      select substr(sql_text, 1, 50) as sql_t,
             trim(program),
             min(sql_id),
             count(*)
        from (select sql_text, a.sql_id, program
                from v\$session a, v\$sqlarea b,v\$px_session px
               where a.sql_id = b.sql_id
                 and a.sid = px.qcsid
                 and a.status = 'ACTIVE'
                 and a.sql_id is not null
              union all
              select sql_text, a.PREV_SQL_ID as sql_id, program
                from v\$session a, v\$sqlarea b,v\$px_session px
               where a.sql_id is null
                 and a.PREV_SQL_ID = b.sql_id
                 and a.sid = px.qcsid
                 and a.status = 'ACTIVE')
       group by substr(sql_text, 1, 50), trim(program)
       order by 1;
               exit
EOF
     ;;
 event)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set linesize 150 pages 100
     col event for a60
     select event#,event,count(*) from v\$session
   where status='ACTIVE' and event not like '%message%' group by event#, event order by 3;              
exit
EOF
     ;;     
   size)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col owner format a10
         col segment_name for a30
         alter session set cursor_sharing=force;
         SELECT  OWNER,SEGMENT_NAME, SEGMENT_TYPE, SUM(BYTES)/1048576 SIZE_MB,
                    MAX(INITIAL_EXTENT) INIEXT, MAX(NEXT_EXTENT) MAXEXT FROM DBA_SEGMENTS
             WHERE SEGMENT_NAME = upper('$2')
               AND ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3'))
               AND SEGMENT_TYPE LIKE 'TABLE%'
             GROUP BY OWNER, SEGMENT_NAME, SEGMENT_TYPE
           UNION ALL
             SELECT OWNER, SEGMENT_NAME, SEGMENT_TYPE, SUM(BYTES)/1048576 SIZE_MB,
                    MAX(INITIAL_EXTENT) INIEXT, MAX(NEXT_EXTENT) MAXEXT FROM DBA_SEGMENTS
             WHERE (OWNER,SEGMENT_NAME) IN (
                SELECT OWNER,INDEX_NAME FROM DBA_INDEXES WHERE TABLE_NAME=upper('$2') AND
                ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3'))
                UNION
                SELECT OWNER,SEGMENT_NAME FROM DBA_LOBS WHERE TABLE_NAME=upper('$2') AND
                ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3')))
             GROUP BY OWNER, SEGMENT_NAME, SEGMENT_TYPE;
          exit
EOF
     ;;
   idxdesc)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     alter session set cursor_sharing=force;
      SET linesize 500
      col INDEX_COL  FOR a30
      col INDEX_TYPE FOR a22
      col INDEX_NAME FOR a32
      col table_name FOR a32
      SELECT B.OWNER||'.'||B.INDEX_NAME INDEX_NAME,
             A.INDEX_COL,B.INDEX_TYPE||'-'||B.UNIQUENESS INDEX_TYPE,B.PARTITIONED
        FROM (SELECT TABLE_OWNER,TABLE_NAME,INDEX_NAME, SUBSTR(MAX(SYS_CONNECT_BY_PATH(COLUMN_NAME, ',')), 2) INDEX_COL
                FROM (SELECT TABLE_OWNER, TABLE_NAME,INDEX_NAME,  COLUMN_NAME,
                             ROW_NUMBER() OVER(PARTITION BY TABLE_OWNER, TABLE_NAME, INDEX_NAME
                             ORDER BY TABLE_OWNER, INDEX_NAME, COLUMN_POSITION, COLUMN_NAME) RN
                        FROM DBA_IND_COLUMNS
                       WHERE TABLE_NAME = UPPER('$2')
                         AND TABLE_OWNER = UPPER('$3'))
               START WITH RN = 1
              CONNECT BY PRIOR RN = RN - 1
                     AND PRIOR TABLE_NAME = TABLE_NAME
                     AND PRIOR INDEX_NAME = INDEX_NAME
                     AND PRIOR TABLE_OWNER = TABLE_OWNER
               GROUP BY TABLE_NAME, INDEX_NAME, TABLE_OWNER
               ORDER BY TABLE_OWNER, TABLE_NAME, INDEX_NAME
             ) A,
            (SELECT * FROM DBA_INDEXES WHERE TABLE_NAME = UPPER('$2') AND TABLE_OWNER = UPPER('$3')) B
       WHERE A.TABLE_OWNER = B.TABLE_OWNER
         AND A.TABLE_NAME = B.TABLE_NAME
         AND A.INDEX_NAME =B.INDEX_NAME;  
         exit
EOF
     ;;
   tsfree)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set lines 200 pages 2000
     select count(*) recycnum  from dba_recyclebin;
    
     col tablespace_name for a40  
     SELECT /*+ ordered */D.TABLESPACE_NAME,SPACE "SUM_SPACE(M)",BLOCKS SUM_BLOCKS,SPACE - NVL(FREE_SPACE, 0) "USED_SPACE(M)",
            ROUND((1 - NVL(FREE_SPACE, 0) / SPACE) * 100, 2) "USED_RATE(%)", FREE_SPACE "FREE_SPACE(M)"
             FROM (SELECT TABLESPACE_NAME, ROUND(SUM(BYTES) / (1024 * 1024), 2) SPACE, SUM(BLOCKS) BLOCKS
               FROM DBA_DATA_FILES GROUP BY TABLESPACE_NAME) D,
                              (SELECT TABLESPACE_NAME, ROUND(SUM(BYTES) / (1024 * 1024), 2) FREE_SPACE
               FROM DBA_FREE_SPACE GROUP BY TABLESPACE_NAME) F
      WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME(+)
      ORDER BY  "USED_RATE(%)" DESC;
         exit
EOF
      ;;
   tablespace)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 200 pages 2000
         alter session set cursor_sharing=force;
         select TABLESPACE_NAME TS_NAME,INITIAL_EXTENT INI_EXT,NEXT_EXTENT NXT_EXT,
            STATUS,CONTENTS, EXTENT_MANAGEMENT EXT_MGR,ALLOCATION_TYPE ALLOC_TYPE
         FROM DBA_TABLESPACES ORDER BY 5,1;
         exit
EOF
      ;;
   datafile)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col name format a60
         col file# format 9999
         col size_mb format 99999
         alter session set cursor_sharing=force;
         select /*+ RULE */
            f.file#, F.NAME, TRUNC(f.BYTES/1048576,2) SIZE_MB , f.CREATION_TIME,f.status,d.AUTOEXTENSIBLE exten
         FROM V\$DATAFILE F,V\$TABLESPACE T,DBA_DATA_FILES D
         WHERE F.ts#=T.ts# and f.name=d.file_name AND T.NAME = NVL(UPPER('$2'),'SYSTEM')
         order by f.CREATION_TIME;
         exit
EOF
     ;;
   sqltext)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ SQL_TEXT FROM V\$SQLTEXT
          WHERE SQL_ID = to_char('$2')
          ORDER BY PIECE;
         exit
EOF
   ;;
   plan)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         alter session set cursor_sharing=force;
         set linesize 500 pages 4000
         SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(to_char('$2'),NULL));
         exit
EOF
     ;;
   lock)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col type format a12
         col hold format a12
         col request format a12
         col BLOCK_OTHERS format a16
         alter session set cursor_sharing=force;
         select  /*+ RULE */
            sid,
            decode(type,
                    'MR', 'Media Recovery',
                    'RT', 'Redo Thread',
                    'UN', 'User Name',
                    'TX', 'Transaction',
                    'TM', 'DML',
                    'UL', 'PL/SQL User Lock',
                    'DX', 'Distributed Xaction',
                    'CF', 'Control File',
                    'IS', 'Instance State',
                    'FS', 'File Set',
                    'IR', 'Instance Recovery',
                    'ST', 'Disk Space Transaction',
                    'TS', 'Temp Segment',
                    'IV', 'Library Cache Invalidation',
                    'LS', 'Log Start or Switch',
                    'RW', 'Row Wait',
                    'SQ', 'Sequence Number',
                    'TE', 'Extend Table',
                    'TT', 'Temp Table',
                    'TC', 'Thread Checkpoint',
                                'SS', 'Sort Segment',
                                'JQ', 'Job Queue',
                                'PI', 'Parallel operation',
                                'PS', 'Parallel operation',
                                'DL', 'Direct Index Creation',
                    type) type,
            decode(lmode,
                    0, 'None',            
                    1, 'Null',            
                    2, 'Row-S (SS)',      
                    3, 'Row-X (SX)',      
                    4, 'Share',           
                    5, 'S/Row-X (SSX)',   
                    6, 'Exclusive',       
                    to_char(lmode)) hold,
             decode(request,
                    0, 'None',            
                    1, 'Null',            
                    2, 'Row-S (SS)',      
                    3, 'Row-X (SX)',      
                    4, 'Share',           
                    5, 'S/Row-X (SSX)',   
                    6, 'Exclusive',       
                    to_char(request)) request,
             ID1,ID2,CTIME,
             decode(block,
                    0, 'Not Blocking',  
                    1, 'Blocking',      
                    2, 'Global',        
                    to_char(block)) block_others
                from v\$lock
            where type <> 'MR' and to_char(sid) = nvl('$2',to_char(sid)) ;
         exit
EOF
     ;;
   lockwait)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col HOLD_SID format 99999
         col WAIT_SID format 99999
         col type format a20
         col hold format a12
         col request format a12
         alter session set cursor_sharing=force;
         SELECT /*+ ORDERED USE_HASH(H,R) */
            H.SID HOLD_SID,
            R.SID WAIT_SID,
            decode(H.type,
                    'MR', 'Media Recovery',
                    'RT', 'Redo Thread',
                    'UN', 'User Name',
                    'TX', 'Transaction',
                    'TM', 'DML',
                    'UL', 'PL/SQL User Lock',
                    'DX', 'Distributed Xaction',
                    'CF', 'Control File',
                    'IS', 'Instance State',
                    'FS', 'File Set',
                    'IR', 'Instance Recovery',
                    'ST', 'Disk Space Transaction',
                    'TS', 'Temp Segment',
                    'IV', 'Library Cache Invalidation',
                    'LS', 'Log Start or Switch',
                    'RW', 'Row Wait',
                    'SQ', 'Sequence Number',
                    'TE', 'Extend Table',
                    'TT', 'Temp Table',
                    'TC', 'Thread Checkpoint',
                                'SS', 'Sort Segment',
                                'JQ', 'Job Queue',
                                'PI', 'Parallel operation',
                                'PS', 'Parallel operation',
                                'DL', 'Direct Index Creation',
                    H.type) type,
            decode(H.lmode,
                    0, 'None',         1, 'Null',
                    2, 'Row-S (SS)',   3, 'Row-X (SX)',
                    4, 'Share',        5, 'S/Row-X (SSX)',
                    6, 'Exclusive',    to_char(H.lmode)) hold,
             decode(r.request,         0, 'None',
                    1, 'Null',         2, 'Row-S (SS)',
                    3, 'Row-X (SX)',   4, 'Share',
                    5, 'S/Row-X (SSX)',6, 'Exclusive',
                    to_char(R.request)) request,
            R.ID1,R.ID2,R.CTIME
          FROM V\$LOCK H,V\$LOCK R
          WHERE H.BLOCK = 1 AND R.REQUEST > 0 AND H.SID <> R.SID
            and H.TYPE <> 'MR' AND R.TYPE <> 'MR'
            AND H.ID1 = R.ID1 AND H.ID2 = R.ID2 AND H.TYPE=R.TYPE
            AND H.LMODE > 0 AND R.REQUEST > 0 ORDER BY 1,2;
         exit
EOF
      ;;
   objlike)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col type format a16
         col OWNER format a12
         col status format a8
         col CREATED format a10
         col MODIFIED format a19
         col OBJECT_NAME format a30
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ OBJECT_TYPE TYPE,OBJECT_ID ID,OWNER,OBJECT_NAME,
               TO_CHAR(CREATED,'YYYY/MM/DD') CREATED,
               TO_CHAR(LAST_DDL_TIME,'YYYY/MM/DD HH24:MI:SS') MODIFIED,STATUS
           FROM ALL_OBJECTS
           WHERE OBJECT_TYPE IN ('CLUSTER','FUNCTION','INDEX',
                'PACKAGE','PROCEDURE','SEQUENCE','SYNONYM',
                'TABLE','TRIGGER','TYPE','VIEW')
             AND ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3'))
             AND OBJECT_NAME LIKE UPPER('%$2%');
         exit
EOF
      ;;
   tablike)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col OWNER format a12
         col status format a8
         col CREATED format a10
         col MODIFIED format a19
         col OBJECT_NAME format a30
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ OBJECT_ID ID,OWNER,OBJECT_NAME,
               TO_CHAR(CREATED,'YYYY/MM/DD') CREATED,
               TO_CHAR(LAST_DDL_TIME,'YYYY/MM/DD HH24:MI:SS') MODIFIED,STATUS
           FROM ALL_OBJECTS
           WHERE OBJECT_TYPE = 'TABLE'
             AND ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3'))
             AND OBJECT_NAME LIKE UPPER('%$2%');
         exit
EOF
      ;;
   tstat)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         
         col owner format a10
         col partname format a30
         col INIEXT format 99999
         col nxtext format 99999
         col avgspc format 99999
         col ccnt format 999
         col rowlen format 9999
         col ssize format 9999999
         alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
         alter session set cursor_sharing=force;
         SELECT   OWNER,NULL PARTNAME,
            NUM_ROWS NROWS, BLOCKS, AVG_SPACE AVGSPC,CHAIN_CNT CCNT, AVG_ROW_LEN ROWLEN,
            SAMPLE_SIZE SSIZE,LAST_ANALYZED ANADATE
         FROM ALL_TABLES
         WHERE UPPER(OWNER)=NVL(UPPER('$3'),OWNER)  AND TABLE_NAME=UPPER('$2')
         UNION ALL
         SELECT     TABLE_OWNER OWNER,PARTITION_NAME PARTNAME,
            NUM_ROWS NROWS, BLOCKS, AVG_SPACE AVGSPC,CHAIN_CNT CCNT, AVG_ROW_LEN ROWLEN,
            SAMPLE_SIZE SSIZE,LAST_ANALYZED ANADATE
         FROM ALL_TAB_PARTITIONS
         WHERE UPPER(TABLE_OWNER)=NVL(UPPER('$3'),TABLE_OWNER)  AND TABLE_NAME=UPPER('$2');
         
         
         exit
EOF
     ;;
   istat)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col OWNER format a10
         col lkey format 999
         col dkey format 999
         col lev format 99
         col anaday format a10
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */  
            TABLE_OWNER OWNER, INDEX_NAME,
            BLEVEL LEV, LEAF_BLOCKS LBLKS,TRUNC(NUM_ROWS) NROWS,
            DISTINCT_KEYS DROWS,
            CLUSTERING_FACTOR CLSFCT,SAMPLE_SIZE SSIZE,
            TO_CHAR(LAST_ANALYZED,'YYYY/MM/DD') ANADAY,
            PARTITIONED PAR
         FROM DBA_INDEXES
         WHERE (upper(table_owner) in null or UPPER(TABLE_OWNER)=NVL(UPPER('$3'),TABLE_OWNER))
           AND TABLE_NAME=UPPER('$2');
         exit
EOF
     ;;
   ipstat)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col OWNER format a10
         col lkey format 999
         col dkey format 999
         col lev format 99
         col anaday format a10
         alter session set cursor_sharing=force;
         SELECT
            PARTITION_NAME,
            BLEVEL LEV, LEAF_BLOCKS LBLKS,TRUNC(NUM_ROWS) NROWS,
            DISTINCT_KEYS DROWS,
            CLUSTERING_FACTOR CLSFCT,SAMPLE_SIZE SSIZE,
            TO_CHAR(LAST_ANALYZED,'YYYY/MM/DD') ANADAY
         FROM DBA_IND_PARTITIONS
         WHERE UPPER(INDEX_OWNER)=NVL(UPPER('$3'),INDEX_OWNER)
           AND INDEX_NAME=UPPER('$2');
         exit
EOF
     ;;
   objsql)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col vers format 999
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */
            HASH_VALUE, OPEN_VERSIONS VERS,
            SORTS, EXECUTIONS EXECS,  
            DISK_READS READS, BUFFER_GETS GETS,
            ROWS_PROCESSED ROWCNT
          FROM V\$SQL WHERE EXECUTIONS > 10 AND HASH_VALUE IN
            (SELECT /*+ NL_SJ */ DISTINCT HASH_VALUE
               FROM V\$SQL_PLAN WHERE OBJECT_NAME=UPPER('$2')
               AND NVL(OBJECT_OWNER,'A')=UPPER(NVL('$3','A')));
         exit
EOF
     ;;
   longops)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col MESSAGE format a30
         col opname for a20
         col username for a20
         set pagesize 1000
         alter session set cursor_sharing=force;
         select opname,TIME_REMAINING REMAIN,
                ELAPSED_SECONDS ELAPSE,MESSAGE,
                SQL_ID,sid,username
         from v\$session_longops where TIME_REMAINING >0;
         exit
EOF
     ;;
   tran)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col USERNAME format a12
         col rbs format a22
         col BLKS_RECS format a16
         col START_TIME format a17
         col LOGIO format 99999
         col PHY_IO FORMAT 99999
         COL CRGET FORMAT 99999
         COL CRMOD FORMAT 99999
         alter session set cursor_sharing=force;
         SELECT /*+ rule */   
             S.SID,S.SERIAL#,S.USERNAME, R.NAME RBS,
             T.START_TIME,  
             to_char(T.USED_UBLK)||','||to_char(T.USED_UREC) BLKS_RECS ,
             T.LOG_IO LOGIO,T.PHY_IO PHYIO,T.CR_GET CRGET,T.CR_CHANGE CRMOD
           FROM V\$TRANSACTION T, V\$SESSION S,V\$ROLLNAME R,
                V\$ROLLSTAT RS
           WHERE T.SES_ADDR(+) = S.SADDR   
             AND T.XIDUSN = R.USN AND S.USERNAME IS NOT NULL  
             AND R.USN = RS.USN ;
         exit
EOF
     ;;
   depend)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 170 pages 2000
         col name for a15
         col D_NAME for a30
         col D_OWNER for a20
         col dblink for a20
         alter session set cursor_sharing=force;
         SELECT TYPE,REFERENCED_OWNER D_OWNER,
               REFERENCED_NAME D_NAME,REFERENCED_TYPE D_TYPE,
               REFERENCED_LINK_NAME DBLINK, DEPENDENCY_TYPE DEPEND
           FROM DBA_DEPENDENCIES
           WHERE
             UPPER(OWNER) = NVL(UPPER('$3'),OWNER)
             AND NAME  = UPPER('$2');
         SELECT   REFERENCED_TYPE TYPE,OWNER R_OWNER,
                NAME R_NAME, TYPE R_TYPE,DEPENDENCY_TYPE DEPEND
           FROM DBA_DEPENDENCIES
           WHERE
             UPPER(REFERENCED_OWNER) = NVL(UPPER('$3'),REFERENCED_OWNER)
             AND REFERENCED_NAME  = UPPER('$2')
             AND REFERENCED_LINK_NAME IS NULL;
         exit
EOF
     ;;
   latch)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         alter session set cursor_sharing=force;
         SELECT  NAME FROM V\$LATCHNAME WHERE LATCH#=TO_NUMBER('$2');
         exit
EOF
     ;;
   hold)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col USERNAME format a16
         col MACHINE format a20
         alter session set cursor_sharing=force;
         SELECT /*+ RULE */
             S.SID,S.SERIAL#,P.SPID,S.USERNAME,
             S.MACHINE,S.STATUS
           FROM V\$PROCESS P, V\$SESSION S, V\$LOCKED_OBJECT O   
           WHERE P.ADDR = S.PADDR
             AND O.SESSION_ID=S.SID    
             AND S.USERNAME IS NOT NULL
             AND O.OBJECT_ID=TO_NUMBER('$2');
         exit
EOF
     ;;
   sort)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col USERNAME format a12
         col MACHINE format a16
         col TABLESPACE format a20
         alter session set cursor_sharing=force;
         SELECT /*+ ordered */  
           B.SID,B.SERIAL#,B.USERNAME,B.MACHINE,A.BLOCKS,A.TABLESPACE,
           A.SEGTYPE,A.SEGFILE# FILE#,A.SEGBLK# BLOCK#
           FROM V\$SORT_USAGE A,V\$SESSION B
           WHERE A.SESSION_ADDR = B.SADDR;
         exit
EOF
     ;;
   desc)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 150 pages 2000
         col name format a30
         col nullable format a8
         col type format a30
         alter session set cursor_sharing=force;
         select COLUMN_ID NO#,COLUMN_NAME NAME,
           DECODE(NULLABLE,'N','NOT NULL','') NULLABLE,
           (case  
              when data_type='CHAR' then data_type||'('||data_length||')'
              when data_type='VARCHAR' then data_type||'('||data_length||')'
              when data_type='VARCHAR2' then data_type||'('||data_length||')'
              when data_type='NCHAR' then data_type||'('||data_length||')'
              when data_type='NVARCHAR' then data_type||'('||data_length||')'
              when data_type='NVARCHAR2' then data_type||'('||data_length||')'
              when data_type='RAW' then data_type||'('||data_length||')'
              when data_type='NUMBER' then
                    (
                       case
                          when data_scale is null and data_precision is null then 'NUMBER'
                          when data_scale <> 0  then 'NUMBER('||NVL(DATA_PRECISION,38)||','||DATA_SCALE||')'
                      else 'NUMBER('||NVL(DATA_PRECISION,38)||')'
                       end
                    )
              else
                 ( case
                     when data_type_owner is not null then data_type_owner||'.'||data_type
                                 else data_type
                   end )
            end) TYPE
            from dba_tab_columns
            where upper(owner)=UPPER(nvl('$3',owner)) AND TABLE_NAME=upper('$2')
            order by 1;
         exit
EOF
     ;;
   segment)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col USERNAME format a12
         col MACHINE format a16
         col TABLESPACE format a10
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ /*+ RULE */
            SEGMENT_TYPE,OWNER SEGMENT_OWNER,SEGMENT_NAME,  
                    TRUNC(SUM(BYTES)/1024/1024,1) SIZE_MB
            FROM DBA_SEGMENTS WHERE OWNER NOT IN ('SYS','SYSTEM')
            GROUP BY SEGMENT_TYPE,OWNER,SEGMENT_NAME
            HAVING SUM(BYTES) > TO_NUMBER(NVL('$2','100')) * 1048576  
            ORDER BY 1,2,3,4 DESC;
         exit
EOF
     ;;
   seqlike)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col owner format a12
         col MAX_VALUE format 999999999999
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ SEQUENCE_OWNER OWNER,SEQUENCE_NAME,
            MIN_VALUE LOW,MAX_VALUE HIGH,INCREMENT_BY STEP,CYCLE_FLAG CYC,
            ORDER_FLAG ORD,CACHE_SIZE CACHE,LAST_NUMBER CURVAL
           FROM ALL_SEQUENCES
           WHERE ('$3' IS NULL OR UPPER(SEQUENCE_OWNER) = UPPER('$3'))
             AND SEQUENCE_NAME LIKE UPPER('$2');
         exit
EOF
     ;;
   tabpart)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col USERNAME format a12
         col MACHINE format a16
         col TABLESPACE format a10
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ PARTITION_POSITION NO#,PARTITION_NAME,TABLESPACE_NAME TS_NAME,
            INITIAL_EXTENT/1024 INI_K, NEXT_EXTENT/1024 NEXT_K,PCT_INCREASE PCT,
            FREELISTS FLS, FREELIST_GROUPS FLGS
           FROM ALL_TAB_PARTITIONS
           WHERE ('$3' IS NULL OR UPPER(TABLE_OWNER) = UPPER('$3'))
             AND TABLE_NAME LIKE UPPER('$2')
           ORDER BY 1;
         exit
EOF
     ;;
   view)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 200  pages 2000
         col TYPE_NAME format a30
         alter session set cursor_sharing=force;
         SELECT  /*+ ordered */OWNER,VIEW_NAME,
            DECODE(VIEW_TYPE_OWNER,NULL,NULL,VIEW_TYPE_OWNER||'.'||VIEW_TYPE) TYPE_NAME
           FROM DBA_VIEWS
           WHERE ('$3' IS NULL OR UPPER(OWNER) = UPPER('$3'))
             AND VIEW_NAME LIKE UPPER('%$2%')
             AND OWNER NOT IN ('SYS','SYSTEM');
         exit
EOF
     ;;
   param)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col NAME format a40
         COL VALUE FORMAT A40
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */ NAME,ISDEFAULT,ISSES_MODIFIABLE SESMOD,
           ISSYS_MODIFIABLE SYSMOD,VALUE
           FROM V\$PARAMETER
           WHERE NAME LIKE '%' || LOWER('$2') || '%'
             AND NAME <> 'control_files'
             and name <> 'rollback_segments';
         exit
EOF
     ;;
   _param)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col NAME format a40
         COL VALUE FORMAT A40
         alter session set cursor_sharing=force;
         SELECT /* SHSNC */
           P.KSPPINM NAME, V.KSPPSTVL VALUE  
         FROM SYS.X\$KSPPI P, SYS.X\$KSPPSV V
         WHERE P.INDX = V.INDX  
           AND V.INST_ID = USERENV('Instance')
           AND SUBSTR(P.KSPPINM,1,1)='_'
           AND ('$2' IS NULL OR P.KSPPINM LIKE '%'||LOWER('$2')||'%');
         exit
EOF
     ;;
   grant)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set linesize 120
         col GRANTEE format a12
         col owner   format a12
         col GRANTOR format a12
         col PRIVILEGE format a20
         COL VALUE FORMAT A40
         alter session set cursor_sharing=force;
         SELECT  * FROM DBA_TAB_PRIVS
          WHERE (OWNER=NVL(UPPER('$3'),OWNER) or '$3' IS NULL)
            AND TABLE_NAME LIKE UPPER('$2');
         exit
EOF
     ;;
   unusable)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 200 pages 2000
         col GRANTEE format a12
         col owner   format a12
         col GRANTOR format a12
         col PRIVILEGE format a20
         COL VALUE FORMAT A40
         alter session set cursor_sharing=force;
         SELECT
           'ALTER INDEX '||OWNER||'.'||INDEX_NAME||' REBUILD ONLINE;' UNUSABLE_INDEXES
         FROM ALL_INDEXES
         WHERE (TABLE_OWNER=UPPER('$2') OR '$2' IS NULL) AND STATUS='UNUSABLE'
         UNION ALL
         SELECT 'ALTER INDEX '||IP.INDEX_OWNER||'.'||IP.INDEX_NAME||' REBUILD PARTITION '
                ||IP.PARTITION_NAME||' ONLINE;'
         FROM ALL_IND_PARTITIONS IP, ALL_INDEXES I
         WHERE IP.INDEX_OWNER=I.OWNER AND IP.INDEX_NAME=I.INDEX_NAME
           AND (I.TABLE_OWNER=UPPER('$2') OR '$2' IS NULL) AND IP.STATUS='UNUSABLE'
         UNION ALL
         SELECT 'ALTER INDEX '||IP.INDEX_OWNER||'.'||IP.INDEX_NAME||' REBUILD SUBPARTITION '
                ||IP.PARTITION_NAME||' ONLINE;'
         FROM ALL_IND_SUBPARTITIONS IP, ALL_INDEXES I
         WHERE IP.INDEX_OWNER=I.OWNER AND IP.INDEX_NAME=I.INDEX_NAME
           AND (I.TABLE_OWNER=UPPER('$2') OR '$2' IS NULL) AND IP.STATUS='UNUSABLE';
         exit
EOF
     ;;
   invalid)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set lines 150 pages 2000
         col owner format a12
         col object_name format a30
         col created format a20
         col last_ddl_time format a19
         alter session set cursor_sharing=force;
         SELECT  OBJECT_ID, OWNER,OBJECT_NAME,OBJECT_TYPE,
           to_char(created,'yy-mm-dd hh24:mi:ss') created,
           to_char(LAST_DDL_TIME,'yy-mm-dd hh24:mi:ss') last_ddl_time
         FROM DBA_OBJECTS
         WHERE STATUS='INVALID' AND ('$2' IS NULL OR OWNER=UPPER('$2'));
         exit
EOF
     ;;
    ddl)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set long 49000
         set longc 9999
         set line 150 pagesize 10000
         alter session set cursor_sharing=force;
         SELECT dbms_metadata.get_ddl(upper('$2'),upper('$4'),upper('$3')) from dual;
         exit
EOF
     ;;
        lockholder)
     sqlplus -s "$SQLPLUS_CMD" << EOF
  set lines 150 pages 2000
  column event format a30
  column sess format a20
  break on id1 skip 1
select decode(request,0,'Holder:',' Waiter:') || s.inst_id || ':' || s.sid||','|| s.serial# sess,
      id1, id2, lmode, request, l.type, ctime, s.sql_id, s.event,s.last_call_et
  from gv\$lock l, gv\$session s
  where (id1, id2, l.type) in
    (select id1, id2, type from gv\$lock where request>0
    )
   and l.sid=s.sid
   and l.inst_id=s.inst_id
  order by id1, ctime desc, request;
exit
EOF
     ;;
       hcost)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set line 300 pages 100
          col "program" format a38
          col "event" format a30
          col "username" format a15
       select ta.*,round(ta.cpu_time/tb.total_cpu * 100,1) cpu_usage from
  (select s.username,s.program,s.event,s.sql_id,sum(trunc(m.CPU)) CPU_TIME,count(*) sum
  from v\$sessmetric m ,v\$session s
  where ( m.PHYSICAL_READS >100
       or m.CPU>100
       or m.LOGICAL_READS >100)
       and m.SESSION_ID = s.SID
       and m.SESSION_SERIAL_NUM = s.SERIAL#
       and s.status = 'ACTIVE'
       and username is not null
 group by s.username,s.program,s.event,s.sql_id
 order by 5 desc) ta,(select sum(cpu) total_cpu from v\$sessmetric) tb
 where rownum < 11;    
exit
EOF
     ;;
       get_kill_sh)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set line 120;
     select 'ps -ef|grep '||to_char(spid)||'|grep LOCAL=NO|awk ''{print " -9 "\$2}''|xargs kill' kill_sh
from v\$process p,v\$session s
where s.paddr=p.addr
and s.sql_id='$2';
     exit
EOF
     ;;
    hsql)
     sqlplus -s "$SQLPLUS_CMD" << EOF
col username for a10
col program for a50
col event for a30
set line 300
select s.username,s.program,s.sql_id,s.event,p.spid,sql.cpu_time/1000000/decode(EXECUTIONS,0,1,EXECUTIONS) cpu,sql.BUFFER_GETS/decode(EXECUTIONS,0,1,EXECUTIONS) buff
from  v\$sql sql,v\$session s,v\$process p
where s.sql_id=sql.sql_id
and s.status='ACTIVE'
and WAIT_CLASS#<>6
and s.paddr=p.addr
order by 6 desc;
     exit
EOF
     ;;
      frag)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set line 300
     set pagesize 300
     col table_name for a35
SELECT OWNER,
       TABLE_NAME,
       segment_space_management MANAGEMENT,
       TABLE_MB USED_MB,
       WASTE_PER fragment_per,
       SEGMENT_TYPE,
       ROUND(WASTE_PER * TABLE_MB / 100, 2) FRAG_MB
  FROM (SELECT OWNER,
               SEGMENT_NAME TABLE_NAME,
               LAST_ANALYZED,
               SEGMENT_TYPE,
               GREATEST(ROUND(100 * (NVL(HWM - AVG_USED_BLOCKS, 0) / GREATEST(NVL(HWM, 1), 1)), 2), 0) WASTE_PER,
               ROUND(BYTES / POWER(1024, 2), 2) TABLE_MB,
               NUM_ROWS,
               BLOCKS,
               EMPTY_BLOCKS,
               HWM HIGHWATER_MARK,
               AVG_USED_BLOCKS,
               CHAIN_PER,
               EXTENTS,
               MAX_EXTENTS,
               ALLO_EXTENT_PER,
               DECODE(GREATEST(MAX_FREE_SPACE - NEXT_EXTENT, 0), 0, 'N', 'Y') CAN_EXTEND_SPACE,
               NEXT_EXTENT,
               MAX_FREE_SPACE,
               O_TABLESPACE_NAME TABLESPACE_NAME,
               block_size,
               segment_space_management
          FROM (SELECT A.OWNER OWNER,
                       A.SEGMENT_NAME,
                       A.SEGMENT_TYPE,
                       A.BYTES,
                       B.NUM_ROWS,
                       A.BLOCKS BLOCKS,
                       B.EMPTY_BLOCKS EMPTY_BLOCKS,
                       A.BLOCKS - B.EMPTY_BLOCKS - 1 HWM,
                       DECODE(ROUND((B.AVG_ROW_LEN * NUM_ROWS * (1 + (PCT_FREE / 100))) / dt.block_size, 0), 0, 1,
                              ROUND((B.AVG_ROW_LEN * NUM_ROWS * (1 + (PCT_FREE / 100))) / dt.block_size, 0)) + 2 AVG_USED_BLOCKS,
                              ROUND(100 * (NVL(B.CHAIN_CNT, 0) / GREATEST(NVL(B.NUM_ROWS, 1), 1)),
                             2) CHAIN_PER,
                       ROUND(100 * (A.EXTENTS / A.MAX_EXTENTS), 2) ALLO_EXTENT_PER,
                       A.EXTENTS EXTENTS,
                       A.MAX_EXTENTS MAX_EXTENTS,
                       B.NEXT_EXTENT NEXT_EXTENT,
                       B.TABLESPACE_NAME O_TABLESPACE_NAME,
                       B.LAST_ANALYZED,
                       dt.block_size,
                       DT.segment_space_management
                  FROM DBA_SEGMENTS A,
                       DBA_TABLES   B,
                       DBA_TABLESPACES  dt
                 WHERE A.OWNER = B.OWNER
                   and SEGMENT_NAME = TABLE_NAME
                   and SEGMENT_TYPE = 'TABLE'
                   and dt.tablespace_name = a.tablespace_name
                   and b.last_analyzed > sysdate-30
                union all
                SELECT A.OWNER OWNER,
                       SEGMENT_NAME || '.' || B.PARTITION_NAME,
                       SEGMENT_TYPE,
                       BYTES,
                       B.NUM_ROWS,
                       A.BLOCKS BLOCKS,
                       B.EMPTY_BLOCKS EMPTY_BLOCKS,
                       A.BLOCKS - B.EMPTY_BLOCKS - 1 HWM,
                       DECODE(ROUND((B.AVG_ROW_LEN * B.NUM_ROWS * (1 + (B.PCT_FREE / 100))) / dt.block_size, 0), 0, 1,
                              ROUND((B.AVG_ROW_LEN * B.NUM_ROWS * (1 + (B.PCT_FREE / 100))) / dt.block_size, 0)) + 2 AVG_USED_BLOCKS,
                              ROUND(100 * (NVL(B.CHAIN_CNT, 0) / GREATEST(NVL(B.NUM_ROWS, 1), 1)), 2) CHAIN_PER,
                       ROUND(100 * (A.EXTENTS / A.MAX_EXTENTS), 2) ALLO_EXTENT_PER,
                       A.EXTENTS EXTENTS,
                       A.MAX_EXTENTS MAX_EXTENTS,
                       B.NEXT_EXTENT,
                       B.TABLESPACE_NAME O_TABLESPACE_NAME,
                       d.last_analyzed,
                       dt.block_size,
                       DT.segment_space_management
                  FROM DBA_SEGMENTS       A,
                       DBA_TAB_PARTITIONS B,
                       DBA_TABLES         D,
                       DBA_TABLESPACES    dt
                 WHERE A.OWNER = B.TABLE_OWNER
                   and SEGMENT_NAME = B.TABLE_NAME
                   and SEGMENT_TYPE = 'TABLE PARTITION'
                   and dt.tablespace_name = a.tablespace_name
                   AND D.OWNER = B.TABLE_OWNER
                   AND D.TABLE_NAME = B.TABLE_NAME
                   AND A.PARTITION_NAME = B.PARTITION_NAME
                   AND D.last_analyzed > sysdate-30 ),
               (SELECT TABLESPACE_NAME F_TABLESPACE_NAME,
                       MAX(BYTES) MAX_FREE_SPACE
                  FROM SYS.DBA_FREE_SPACE
                 GROUP BY TABLESPACE_NAME)
         WHERE F_TABLESPACE_NAME = O_TABLESPACE_NAME
           AND GREATEST(ROUND(100 * (NVL(HWM - AVG_USED_BLOCKS, 0) /GREATEST(NVL(HWM, 1), 1)),2), 0) > 25
           AND OWNER not in ('SYS', 'SYSMAN','SYSTEM')
           AND BLOCKS > POWER(1024, 2) / block_size)
 where ROUND(WASTE_PER * TABLE_MB / 100, 2) > 100
 ORDER BY 5 DESC;     
     exit
EOF
     ;;
       tsql)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set line 300;
         set pagesize 300;
         col module for a30;
         col PARSING_SCHEMA_NAME for a10;
        select to_char(a.begin_time,'yyyymmdd hh24:mi'),to_char(a.end_time,'yyyymmdd hh24:mi'),a.INSTANCE_NUMBER,a.PARSING_SCHEMA_NAME,a.MODULE,a.SQL_ID,a.BUFFER_GETS_DELTA,a.CPU_TIME_DELTA/b.VALUE*100 cpu_pct
from (
select * from(
select ss.snap_id,sn.BEGIN_INTERVAL_TIME begin_time,sn.END_INTERVAL_TIME end_time,sn.INSTANCE_NUMBER,PARSING_SCHEMA_NAME,MODULE,SQL_ID,BUFFER_GETS_DELTA,CPU_TIME_DELTA,
RANK() OVER (PARTITION BY ss.snap_id,sn.INSTANCE_NUMBER ORDER BY CPU_TIME_DELTA DESC)rank
from DBA_HIST_SQLSTAT ss,DBA_HIST_SNAPSHOT sn
where sn.SNAP_ID=ss.snap_id
and sn.BEGIN_INTERVAL_TIME between sysdate-$2/24 and sysdate
and ss.INSTANCE_NUMBER=sn.INSTANCE_NUMBER)
where rank<6) a,DBA_HIST_SYSSTAT b
where a.snap_id=b.snap_id
and a.INSTANCE_NUMBER=b.INSTANCE_NUMBER
and b.STAT_ID=3649082374
order by 1,3 asc,8 desc;
     exit
EOF
     ;;
  difplan)
    sqlplus -s "$SQLPLUS_CMD" << EOF
  set lines 200 pages 2000
  col PLAN_HASH_VALUE format 99999999999
  col OPERATION format a30
  col OPTIONS format a40
  col OBJECT_NAME format a50
  alter session set nls_date_format='YYYY-MM-DD HH24:MI:SS';
select  distinct d.sql_id,d.plan_hash_value,(q.cpu_time/q.executions)/1000000 avg_ctime,q.buffer_gets/q.executions avg_lio,
 (q.elapsed_time/q.executions)/1000000 avg_etime,d.timestamp from DBA_HIST_SQL_PLAN d,v\$sql q
 where d.sql_id = '$2'
  and d.plan_hash_value = q.plan_hash_value (+)
 order by 6 asc;   
    exit
EOF
    ;;      
  parttab)
     sqlplus -s "$SQLPLUS_CMD" << EOF
         set line 200;
          COL "owner" format a10
          col "column_name" format a10
          col "object" format a10
          col "partitioning_type" format a20
          col "data_type" format a15
          SELECT C.*,D.DATA_TYPE FROM (select a.owner, a.name, a.column_name,a.OBJECT_TYPE,b.PARTITIONING_TYPE from DBA_PART_KEY_COLUMNS a, DBA_PART_TABLES b where a.owner=b.owner and a.NAME=b.TABLE_NAME) C ,DBA_TAB_COLS D WHERE C.owner=D.OWNER AND C.name=D.TABLE_NAME and c.column_name=d.COLUMN_NAME and UPPER(C.OWNER)=UPPER('$2')  AND D.TABLE_NAME=UPPER('$3');
     exit
EOF
     ;;
  hplan)
  sqlplus -s "$SQLPLUS_CMD" << EOF
set lin 220 pages 1000
col last_load_time for a25
select child_number cur#, plan_hash_value,
    buffer_gets/executions get_buff, disk_reads/executions read_e,
    cpu_time/executions/1000 cpu_e_ms  ,elapsed_time/executions/1000 elaps_e_ms  ,
     parsing_schema_id user#,USERS_EXECUTING  e_curr,
    CLUSTER_WAIT_TIME/executions/1000 cl_e_ms,
    ROWS_PROCESSED/executions rows_e,executions execs, last_load_time
from v\$sql where sql_id='$2'
and executions>0
/
exit   
EOF
     ;;
  user)
  sqlplus -s "$SQLPLUS_CMD" << EOF
  set lines 150 pages 2000
alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
select username,account_status,lock_date,expiry_date,default_tablespace def_tbs,temporary_tablespace tem_tbs,profile
   from dba_users where username=upper('$2');
!echo **************lock account****************
select username,account_status,expiry_date from dba_users where account_status like '%LOCK%';
exit
EOF
     ;;
hplan_hist)
     sqlplus -s "$SQLPLUS_CMD" << EOF
set lines 150 pages 999;
col p_user for 99999 ;
col execs  for 9999999 ;
select a.INSTANCE_NUMBER inst_id,to_char(b.END_INTERVAL_TIME,'yyyymmdd hh24:mi:ss') time,plan_hash_value,
    buffer_gets_delta/executions_delta get_exec, disk_reads_delta/executions_delta read_exec,
    cpu_time_delta/executions_delta/1000 cpu_exec_ms  ,elapsed_time_delta/executions_delta/1000 elaps_exec_ms  ,
     parsing_schema_id p_user,
    ROWS_PROCESSED_delta/executions_delta rows_exec,EXECUTIONS_DELTA execs
from dba_hist_sqlstat a, dba_hist_snapshot b
where a.sql_id='$2'
  and a.snap_id = b.snap_id
  and a.instance_number = b.instance_number
and b.END_INTERVAL_TIME between sysdate - $3 and sysdate
and executions_delta>0  order by 2,1
/
exit
EOF
     ;;
asm)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set lines 200 pages 2000
     col path for a30
select name,total_mb,type,free_mb,required_mirror_free_mb,usable_file_mb,compatibility
from v\$asm_diskgroup;
select g.name,
       d.path,
       d.failgroup,
       d.state,
       d.total_mb,
       d.free_mb,
       (d.total_mb-d.free_mb)/d.total_mb*100 used,
       d.failgroup_type
  from v\$asm_disk d, v\$asm_diskgroup g
 where d.group_number = g.group_number
 order by 1, 3, 2;
exit
EOF
     ;;
memory)
     sqlplus -s "$SQLPLUS_CMD" << EOF
     set lines 150 pages 2000
     col COMPONENT format a26
  alter session set nls_date_format='yyyy-mm-dd hh24';
  select name,bytes/1024/1024/1024,resizeable from v\$sgainfo;
 
  select sum(pga_alloc_mem)/1024/1024/1024 pga_sizeG from v\$process ;

  select component,current_size/1024/1024 current_mb,oper_count op_count,last_oper_type,last_oper_mode,last_oper_time from v\$sga_dynamic_components;
!echo ***************heap stat*****************
SELECT  /*+ rule */  ksmchidx "SubPool", 'sga heap(' || ksmchidx || ',0)' sga_heap,
          ksmchcom chunkcomment,
          DECODE (ROUND (ksmchsiz / 1000),
                  0, '0-1K', 1, '1-2K',2, '2-3K',3, '3-4K',4, '4-5K', 5, '5-6k',
                  6, '6-7k', 7, '7-8k','> 8K') "size",
          COUNT (*), ksmchcls status, SUM (ksmchsiz) BYTES
     FROM x\$ksmsp WHERE ksmchcom = 'free memory'
 GROUP BY ksmchidx, ksmchcls, 'sga heap(' || ksmchidx || ',0)',ksmchcom, ksmchcls,
          DECODE (ROUND (ksmchsiz / 1000),
                  0, '0-1K', 1, '1-2K',2, '2-3K',3, '3-4K',4, '4-5K', 5, '5-6k',
                  6, '6-7k', 7, '7-8k','> 8K') order by 1,3;
 
!echo ***************buffer cache advice*****************
    SELECT /*+ rule */ size_for_estimate "Cache Size (MB)",
                   size_factor,
                   buffers_for_estimate    "Buffers",
                         estd_physical_read_factor est_read_factor,
                   estd_physical_reads     estd_phy_red
            FROM   v\$db_cache_advice
            WHERE NAME='DEFAULT'
            AND block_size=(
                SELECT VALUE
                    FROM v\$parameter
                    WHERE NAME='db_block_size'
                    AND advice_status='ON');
                    
!echo ***************TOP10 hot obj*****************   
col OWNER for a30
col object_name for a50                  
select /*+ rule */ owner,object_name from dba_objects  
  where data_object_id in  
 (select obj from  
 (select obj from x\$bh order by tch desc )  
 where rownum <11);      
exit
EOF
     ;;
tbstat)
  sqlplus -s "$SQLPLUS_CMD" << EOF
  set pages 1000
select username,account_status,expiry_date from dba_users where account_status like '%LOCK%';
exit
EOF
     ;;
temp)
  sqlplus -s "$SQLPLUS_CMD" << EOF
    set lines 200 pages 2000
    col PROPERTY_VALUE for a30
    COL TEMP_FILE FOR A60
  SELECT PROPERTY_NAME, PROPERTY_VALUE FROM DATABASE_PROPERTIES WHERE PROPERTY_NAME='DEFAULT_TEMP_TABLESPACE';

  SELECT F.tablespace_name                                                             AS tbname,
       D.FILE_ID                                                                       AS ID,
       D.FILE_NAME                                                                     AS "TEMP_FILE",
       D.STATUS                                                                        AS STATUS,
       ROUND((F.BYTES_FREE  + F.BYTES_USED)/1024/1024/1024, 2)                         AS "TOTAL(GB)",
       ROUND(NVL(P.BYTES_USED, 0)/1024/1024/1024, 2)                                   AS "USED(GB)" ,
       ROUND(((F.BYTES_USED + F.BYTES_FREE) - NVL(P.BYTES_USED, 0))/1024/1024/1024, 2) AS "FREE(GB)"
FROM SYS.V_\$TEMP_SPACE_HEADER F ,DBA_TEMP_FILES D ,SYS.V_\$TEMP_EXTENT_POOL P
WHERE F.TABLESPACE_NAME(+) = D.TABLESPACE_NAME
  AND F.FILE_ID(+) = D.FILE_ID
  AND P.FILE_ID(+) = D.FILE_ID;
exit
EOF
     ;;
libpin)
  sqlplus -s "$SQLPLUS_CMD" << EOF
    set lines 200 pages 2000
    col username for a12
    SELECT b.inst_id,a.SID, a.serial#,a.username, a.program,a.event,b.addr, b.kglpnadr, b.kglpnhdl, b.kglpnmod, b.kglpnreq
  FROM gv\$session a, x\$kglpn b
 WHERE a.saddr = b.kglpnuse
   AND b.kglpnmod <> 0
   AND b.kglpnhdl IN (SELECT p1raw FROM gv\$session_wait WHERE event like 'library %') order by 1,9;
exit
EOF
     ;;
redo)
  sqlplus -s "$SQLPLUS_CMD" << EOF
    set lines 200 pages 2000
    col group#  for 99
    col type    for a10
    col member  for a60
    select group#,type,member from v\$logfile order by 1;

  select l.thread#,l.group#,l.sequence#,l.bytes/1024/1024,l.members,l.status,a.ARCHIVED arch,a.APPLIED appl,a.DELETED dele
 from v\$Log l,
     v\$archived_log a
 where l.SEQUENCE# = a.SEQUENCE# (+)
 order by 1,2,3;

archive log list;

col Date for a18
col Day for a6
col Total for 9999
col "h00" for a3
col "h01" for a3
col "h02" for a3
col "h03" for a3
col "h04" for a3
col "h05" for a3
col "h06" for a3
col "h07" for a3
col "h08" for a3
col "h09" for a3
col "h10" for a3
col "h11" for a3
col "h12" for a3
col "h13" for a3
col "h14" for a3
col "h15" for a3
col "h16" for a3
col "h17" for a3
col "h18" for a3
col "h19" for a3
col "h20" for a3
col "h21" for a3
col "h22" for a3
col "h23" for a3
SELECT  trunc(first_time) "Date",
to_char(first_time, 'Dy') "Day",
count(1) as "Total",
substr(SUM(decode(to_char(first_time, 'hh24'),'00',1,0)),1,3) as "h00",
substr(SUM(decode(to_char(first_time, 'hh24'),'01',1,0)),1,3) as "h01",
substr(SUM(decode(to_char(first_time, 'hh24'),'02',1,0)),1,3) as "h02",
substr(SUM(decode(to_char(first_time, 'hh24'),'03',1,0)),1,3) as "h03",
substr(SUM(decode(to_char(first_time, 'hh24'),'04',1,0)),1,3) as "h04",
substr(SUM(decode(to_char(first_time, 'hh24'),'05',1,0)),1,3) as "h05",
substr(SUM(decode(to_char(first_time, 'hh24'),'06',1,0)),1,3) as "h06",
substr(SUM(decode(to_char(first_time, 'hh24'),'07',1,0)),1,3) as "h07",
substr(SUM(decode(to_char(first_time, 'hh24'),'08',1,0)),1,3) as "h08",
substr(SUM(decode(to_char(first_time, 'hh24'),'09',1,0)),1,3) as "h09",
substr(SUM(decode(to_char(first_time, 'hh24'),'10',1,0)),1,3) as "h10",
substr(SUM(decode(to_char(first_time, 'hh24'),'11',1,0)),1,3) as "h11",
substr(SUM(decode(to_char(first_time, 'hh24'),'12',1,0)),1,3) as "h12",
substr(SUM(decode(to_char(first_time, 'hh24'),'13',1,0)),1,3) as "h13",
substr(SUM(decode(to_char(first_time, 'hh24'),'14',1,0)),1,3) as "h14",
substr(SUM(decode(to_char(first_time, 'hh24'),'15',1,0)),1,3) as "h15",
substr(SUM(decode(to_char(first_time, 'hh24'),'16',1,0)),1,3) as "h16",
substr(SUM(decode(to_char(first_time, 'hh24'),'17',1,0)),1,3) as "h17",
substr(SUM(decode(to_char(first_time, 'hh24'),'18',1,0)),1,3) as "h18",
substr(SUM(decode(to_char(first_time, 'hh24'),'19',1,0)),1,3) as "h19",
substr(SUM(decode(to_char(first_time, 'hh24'),'20',1,0)),1,3) as "h20",
substr(SUM(decode(to_char(first_time, 'hh24'),'21',1,0)),1,3) as "h21",
substr(SUM(decode(to_char(first_time, 'hh24'),'22',1,0)),1,3) as "h22",
substr(SUM(decode(to_char(first_time, 'hh24'),'23',1,0)),1,3) as "h23"
FROM  V\$log_history
where FIRST_TIME > (sysdate-5)
group by trunc(first_time), to_char(first_time, 'Dy')
Order by 1;
    
exit
EOF
     ;;
tsqt)
  sqlplus -s "$SQLPLUS_CMD" << EOF
    set lines 200 pages 2000
col ownr format a20         justify c heading 'Owner'
col name format a20         justify c heading 'Tablespace' trunc
col qota format a12         justify c heading 'Quota (MB)'
col used format 999,999,990 justify c heading 'Used (MB)'
select
  username          ownr,
  tablespace_name   name,
  decode(greatest(max_bytes, -1),
    -1, 'Unrestricted',
    to_char(max_bytes/1024/1024, '999,999,990')
  )                 qota,
  bytes/1024/1024        used
from
  dba_ts_quotas
where
  max_bytes!=0
    or
  bytes!=0
order by  1,2 ;
exit
EOF
     ;;
*)
     echo
     echo "Usage:";
     echo "  ora keyword [value1 [value2]] ";
     echo "  -----------------------------------------------------------------";
     echo "  active                      --- Get Active Session";
     echo "  asm                         --- ASM status";
     echo "  datafile   tsname           --- List data files by tablespace";
     echo "  ddl  object_type owner name --- get the create object sql";
     echo "  depend     objname [owner]  --- Get dependency information";
     echo "  desc       tabname [owner]  --- Describe Table Structure";
     echo "  difplan                     --* List the sql plan had been change";
     echo "  event                       --- List all wait event";
     echo "  frag                        --- get high water stage";
     echo "  get_kill_sh sql_id          --- Get kill OS spid of sql_id and username";
     echo "  grant      objname [owner]  --- Get grant information";
     echo "  hcost                       --- Get session info of high cost";
     echo "  highpara                    --- get hight pararllel module";
     echo "  hold       objectid         --- Who have lock on given object_id";
     echo "  hplan      sql_id           --- List sql explan infor in library cache currently";
     echo "  hplan_hist [sql_id] [n]     --- List sql explan infor in n days";
     echo "  idxdesc    tabname owner    --- Display index structure";
     echo "  invalid    [owner]          --- List invalid objects";
     echo "  ipstat     indname owner    --- Get index partition statistics";
     echo "  istat      tabname owner    --- Get index statistics";
     echo "  ke         [event#]         --- kill event#";
     echo "  latch      latch#           --- Get latch name by latch id";
     echo "  lock       [sid]            --- Get lock information by sid";
     echo "  lockholder                  --- List lockholder";
     echo "  lockwait                    --- Get lock requestor/blocker";
     echo "  log                         --* tail alert*.log";
     echo "  longops                     -- Get long run query";
     echo "  user                        --- List account status";
     echo "  memory                      --- List memory status";
     echo "  objlike    pattern [owner]  -- Get object by name pattern";
     echo "  objsql     objname owner    -- Get SQLs by object name";
     echo "  param      pattern          -- List Oracle parameters";
     echo "  parttab    owner tabname    -- Get partition_table column";
     echo "  plan       SQL_ID           -- Get Execute Plan by SQL_ID";
     echo "  _param     pattern          -- List Oracle hidden parameters";
     echo "  res cpu    n                -- get top top_value process of consume by cpu";
     echo "  res io     n                -- get top top_value process of consume by io";
     echo "  res buff   n                -- get top top_value process of consume by io";
     echo "  res mem    v                -- get process of consume pga_memery than mem_value v";
     echo "  res drgee  v                -- get process of parallel than degree_value v";
     echo "  res all    n                -- get top top_value process of sum consume by resource";
     echo "  segment    [size]           -- Segment large than given size";
     echo "  seqlike    pattern [owner]  -- Get sequence by name pattern";
     echo "  si                          --- Login as OS User";
     echo "  size       tabname [owner]  --- Get Size of tables/indexes";
     echo "  sort                        --- which session is running sort operation";
     echo "  sqltext    SQL_ID           -- Get SQL Text by hash value";
     echo "  tsfree     [tsname]         -- Get Tablespace Usage";
     echo "  libpin                      --- get library lock&pin status";
     echo "  tablespace                  --- Tablespace Information";
     echo "  tablike    pattern [owner]  -- Get table by name pattern";
     echo "  tstat      tabname owner    -- Get table statistics";
     echo "  tran                        --- Get all the transactions";
     echo "  tsqt                        --- Show all user quota";
     echo "  tabpart    tabname [owner]  -- List table partitions";
     echo "  tsql       hours            -- Get top5 sql for the last n hours";
     echo "  temp                        --- Get the temp tbs status";
     echo "  undo                        --- get undo status detail";
     echo "  redo                        --- get redo status";
     echo "  unusable   [owner]          --- List unusable indexes";
     echo "  view       pattern [owner]  --- List view by name pattern";
     echo "  ----------------------------------------------------------------";
     echo
     ;;
esac

你可能感兴趣的:(oracle)