美文网首页oracle
数据库常用SQL脚本[dbascripts]

数据库常用SQL脚本[dbascripts]

作者: 番茄人 | 来源:发表于2019-07-29 15:57 被阅读0次

    一、等待事件

    在诊断和优化Oracle,查看等待事件时,经常需要用到的查询SQL:

    1. wait.sql

    查看当前所有的等待事件:

    set linesize 180;
    set pagesize 200;
    select * from (select event,count(*) from v$session_wait group by event) order by 2 ;
    
    EVENT                                                              COUNT(*)
    ---------------------------------------------------------------- ----------
    db file scattered read                                                    1
    Streams AQ: qmn coordinator idle wait                                     1
    Streams AQ: waiting for time management or cleanup tasks                  1
    VKTM Logical Idle Wait                                                    1
    SQL*Net message to client                                                 1
    Streams AQ: qmn slave idle wait                                           1
    pmon timer                                                                1
    smon timer                                                                1
    db file sequential read                                                   2
    DIAG idle wait                                                            2
    Space Manager: slave idle wait                                            4
    rdbms ipc message                                                        17
    enq: TX - row lock contention                                            20
    SQL*Net message from client                                             828
    
    2. waitdetail.sql

    根据等待事件,查看具体的sql_id,username等信息

    set linesize 2000;
    set pagesize 200;
    col machine format a15; 
    col PROGRAM format a33;
    col username format a10;
    select a.sid,
           a.serial#,
           a.username,
           a.machine,
           a.program,
           a.sql_id,
           a.blocking_session,
           b.spid
      from v$session a, v$process b
     where a.paddr = b.addr
       and a.event like '%&wait_name%'
    
    3. detail.sql

    查看指定sid的详细会话信息

    set linesize 2000;
    set pagesize 200;
    col machine format a15;
    col PROGRAM format a33;
    col username format a10;
    col spid format a10;
    col event format a30;
    select a.sid,
           a.serial#,
           a.username,
           a.machine,
           a.program,
           b.spid,
           a.sql_id,
           a.event
      from v$session a, v$process b
     where a.paddr = b.addr
       and a.sid = &sid;
    
    4. sqlbypid.sql

    查看指定spid进程的具体文本内容

    -- view sql text by OS Process ID
    set linesize 2000
    select a.sid,a.serial#,a.username,c.sql_text
    from v$session a, v$process b, v$sqlarea c
    where a.paddr=b.addr
    and a.sql_id = c.sql_id
    and b.spid='&spid';
    
    5. sqlbysid.sql

    查看指定sid会话的具体文本内容

    set linesize 2000;
    select /*+ ordered */
     sql_text
      from v$sqltext a
     where (a.hash_value, a.address) in
           (select decode(sql_hash_value, 0, prev_hash_value, sql_hash_value),
                   decode(sql_hash_value, 0, prev_sql_addr, sql_address)
              from v$session b
             where b.sid = &sid)
     order by piece asc;
    
    6. sqlbyid.sql

    查看指定sql_id的具体文本内容

     set linesize 2000; 
     set pagesize 200; 
    SELECT SQL_TEXT FROM V$SQLTEXT WHERE SQL_ID = '&sqlid' order by piece; 
    
    7. kill_session.sql

    杀掉指定SQL_ID的会话

    -- kill the  special userame SQL statement;
    set linesize 2000
    set pagesize 200;
    select 'alter system kill session '''||sid||','||serial#||''';' from v$session where status='ACTIVE' and username='&USERNAME'  and  sql_id='&sqlid';
    
    8. kill_process.sql

    找出指定SQL的进程

    -- kill the  special userame SQL PROCESS;
    set linesize 2000
    set pagesize 200;
    select 'kill -9 '||spid from v$process p,v$session s where p.addr=s.paddr and s.username='&USERNAME' and s.sql_id='&SQL_ID' ;
    

    生成批量杀process进程

    --event事件进程
    select 'ps -ef |grep '||to_char(spid)||'|grep -v grep'||'|grep LOCAL=NO|awk ''{print $2}''|xargs kill -9;' kill_sh
            from  v$process p,v$session s
          where  s.paddr=p.addr
             and  type='USER'
             and  s.event='enq: TX - row lock contention';
    
    --用户相关进程
    select 'ps -ef |grep '||to_char(spid)||'|grep -v grep'||'|grep LOCAL=NO|awk ''{print $2}''|xargs kill -9;' kill_sh
            from  v$process p,v$session s
          where  s.paddr=p.addr
             and  type='USER'
             and  s.username=upper('&username');
    
    9. block.sql

    查看是否有锁阻塞[10G版本无法查询]

    col wait_event_text format a30;
    select b.sid,
           sess_serial#,
           wait_event_text,
           s.sql_id,
           blocker_instance_id block_inst,
           blocker_sid block_sid,
           blocker_sess_serial# block_serial#
      from v$session_blockers b, v$session s
     where b.sid = s.sid;
    
    10. lock.sql
    set linesize 2000;
    set pagesize 200;
    col username format a10;
    col objname format a30;
    select a.oracle_username username,c.object_name objname,a.session_id,b.serial#,b.status,
    DECODE (a.locked_mode,
                   0, 'none',
                   1, 'null',
                   2, 'row-s(SS)',
                   3, 'row-x(SX)',
                   4, 'share(S)',
                   5, 'S/ROW(SSX)',
                   6, 'exclusive(X)'
                  ) as lock_mode,
     b.logon_time
    from v$locked_object a,v$session b,dba_objects c
    where a.session_id = b.sid
    and a.object_id=c.object_id
    order by b.logon_time;
    
    # 或者
    select a.oracle_username username,
           c.object_name objname,
           a.session_id,
           b.serial#,
           b.status,
           a.locked_mode,
           b.logon_time
      from v$locked_object a, v$session b, dba_objects c
     where a.session_id = b.sid
       and a.object_id = c.object_id
     order by b.logon_time;
    
    10. high_cpu.sql

    查看最消耗CPU资源的会话

    set linesize 2000;
    set pagesize 200;
    SELECT s.sid,
           s.serial#,
           s.username,
           p.spid as "OS PID",
           s.module,
           st.value / 100 as "CPU sec"
      FROM v$sesstat st, v$statname sn, v$session s, v$process p
     WHERE sn.name = 'CPU used by this session' -- CPU
       AND st.statistic# = sn.statistic#
       AND st.sid = s.sid
       AND s.paddr = p.addr
       AND s.last_call_et < 1800 -- active within last 1/2 hour
       AND s.logon_time > (SYSDATE - 40 / 1440) -- sessions logged on within 4 hours
     ORDER BY st.value desc;
    

    查看长事务:

    set linesize 2000;
    set pagesize 200;
    select sid,
           sql_id,
           to_char(start_time, 'yyyy-mm-dd hh24:mi:ss'),
           elapsed_seconds,
           time_remaining,
           to_char(last_update_time, 'yyyy-mm-dd hh24:mi:ss'),
           sofar,
           totalwork,
           sofar / totalwork * 100 percent
      from v$session_longops
     where start_time > trunc(sysdate)
       and sofar <> totalwork
     order by to_char(start_time, 'yyyy-mm-dd hh24:mi:ss') asc;
    

    查看指定sid的trace文件

    set linesize 2000;
    set pagesize 200;
    SELECT    d.VALUE
           || '/'
           || LOWER (RTRIM (i.value, CHR (0)))
           || '_ora_'
           || p.spid
           || '.trc' trace_file_name
      FROM (SELECT p.spid
              FROM  v$session s, v$process p
             WHERE  p.addr = s.paddr and s.sid=&SID) p,
           (select value from v$parameter where name like '%instance_name%') i,
           (SELECT VALUE
              FROM v$parameter
             WHERE NAME = 'user_dump_dest') d;
    

    二、ASH(v$active_session_history)

    转载: https://blog.csdn.net/u012457058/article/details/41015685

    查询过去30分钟数据库引起最多等待的sql语句

    select ash.USER_ID,
           u.username,
           sum(ash.WAIT_TIME) Total_wait_time,
           s.SQL_TEXT
      from v$active_session_history ash, v$sqlarea s, dba_users u
     where ash.SAMPLE_TIME between sysdate - 5 / 1440 and sysdate
       and ash.SQL_ID = s.SQL_ID
       and ash.USER_ID = u.user_id
     group by ash.USER_ID, s.SQL_TEXT, u.username
     order by Total_wait_time desc;
    

    查询数据库等待时间和实际执行时间的相对百分比

    select *
      from v$sysmetric a
     where a.METRIC_NAME in
           ('Database CPU Time Ratio', 'Database Wait Time Ratio')
       and a.INTSIZE_CSEC = (select max(intsize_csec) from v$sysmetric);
    
    BEGIN_TIM END_TIME  INTSIZE_CSEC   GROUP_ID  METRIC_ID METRIC_NAME                                                           VALUE METRIC_UNIT
    --------- --------- ------------ ---------- ---------- ---------------------------------------------------------------- ---------- -------------------------
    29-JUL-19 29-JUL-19         5934          2       2107 Database Wait Time Ratio                                         2.68703104 % Wait/DB_Time
    29-JUL-19 29-JUL-19         5934          2       2108 Database CPU Time Ratio                                           97.312969 % Cpu/DB_Time
    

    查询数据库过去30分钟最重要的等待事件

    select ash.EVENT, sum(ash.WAIT_TIME + ash.TIME_WAITED) total_wait_time
      from v$active_session_history ash
     where ash.SAMPLE_TIME between sysdate - 30 /1440 and sysdate
     group by event
     order by total_wait_time desc;
    
    EVENT                                              TOTAL_WAIT_TIME
    -------------------------------------------------- ---------------
                                                             396207630
    enq: TX - row lock contention                             46809568
    log file sync                                              6769778
    db file sequential read                                    6377617
    log file parallel write                                    2527106
    db file scattered read                                     1124571
    SQL*Net more data to client                                1024698
    direct path read                                            891071
    db file async I/O submit                                    372107
    read by other session                                       342093
    cursor: pin S wait on X                                     229911
    enq: KO - fast object checkpoint                            188481
    db file parallel read                                       102070
    direct path write                                            75884
    control file parallel write                                  57762
    os thread startup                                            37215
    SQL*Net message to client                                    33843
    recovery area: computing obsolete files                      11290
    library cache load lock                                       4922
    latch: cache buffers chains                                   3518
    reliable message                                              1421
    SQL*Net more data from client                                  306
    

    在过去30分钟哪些用户经历了等待

    select s.SID,
           s.USERNAME,
           sum(ash.WAIT_TIME + ash.TIME_WAITED) total_wait_time
      from v$active_session_history ash, v$session s
     where ash.SAMPLE_TIME between sysdate - 30/1440 and sysdate
       and ash.SESSION_ID = s.SID
     group by s.SID, s.USERNAME
     order by total_wait_time desc;
    

    查询等待时间最长的对象

    select a.CURRENT_OBJ#,
           d.object_name,
           d.object_type,
           a.EVENT,
           sum(a.WAIT_TIME + a.TIME_WAITED) total_wait_time
      from v$active_session_history a, dba_objects d
     where a.SAMPLE_TIME between sysdate - 30/1440 and sysdate
       and a.CURRENT_OBJ# = d.object_id
     group by a.CURRENT_OBJ#, d.object_name, d.object_type, a.EVENT
     order by total_wait_time desc;
    

    查询过去30分钟等待时间最长的sql语句

    select a.USER_ID,
           u.username,
           s.SQL_TEXT,
           sum(a.WAIT_TIME + a.TIME_WAITED) total_wait_time
      from v$active_session_history a, v$sqlarea s, dba_users u
     where a.SAMPLE_TIME between sysdate - 30/1440 and sysdate
       and a.SQL_ID = s.SQL_ID
       and a.USER_ID = u.user_id
     group by a.USER_ID, s.SQL_TEXT, u.username
     order by total_wait_time desc;
    

    查看哪些会话正在等待IO资源

    SELECT username, program, machine, sql_id
      FROM V$SESSION
     WHERE EVENT LIKE 'db file%read';
    

    查看正在等待IO资源的对象

    select d.object_name, d.object_type, d.owner
      from v$session s, dba_objects d
     where event like 'db file%read'
       and s.row_wait_obj# = d.object_id;
    

    三、常用数据库对象SQL

    查看ddl语句
    set linesize 2000;
    set pagesize 200;
    set long 9999;
    SELECT   dbms_metadata.get_ddl(upper('&obj_type'),upper('&obj_name'),upper('&schema')) from dual;
    
    查看对象信息
    col object_name format a40
    select owner,object_name,OBJECT_TYPE,status,LAST_DDL_TIME from dba_objects where object_name like upper('%&objname%');
    
    查看绑定变量值
    col VALUE_STRING format a35;
    col name format a20;
    select t.HASH_VALUE,
           t.SQL_ID,
           t.NAME,
           t.LAST_CAPTURED,
           t.WAS_CAPTURED,
           t.VALUE_STRING     
      from v$sql_bind_capture t
     where sql_id ='&sql_id'  and VALUE_STRING is not null
    
    查看SQL的执行计划
    select * from table(dbms_xplan.display_cursor('&sql_id',null,'advanced'));
    
    查看对象的依赖
    --view dependent object
    set linesize 2000;
    set pagesize 200;
    col owner format a10
    col referenced_owner format a10
    col REFERENCED_NAME format a30
    col REFERENCED_LINK_NAME format a10
    col REFERENCED_TYPE format a10
    select t.* from dba_dependencies t,dba_objects m where t.name=m.object_name
             and t.referenced_name = upper('&objname')
             and m.object_type in ('PROCEDURE','VIEW','FUNCTION','PACKAGE','SYNONYNM')
             and m.status='VALID'
         order by T.OWNER,T.type;
    
    查看表的索引信息
    set linesize 2000;
    set pagesize 200;
    col owner format a12;
    col tabname format a20;
    col indname format a30;
    col colname  format a20;
    Select a.table_owner     owner,
           a.table_name      tabname,
           a.index_name      indname,
           a.status          status,
           b.column_name     colname,
           b.COLUMN_POSITION col_posi
      from dba_indexes a, dba_ind_columns b
     where a.index_name = b.index_name
       and a.table_name = upper('&tabname')
     order by indname, col_posi;
    
    # 查询索引表空间,用户,状态、分区等信息
    select owner,
           index_name,
           index_type,
           table_owner,
           table_name,
           table_type,
           tablespace_name,
           status,
           PARTITIONED
      from dba_indexes
    where owner||'.'||index_name='&owner.index_name';
    
    # 查询索引字段
    col index_owner for a10;
    col column_name for a20;
    select index_owner,
           index_name,
           table_owner,
           table_name,
           column_name,
           COLUMN_POSITION
      from dba_ind_columns
     where index_name = '&indexname';
    
    查看分区表信息
    select TABLE_OWNER,
           TABLE_NAME,
           PARTITION_NAME,
           HIGH_VALUE,
           NUM_ROWS,
           LAST_ANALYZED
      from dba_tab_partitions
     where table_owner like upper('%&owner%')
       and TABLE_NAME like upper('%&tab_name%')
     order by 3;
    
    查看同义词
    col owner format a25;
    col synonym_name format a25;
    col table_owner format a25;
    col table_name format a25;
    col db_link format a25;
    select owner, synonym_name, table_owner, table_name, db_link 
    from dba_synonyms 
    where  synonym_name like upper('%&objname%');
    
    查看dba_jobs
    set linesize 2000;
    set pagesize 200;
    col SCHEMA_USER format a15
    col what format a30
    col next_date format a20
    col interval format a30
    select job,
           SCHEMA_USER,
           what,
           to_char(LAST_DATE, 'yyyymmddhh24miss') last_date,
           to_char(next_date, 'yyyymmddhh24miss') next_date,
           interval,
           broken
      from dba_jobs
     where what like '%&what%'
     order by SCHEMA_USER;
    
    查看过程(proc)的内容
    select text from dba_source where owner like upper('%&owner%') and name like upper('%&name%') order by line;
    
    查看表dml的信息
    select table_owner, table_name, inserts, updates, deletes, timestamp
      from dba_tab_modifications
     where table_name like upper('%&tabname%')
     order by timestamp desc;
    

    四、其他

    查询所有实例的会话信息 (按主机,数据库账号,程序汇总RAC的连接数)
    select inst_id, username, machine, program, count(*)
      from gv$session
     group by inst_id, username, machine, program
    having count(*) > 10
     order by 4;
    
    按小时查看归档日志个数
    set linesize 300 pagesize 10000
    col Date for a10
    col Day for a10
    col Total for 99999
    col "h00" for a10
    col "h01" for a10
    col "h02" for a10
    col "h03" for a10
    col "h04" for a10
    col "h05" for a10
    col "h06" for a10
    col "h07" for a10
    col "h08" for a10
    col "h09" for a10
    col "h10" for a10
    col "h11" for a10
    col "h12" for a10
    col "h13" for a10
    col "h14" for a10
    col "h15" for a10
    col "h16" for a10
    col "h17" for a10
    col "h18" for a10
    col "h19" for a10
    col "h20" for a10
    col "h21" for a10
    col "h22" for a10
    col "h23" for a10
    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
    group by trunc(first_time), to_char(first_time, 'Dy')
    Order by 1;
    

    相关文章

      网友评论

        本文标题:数据库常用SQL脚本[dbascripts]

        本文链接:https://www.haomeiwen.com/subject/mopvrctx.html