DBA常用Sql语句--留着给自己看

查看表空间的名称及大小:

SQL>select t.tablespace_name,round(sum(bytes/(1024*1024)),0) ts_size

from dba_tablespaces t, dba_data_files dwhere t.tablespace_name = d.tablespace_name group by t.tablespace_name;

 

查看表空间物理文件的名称及大小:

SQL>select tablespace_name, file_id,file_name,round(bytes/(1024*1024),0) total_space from dba_data_files order bytablespace_name;

 

查看回滚段名称及大小:

SQL>select segment_name,tablespace_name, r.status,

(initial_extent/1024)InitialExtent,(next_extent/1024) NextExtent,

max_extents, v.curext CurExtent Fromdba_rollback_segs r, v$rollstat v

Where r.segment_id = v.usn(+) order bysegment_name;

 

如何查看某个回滚段里面,跑的什么事物或者正在执行什么sql语句:

SQL>select d.sql_text,a.name
from v$rollname a,v$transaction b,v$session c,v$sqltext d
where a.usn=b.xidusn and b.addr=c.taddr and c.sql_address=
d.address and c.sql_hash_value=d.hash_value
and a.usn=1;

(备注:你要看哪个,就把usn=?写成几就行了)

 

查看控制文件:

SQL>select * from v$controlfile;

 

查看日志文件:

SQL> col member format a50

SQL>select * from v$logfile;

 

如何查看当前SQL*PLUS用户的sid和serial#:

SQL>select sid, serial#, status fromv$session where audsid=userenv('sessionid');

 

如何查看当前数据库的字符集: 

SQL>select userenv('language') fromdual;

SQL>select userenv('lang') from dual;

 

怎么判断当前正在使用何种SQL优化方式:

用explain plan产生EXPLAIN PLAN,检查PLAN_TABLE中ID=0的POSITION列的值。

SQL>selectdecode(nvl(position,-1),-1,'RBO',1,'CBO') from plan_table where id=0;

 

如何查看系统当前最新的SCN号:

SQL>select max(ktuxescnw * power(2,32) +ktuxescnb) from x$ktuxe;

 

 

在ORACLE中查找TRACE文件的脚本:

SQL>select u_dump.value || '/' ||instance.value || '_ora_' ||

v$process.spid ||nvl2(v$process.traceid,  '_' || v$process.traceid, null ) ||'.trc'"Trace File" from v$parameter u_dump cross join v$parameterinstance cross join v$process join v$session on v$process.addr =v$session.paddr where u_dump.name = 'user_dump_dest' and

instance.name = 'instance_name' andv$session.audsid=sys_context('userenv','sessionid');

 

SQL>select d.value || '/ora_' || p.spid|| '.trc' trace_file_name
from (select p.spid from sys.v_$mystat m,sys.v_$session s,
sys.v_$process p where m.statistic# = 1 and
s.sid = m.sid and p.addr = s.paddr) p,(select value from sys.v_$parameter wherename ='user_dump_dest') d;

 

如何查看客户端登陆的IP地址:

SQL>selectsys_context('userenv','ip_address') from dual;

 

如何在生产数据库中创建一个追踪客户端IP地址的触发器:

SQL>create or replace trigger on_logon_trigger

after logon on database

begin

 dbms_application_info.set_client_info(sys_context('userenv', 'ip_address'));

end;

 

查询当前日期:

SQL> selectto_char(sysdate,'yyyy-mm-dd,hh24:mi:ss') from dual;

 

查看所有表空间对应的数据文件名:

SQL>select distinctfile_name,tablespace_name,AUTOEXTENSIBLE from dba_data_files;

 

查看表空间的使用情况:

SQL>select sum(bytes)/(1024*1024) asfree_space,tablespace_name

from dba_free_space group bytablespace_name;

 

SQL>SELECT A.TABLESPACE_NAME,A.BYTESTOTAL,B.BYTES USED, C.BYTES FREE,

(B.BYTES*100)/A.BYTES "%USED",(C.BYTES*100)/A.BYTES "% FREE"

FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_USEDB,SYS.SM$TS_FREE C

WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAMEAND A.TABLESPACE_NAME=C.TABLESPACE_NAME;

 

SQL>column tablespace_name format a18;
SQL>column Sum_M format a12;
SQL>column Used_M format a12;
SQL>column Free_M format a12;
column pto_M format 9.99;
SQL>select s.tablespace_name,ceil(sum(s.bytes/1024/1024))||'M'Sum_M,ceil(sum(s.UsedSpace/1024/1024))||'M'Used_M,ceil(sum(s.FreeSpace/1024/1024))||'M' Free_M, sum(s.UsedSpace)/sum(s.bytes)PTUSED

from (selectb.file_id,b.tablespace_name,b.bytes,
(b.bytes-sum(nvl(a.bytes,0))) UsedSpace,
sum(nvl(a.bytes,0)) FreeSpace,(sum(nvl(a.bytes,0))/(b.bytes)) * 100FreePercentRatio from sys.dba_free_space a,sys.dba_data_files b
where a.file_id(+)=b.file_id group by b.file_id,b.tablespace_name,b.bytes
order by b.tablespace_name) s group by s.tablespace_name order bysum(s.FreeSpace)/sum(s.bytes) desc;

 

查看数据文件的hwm(可以resize的最小空间)和文件头大小:

SQL>SELECT v1.file_name,v1.file_id,
num1 totle_space,
num3 free_space,
num1-num3 "USED_SPACE(HWM)",
nvl(num2,0) data_space,
num1-num3-nvl(num2,0) file_head
FROM
(SELECT file_name,file_id,SUM(bytes) num1 FROM Dba_Data_Files GROUP BYfile_name,file_id) v1,
(SELECT file_id,SUM(bytes) num2 FROM dba_extents GROUP BY file_id) v2,
(SELECT file_id,SUM(BYTES) num3 FROM DBA_FREE_SPACE GROUP BY file_id) v3
WHERE v1.file_id=v2.file_id(+)
AND v1.file_id=v3.file_id(+);

 

查看数据文件大小及头大小:

SQL>SELECT v1.file_name,v1.file_id,
num1 totle_space,
num3 free_space,
num1-num3 Used_space,
nvl(num2,0) data_space,
num1-num3-nvl(num2,0) file_head
FROM
(SELECT file_name,file_id,SUM(bytes) num1 FROM Dba_Data_Files GROUP BYfile_name,file_id) v1,
(SELECT file_id,SUM(bytes) num2 FROM dba_extents GROUP BY file_id) v2,
(SELECT file_id,SUM(BYTES) num3 FROM DBA_FREE_SPACE GROUP BY file_id) v3
WHERE v1.file_id=v2.file_id(+)
AND v1.file_id=v3.file_id(+);

(运行以上查询,我们可以如下信息:
Totle_pace:该数据文件的总大小,字节为单位
Free_space:该数据文件的剩于大小,字节为单位
Used_space:该数据文件的已用空间,字节为单位
Data_space:该数据文件中段数据占用空间,也就是数据空间,字节为单位
File_Head:该数据文件头部占用空间,字节为单位)

 

数据库各个表空间增长情况的检查:

SQL>selectA.tablespace_name,(1-(A.total)/B.total)*100 used_percent

From (select tablespace_name,sum(bytes)total from dba_free_space group by tablespace_name) A,(selecttablespace_name,sum(bytes) total  from dba_data_files group bytablespace_name) B where A.tablespace_name=B.tablespace_name;

 

SQL>SELECT UPPER(F.TABLESPACE_NAME)"表空间名",
D.TOT_GROOTTE_MB "表空间大小(M)",
       D.TOT_GROOTTE_MB - F.TOTAL_BYTES "已使用空间(M)",TO_CHAR(ROUND((D.TOT_GROOTTE_MB - F.TOTAL_BYTES) / D.TOT_GROOTTE_MB * 100, 2),'990.99') "使用比",F.TOTAL_BYTES "空闲空间(M)",
       F.MAX_BYTES "最大块(M)"  FROM (SELECTTABLESPACE_NAME,
ROUND(SUM(BYTES) / (1024 * 1024), 2) TOTAL_BYTES,
ROUND(MAX(BYTES) / (1024 * 1024), 2) MAX_BYTES
FROM SYS.DBA_FREE_SPACE GROUP BY TABLESPACE_NAME) F,
       (SELECTDD.TABLESPACE_NAME,ROUND(SUM(DD.BYTES) / (1024 * 1024), 2) TOT_GROOTTE_MB FROM SYS.DBA_DATA_FILESDD
 GROUP BY DD.TABLESPACE_NAME) D WHERE D.TABLESPACE_NAME =F.TABLESPACE_NAME

ORDER BY 4 DESC;

 

查看各个表空间占用磁盘情况: 
SQL>col tablespace_name format a20;
SQL>select  b.file_id  file_ID,
b.tablespace_name  tablespace_name,
b.bytes  Bytes,
(b.bytes-sum(nvl(a.bytes,0)))  used,
 sum(nvl(a.bytes,0))  free,
 sum(nvl(a.bytes,0))/(b.bytes)*100 Percent
     from dba_free_space a,dba_data_files b 
     where a.file_id=b.file_id 
     group by b.tablespace_name,b.file_id,b.bytes 
     order by b.file_id;

 

数据库对象下一扩展与表空间的free扩展值的检查:

SQL>select a.table_name, a.next_extent,a.tablespace_name

from all_tables a,(select tablespace_name,max(bytes) as big_chunk

from dba_free_space group bytablespace_name ) f where f.tablespace_name = a.tablespace_name anda.next_extent > f.big_chunk

union select a.index_name, a.next_extent,a.tablespace_name

from all_indexes a,(select tablespace_name,max(bytes) as big_chunk

from dba_free_space group bytablespace_name ) f where f.tablespace_name = a.tablespace_name anda.next_extent > f.big_chunk;

 

Disk Read最高的SQL语句的获取:

SQL>select sql_text from (select * fromv$sqlarea order by disk_reads)

where rownum<=5;

 

查找前十条性能差的sql:

SQL>SELECT * FROM  (SELECTPARSING_USER_ID
 EXECUTIONS,SORTS,COMMAND_TYPE,DISK_READS,
sql_text FROM  v$sqlarea ORDER BY disk_reads DESC) 
 WHERE ROWNUM<10 ;

 

等待时间最多的5个系统等待事件的获取:

SQL>select * from (select * fromv$system_event where event not like 'SQL%' order by total_waits desc) whererownum<=5;

 

查看当前等待事件的会话:

SQL>col username format a10

SQL>set line 120

SQL>col EVENT format a30

SQL>select SE.Sid,s.Username,SE.Event,se.Total_Waits,SE.Time_Waited,SE.Average_Wait

from v$session S,v$session_event SE whereS.Username is not null and SE.Sid=S.Sid

and S.Status='ACTIVE' and SE.Event not like'%SQL*Net%';

 

SQL>select sid, event, p1, p2, p3,wait_time, seconds_in_wait, state from v$session_wait where event not like'%message%' and event not like 'SQL*Net%' and event not like '%timer%' andevent != 'wakeup time manager';

 

找到与所连接的会话有关的当前等待事件:

SQL>selectSW.Sid,S.Username,SW.Event,SW.Wait_Time,SW.State,SW.Seconds_In_Wait SEC_IN_WAIT

from v$session S,v$session_wait SW whereS.Username is not null and SW.Sid=S.Sid

and SW.event not like '%SQL*Net%' order bySW.Wait_Time Desc;

 

Oracle所有回滚段状态的检查:

SQL>select segment_name,owner,tablespace_name,initial_extent,next_extent,dba_rollback_segs.statusfrom dba_rollback_segs,v$datafile where file_id=file#;

 

Oracle回滚段扩展信息的检查:

SQL>col name format a10

SQL>set linesize140        

SQL>select substr(name,1,40)name,extents,rssize,optsize,aveactive,extends,wraps,shrinks,hwmsize

from v$rollname rn,v$rollstat rs where(rn.usn=rs.usn);
 

extents:回滚段中的盘区数量。

Rssize:以字节为单位的回滚段的尺寸。

optsize:为optimal参数设定的值。

Aveactive:从回滚段中删除盘区时释放的以字节为单位的平均空间的大小。

Extends:系统为回滚段增加的盘区的次数。

Shrinks:系统从回滚段中清除盘区(即回滚段收缩)的次数。回滚段每次清除盘区时,系统可能会从这个回滚段中消除一个或多个盘区。

Hwmsize:回滚段尺寸的上限,即回滚段曾经达到的最大尺寸。

(如果回滚段平均尺寸接近OPTIMAL的值,那么说明OPTIMAL的值设置正确,如果回滚段动态增长次数或收缩次数很高,那么需要提高OPTIMAL的值)

 

查看回滚段的使用情况,哪个用户正在使用回滚段的资源:

SQL>select s.username, u.name from v$transactiont,v$rollstat r,
v$rollname u,v$session s where s.taddr=t.addr and
t.xidusn=r.usn and r.usn=u.usn order by s.username;

 

 

如何查看一下某个shared_server正在忙什么:

SQL>SELECTa.username,a.machine,a.program,a.sid,
a.serial#,a.status,c.piece,c.sql_text
FROM v$session a,v$process b,v$sqltext c
WHERE b.spid=13161 AND b.addr=a.paddr
AND a.sql_address=c.address(+) ORDER BY c.piece; 

 

数据库共享池性能检查:

SQL>Selectnamespace,gets,gethitratio,pins,pinhitratio,reloads,

Invalidations from v$librarycache wherenamespace in

('SQLAREA','TABLE/PROCEDURE','BODY','TRIGGER');

 

检查数据重载比率:

SQL>select sum(reloads)/sum(pins)*100"reload ratio" from

v$librarycache;

 

检查数据字典的命中率:

SQL>select 1-sum(getmisses)/sum(gets)"data dictionary hit

ratio" from v$rowcache;

(对于library cache, gethitratio和pinhitratio应该大于90%,对于数据重载比率,reloadratio应该小于1%,对于数据字典的命中率,data dictionary hit ratio应该大于85%)

 

检查共享内存的剩余情况:

SQL>select request_misses,request_failures from v$shared_pool_reserved; 

(对于共享内存的剩余情况, request_misses 和request_failures应该接近0)

 

数据高速缓冲区性能检查:

SQL>select 1-p.value/(b.value+c.value)"db buffer cache hit

ratio" from v$sysstat p,v$sysstatb,v$sysstat c where

p.name='physical reads' and b.name='dbblock gets' and

c.name='consistent gets';

 

检查buffer poolHIT_RATIO执行

SQL>select name,(physical_reads/(db_block_gets+consistent_gets))

"MISS_HIT_RATIO" FROMv$buffer_pool_statistics WHERE (db_block_gets+ consistent_gets)> 0;

(正常时db buffer cache hit ratio 应该大于90%,正常时buffer poolMISS_HIT_RATIO 应该小于10%)

 

数据库回滚段性能检查:

检查Ratio执行

SQL>select sum(waits)* 100 /sum(gets)"Ratio", sum(waits)

   "Waits", sum(gets)"Gets" from v$rollstat;

检查count/value执行:

SQL>select class,count from v$waitstatwhere class like '%undo%';

SQL>select value from v$sysstat wherename='consistent gets';

(两者的value值相除)

 

检查average_wait执行:

SQL>select event,total_waits,time_waited,average_waitfrom v$system_event

where event like '%undo%';

 

检查RBS headerget ratio执行:

SQL>select n.name,s.usn,s.wraps,decode(s.waits,0,1,1- s.waits/s.gets)"RBS

 header get ratio" fromv$rollstat s,v$rollname n where s.usn=n.usn;

(正常时Ratio应该小于1%,count/value应该小于0.01%,average_wait最好为0,该值越小越好,RBS header get ratio应该大于95%)

 

杀会话的脚本:

SQL>selectA.SID,B.SPID,A.SERIAL#,a.lockwait,A.USERNAME,A.OSUSER,a.logon_time,a.last_call_et/3600LAST_HOUR,A.STATUS,
'orakill '||sid||' '||spid HOST_COMMAND,
'alter system kill session '''||A.sid||','||A.SERIAL#||'''' SQL_COMMAND
from v$session A,V$PROCESS B where A.PADDR=B.ADDR AND SID>6;

 

查看排序段的性能:

SQL>SELECT name, value FROM v$sysstatWHERE name IN ('sorts (memory)', 'sorts (disk)'); 

 

查看数据库库对象:

SQL>select owner, object_type, status,count(*) count# from all_objects group by owner, object_type, status;

 

查看数据库的版本: 

SQL>Select * from v$version;

 

查看数据库的创建日期和归档方式:

SQL>Select Created, Log_Mode, Log_ModeFrom V$Database;

 

捕捉运行很久的SQL:

SQL>column username format a12

SQL>column opname format a16

SQL>column progress format a8

SQL>selectusername,sid,opname,round(sofar*100 / totalwork,0) || '%' asprogress,time_remaining,sql_text from v$session_longops , v$sql wheretime_remaining <> 0 and sql_address=address and sql_hash_value =hash_value;

 

查看数据表的参数信息:

SQL>SELECT partition_name, high_value,high_value_length, tablespace_name,pct_free, pct_used, ini_trans, max_trans,initial_extent,next_extent, min_extent, max_extent, pct_increase,FREELISTS,freelist_groups, LOGGING, BUFFER_POOL, num_rows, blocks,empty_blocks,avg_space, chain_cnt, avg_row_len, sample_size,last_analyzed FROMdba_tab_partitions
--WHERE table_name = :tname AND table_owner = :towner
ORDER BY partition_position;

 

查看还没提交的事务:

SQL>select * from v$locked_object;

SQL>select * from v$transaction;

 

查找object为哪些进程所用:

SQL>select p.spid,s.sid,s.serial#serial_num,s.username user_name,
a.type  object_type,s.osuser os_user_name,a.owner,a.objectobject_name,decode(sign(48 - command),1,
to_char(command), 'Action Code #' || to_char(command) ) action,
p.program oracle_process,s.terminal terminal,s.program program,s.statussession_status  from v$session s, v$access a, v$process p  wheres.paddr = p.addr and s.type = 'USER' and a.sid = s.sid  anda.object='SUBSCRIBER_ATTR'order by s.username, s.osuser;

 

查看回滚段:

SQL>col name format a10

SQL>set linesize 100

SQL>select rownum,sys.dba_rollback_segs.segment_name Name, v$rollstat.extents Extents,v$rollstat.rssize Size_in_Bytes, v$rollstat.xacts XActs, v$rollstat.gets Gets,v$rollstat.waits Waits, v$rollstat.writes Writes, sys.dba_rollback_segs.statusstatus from v$rollstat, sys.dba_rollback_segs, v$rollname wherev$rollname.name(+) = sys.dba_rollback_segs.segment_name and v$rollstat.usn (+)= v$rollname.usn order by rownum;

 

查看耗资源的进程(topsession):

SQL>select s.schemanameschema_name,decode(sign(48 - command), 1, to_char(command), 'Action Code #' ||to_char(command) ) action,status session_status,s.osuseros_user_name,s.sid,p.spid,s.serial# serial_num,nvl(s.username,'[Oracleprocess]') user_name,s.terminal terminal,s.program program,st.valuecriteria_value from v$sesstat st,v$session s,v$process p where st.sid = s.sidand st.statistic# = to_number('38') and  ('ALL'='ALL' or s.status ='ALL')and p.addr=s.paddr order by st.value desc,p.spid asc,s.username asc,s.osuserasc;

 

根据PID查找相应的语句:

SQL>SELECT a.username,

      a.machine,a.program,a.sid,a.serial#,a.status,c.piece,c.sql_text

  FROM v$session a,v$processb,v$sqltext c WHERE b.spid=spid

   AND b.addr=a.paddr ANDa.sql_address=c.address(+) ORDER BY c.piece;

 

根据SID找ORACLE的某个进程:

SQL> select pro.spid from v$sessionses,v$process pro where ses.sid=21 and ses.paddr=pro.addr;

 

监控当前数据库谁在运行什么SQL语句:
SQL>SELECT osuser, username, sql_text from v$session a, v$sqltext b
where a.sql_address =b.address order by address, piece;

 

如何查看数据库中某用户,正在运行什么SQL语句

SQL>SELECT SQL_TEXT FROM V$SQLTEXT T,V$SESSION S WHERE T.ADDRESS=S.SQL_ADDRESS

AND T.HASH_VALUE=S.SQL_HASH_VALUE  ANDS.MACHINE='XXXXX' OR USERNAME='WACOS';

 

如何查出前台正在发出的sql语句:

SQL> select user_name,sql_text fromv$open_cursor where sid in(select sid from (select sid,serial# from v$sessionwhere status='ACTIVE'));

 

查询当前所执行的SQL语句:

 

SQL> select program ,sql_address fromv$session where paddr in (select addr

from v$process where spid=3556);

 

PROGRAM                                         SQL_ADDRESS

----------------------------------------------------------------

sqlplus@ctc20 (TNSV1-V3)                       000000038FCB1A90

 

SQL> select sql_text from v$sqlareawhere address='000000038FCB1A90';

 

找出消耗CPU最高的进程对应的SQL语句:

SQL>set line 240

SQL>set verify off

SQL>column sid format 999

SQL>column pid format 999

SQL>column S_# format 999

SQL>column username format A9 heading"ORA User"

SQL>column program  format a29

SQL>columnSQL      format a60

SQL>COLUMN OSname format a9 Heading "OSUser"

SQL>SELECT P.pid pid,S.sid sid,P.spidspid,S.username username,

S.osuser osname,P.serial#S_#,P.terminal,P.program  program,

P.background,S.status,RTRIM(SUBSTR(a.sql_text,1, 80))  SQL

FROM v$process P, v$session S,v$sqlarea AWHERE P.addr = s.paddr

AND S.sql_address = a.address (+)  ANDP.spid LIKE '%&1%';

 

Enter value for 1: PID(这里输入占用CPU最高的进程对应的PID)

 

 

SQL>set termout off

SQL>spool maxcpu.txt

SQL>SELECT '++'||S.username username,

RTRIM(REPLACE(a.sql_text,chr(10),''))||';'FROMv$process P, v$session S,

v$sqlarea A WHERE P.addr = s.paddr ANDS.sql_address = a.address (+)

AND P.spid LIKE '%&&1%';

Enter value for 1: PID(这里输入占用CPU最高的进程对应的PID)

spool off(这句放在最后执行)

 

CPU用率最高的2条SQL语句的获取

执行:top,通过top获得CPU占用率最高的进程的pid。

SQL>select sql_text,spid,v$session.program,processfrom v$sqlarea,v$session,v$process wherev$sqlarea.address=v$session.sql_address andv$sqlarea.hash_value=v$session.sql_hash_value

and v$session.paddr=v$process.addr andv$process.spid in (pid);

 

SQL>col machine format a30
SQL>col program format a40
SQL>set line 200
SQL>select sid,serial#,username,osuser,machine,program,process,to_char(logon_time,'yyyy/mm/ddhh24:mi:ss') from v$session where paddr in(select addr from v$process wherespid in([$spid]));

 

SQL>select sql_text from v$sqltext_with_newlines
where hash_value=(select SQL_HASH_VALUE from v$session where sid=&sid)
order by piece;

 

 

查看锁(lock)情况:

SQL>select /*+ RULE */ ls.osuseros_user_name, ls.username user_name, 
decode(ls.type,'RW','Row wait enqueue lock','TM','DML enqueue lock','TX','Transactionenqueue lock','UL','User supplied lock') lock_type,o.object_nameobject,decode(ls.lmode, 1, null, 2,'Row Share',3,'RowExclusive',4,'Share',5,'Share RowExclusive',6,'Exclusive',null)lock_mode,o.owner,ls.sid,ls.serial#serial_num,ls.id1,ls.id2 from sys.dba_objects o,(selects.osuser,s.username,l.type,l.lmode,s.sid,s.serial#,l.id1,l.id2 from v$sessions,v$lock l where s.sid=l.sid)ls where o.object_id=ls.id1 ando.owner<>'SYS' order by o.owner, o.object_name;

 

SQL>select  sys.v_$session.osuser,sys.v_$session.machine,v$lock.sid,
sys.v_$session.serial#,decode(v$lock.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 CacheInvalida-tion','LS','Log Start or Switch','RW','Row Wait','SQ','SequenceNumber','TE','Extend Table','TT','Temp Table','Unknown') LockType,
rtrim(object_type) || ' ' || rtrim(owner) || '.' || object_nameobject_name,decode(lmode, 0, 'None',1, 'Null',2, 'Row-S',3, 'Row-X',4, 'Share',
5, 'S/Row-X',6, 'Exclusive','Unknown') LockMode,decode(request, 0, 'None',1,'Null',2, 'Row-S',3, 'Row-X', 4, 'Share',5, 'S/Row-X',
6, 'Exclusive', 'Unknown') RequestMode,ctime, block b
from v$lock, all_objects, sys.v_$session
where v$Lock.sid > 6
and sys.v_$session.sid = v$lock.sid
and v$lock.id1 = all_objects.object_id;

 

 

以DBA角色, 查看当前数据库里锁的情况可以用如下SQL语句:
SQL>col owner for a12
SQL>col object_name for a16
SQL>select b.owner,b.object_name,l.session_id,l.locked_mode
from v$locked_object l, dba_objects b
where b.object_id=l.object_id;

SQL>selectt2.username,t2.sid,t2.serial#,t2.logon_time
from v$locked_object t1,v$session t2
where t1.session_id=t2.sid order by t2.logon_time;

 

SQL>Select sql_address from v$sessionwhere sid=;
SQL>Select * from v$sqltext where address=;

 

SQL>select COMMAND_TYPE,PIECE,sql_textfrom v$sqltext where address=(select sql_address from v$session a wheresid=18);   

 

SQL>select object_id fromv$locked_object;

SQL>select object_name,object_type fromdba_objects where object_id=’’;

如果有长期出现的一列,可能是没有释放的锁。我们可以用下面SQL语句杀掉长期没有释放非正常的锁:
SQL>alter system kill session 'sid,serial#';

查看等待(wait)情况:

SQL>SELECTv$waitstat.class,v$waitstat.count count, SUM(v$sysstat.value) sum_value FROMv$waitstat,v$sysstat WHERE v$sysstat.name IN('db block gets','consistent gets')group by v$waitstat.class,v$waitstat.count;

查看sga情况:

SQL>SELECT NAME, BYTES FROMSYS.V_$SGASTAT ORDER BY NAME ASC;

查看catchedobject:

SQL>SELECTowner,name,db_link,namespace,type,sharable_mem,loads,             executions,locks,pins,kept FROM v$db_object_cache;
          
查看V$SQLAREA:

SQL>SELECTSQL_TEXT,SHARABLE_MEM,PERSISTENT_MEM,RUNTIME_MEM,SORTS,
VERSION_COUNT,LOADED_VERSIONS,OPEN_VERSIONS,USERS_OPENING,EXECUTIONS,
USERS_EXECUTING,LOADS,FIRST_LOAD_TIME,INVALIDATIONS,PARSE_CALLS,

DISK_READS,BUFFER_GETS,ROWS_PROCESSED FROMV$SQLAREA;
 
查看object分类数量:

selectdecode(o.type#,1,'INDEX',2,'TABLE',3,'CLUSTER',4,'VIEW',5,'SYNONYM',6,'SEQUENCE','OTHER') object_type , count(*) quantity from sys.obj$ o whereo.type# > 1 group by decode(o.type#,1,'INDEX',2,'TABLE',3,'CLUSTER',4,'VIEW',5,'SYNONYM',6,'SEQUENCE','OTHER') union select 'COLUMN', count(*)from sys.col$ union select 'DB LINK' , count(*) from all_objects;

有关connection的相关信息:

1)查看有哪些用户连接

select s.osuser os_user_name,decode(sign(48- command),1,to_char(command),
 'Action Code #' || to_char(command))action,p.program oracle_process,
status session_status,s.terminal terminal,s.programprogram,      
s.username user_name,s.fixed_table_sequence activity_meter,''query,  
0 memory,0 max_memory,0 cpu_usage,s.sid,s.serial# serial_num   
from v$session s,v$process p where s.paddr=p.addr and s.type = 'USER' 
 order by s.username, s.osuser;


2)根据v.sid查看对应连接的资源占用等情况

selectn.name,v.value,n.class,n.statistic# 
from v$statname n,v$sesstat v where v.sid=18 and v.statistic# = n.statistic#order by n.class, n.statistic#;


3)根据sid查看对应连接正在运行的sql

select /*+ PUSH_SUBQ */command_type,sql_text,sharable_mem,persistent_mem,runtime_mem,sorts,version_count,

loaded_versions,open_versions,users_opening,executions,users_executing,loads,first_load_time,invalidations,parse_calls,disk_reads,buffer_gets,rows_processed,sysdate start_time,sysdatefinish_time,'>'|| address sql_address,
'N' status from v$sqlarea where address = (select sql_address from v$sessionwhere sid=8);

 

根据pid查看sql语句:
SQL>select sql_text from v$sql
where address in
(select sql_address from v$session
where sid in
(select sid from v$session where paddr in (select addr from v$process wherespid=&pid)));

 

查询表空间使用情况:

SQL>select a.tablespace_name "表空间名称",

100-round((nvl(b.bytes_free,0)/a.bytes_alloc)*100,2)"占用率(%)",

round(a.bytes_alloc/1024/1024,2) "容量(M)",

round(nvl(b.bytes_free,0)/1024/1024,2)"空闲(M)",

round((a.bytes_alloc-nvl(b.bytes_free,0))/1024/1024,2)"使用(M)",

Largest "最大扩展段(M)",to_char(sysdate,'yyyy-mm-ddhh24:mi:ss') "采样时间" from (select f.tablespace_name,sum(f.bytes) bytes_alloc,

sum(decode(f.autoextensible,'YES',f.maxbytes,'NO',f.bytes))maxbytes

from dba_data_files f group bytablespace_name) a,

(select f.tablespace_name,sum(f.bytes)bytes_free

from dba_free_space f group bytablespace_name) b,

(select round(max(ff.length)*16/1024,2)Largest,ts.name tablespace_name

from sys.fet$ ff, sys.file$ tf,sys.ts$ ts

where ts.ts#=ff.ts# andff.file#=tf.relfile# and ts.ts#=tf.ts#

group by ts.name, tf.blocks) c wherea.tablespace_name = b.tablespace_name and a.tablespace_name =c.tablespace_name;

 

SQL>SELECT UPPER(F.TABLESPACE_NAME)"表空间名",
       D.TOT_GROOTTE_MB "表空间大小(M)",
       D.TOT_GROOTTE_MB - F.TOTAL_BYTES "已使用空间(M)",
       TO_CHAR(ROUND((D.TOT_GROOTTE_MB -F.TOTAL_BYTES) / D.TOT_GROOTTE_MB * 100,
                    2),
              '990.99') "使用比",
       F.TOTAL_BYTES "空闲空间(M)",
       F.MAX_BYTES "最大块(M)"
  FROM (SELECT TABLESPACE_NAME,
              ROUND(SUM(BYTES) / (1024 * 1024), 2) TOTAL_BYTES,
              ROUND(MAX(BYTES) / (1024 * 1024), 2) MAX_BYTES
          FROM SYS.DBA_FREE_SPACE
         GROUP BY TABLESPACE_NAME) F,
       (SELECT DD.TABLESPACE_NAME,
              ROUND(SUM(DD.BYTES) / (1024 * 1024), 2) TOT_GROOTTE_MB
          FROM SYS.DBA_DATA_FILESDD
         GROUP BY DD.TABLESPACE_NAME) D
 WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME
 ORDER BY 4 DESC;

 

查询表空间的碎片程度:

 

SQL>selecttablespace_name,count(tablespace_name) from dba_free_space group bytablespace_name having count(tablespace_name)>10;

 

SQL>alter tablespace name coalesce;

SQL>alter table table_name deallocateunused;

 

SQL>create or replace view ts_blocks_vas

selecttablespace_name,block_id,bytes,blocks,'free space' segment_name fromdba_free_space union all

selecttablespace_name,block_id,bytes,blocks,segment_name from dba_extents;

 

SQL>select * from ts_blocks_v;

 

SQL>select tablespace_name,sum(bytes),max(bytes),count(block_id)from dba_free_space group by tablespace_name;

 

SQL>select 'alter tablespace'||TABLESPACE_NAME||' coalesce;'
from DBA_FREE_SPACE_COALESCED where PERCENT_EXTENTS_COALESCED<100
or PERCENT_BLOCKS_COALESCED<100;

 

由于自由空间碎片是由几部分组成,如范围数量、最大范围尺寸等,我们可
用fsfi--freespace fragmentation index(自由空间碎片索引)值来直观体现:


fsfi=100*sqrt(max(extent)/sum(extents))*1/sqrt(sqrt(count(extents)))

rem fsfi value compute
rem fsfi.sql
column fsfi format 999,99
select tablespace_name,sqrt(max(blocks)/sum(blocks))*
(100/sqrt(sqrt(count(blocks)))) fsfi
from dba_free_space
group by tablespace_name order by 1;
spool fsfi.rep;
/
spool off;

 

可以看出,fsfi的最大可能值为100(一个理想的单文件表空间)。随着范
围的增加,fsfi值缓慢下降,而随着最大范围尺寸的减少,fsfi值会迅速下降。

比如,在某数据库运行脚本fsfi.sql,得到以下fsfi值:
tablespace_name fsfi
------------------------------ -------
rbs 74.06
system 100.00
temp 22.82
tools 75.79
users 100.00
user_tools 100.00
ydcx_data 47.34
ydcx_idx 57.19
ydjf_data 33.80
ydjf_idx 75.55

---- 统计出了数据库的fsfi值,就可以把它作为一个可比参数。在一个有着足够
有效自由空间,且fsfi值超过30的表空间中,很少会遇见有效自由空间的问题。
当一个空间将要接近可比参数时,就需要做碎片整理了。

 

 

查询有哪些数据库实例在运行:

SQL>select inst_name fromv$active_instances;

 

以DBA角色, 查看当前数据库里锁的情况:

SQL>selectobject_id,session_id,locked_mode from v$locked_object;

SQL>selectt2.username,t2.sid,t2.serial#,t2.logon_time  from  v$locked_objectt1,v$session t2

where t1.session_id=t2.sid order byt2.logon_time;

 

查看表是否是分区表:

例子:

SQL>select TABLE_NAME,PARTITIONED fromuser_tables where TABLE_NAME='LOCALUSAGE';

TABLE_NAME                    PAR

------------------------------ ---          ---------

LOCALUSAGE                    YES

 

查看分区表的分区名和相应的表空间名:

SQL>select TABLE_NAME,PARTITION_NAME,TABLESPACE_NAME from user_tab_partitions where table_name like ‘%USAGE%’;

 

查看索引是否是分区索引:

SQL>SELECT INDEX_NAME, TABLE_NAME,STATUS, PARTITIONED FROM USER_INDEXES WHERE TABLE_NAME LIKE '%USAGE';

如果返回的PATITIONED为YES,请再执行如下语句来查询分区索引的类型:SELECT index_name,table_name,locality FROM user_part_indexes;

 

Dual是Oracle中的一个实际存在的表,任何用户均可读取,常用在没有目标表的Select中.

查看系统时间:

SQL>select to_char(sysdate,'yy-mm-ddhh24:mi:ss') shijian from dual;

 

查看索引段中extent的数量:

SQL>select segment_name,count(*) fromdba_extents

where segment_type='INDEX' andowner='SCOTT' group by segment_name;

 

查看系统表中的用户索引(用来检查在system表空间内其他用户索引的存在):

SQL>select count(*) from dba_indexeswhere tablespace_name=’SYSTEM’ and ownerNOT IN(‘SYS’,’SYSTEM’);

 

查看wacos表空间内的索引的扩展情况:

SQL>SELECT SUBSTR(segment_name,1,20)"SEGMENT NAME",bytes, COUNT(bytes)

FROM dba_extents WHERE segment_name IN(SELECT index_name FROM dba_indexes

WHERE tablespace_name = 'WACOS') GROUP BYsegment_name,bytes ORDER BY segment_name;

 

查看表空间数据文件的读写性能:

SQL>Selectname,phyrds,phywrts,avgiotim,miniotim,maxiowtm,maxiortm fromv$filestat,v$datafile where v$filestat.file#=v$datafile.file#;

 

SQL>Select fs.namename,f.phyrds,f.phyblkrd,f.phywrts,f.phyblkwrt ,f.readtim,f.writetim

from v$filestat f, v$datafile fs wheref.file# = fs.file# order by fs.name;

(注意:如果phyblkrd与phyrds很接近的话,则表明这个表空间中存在全表扫描的表,这些表需要调整索引或优化SQL语句)

 

转换表空间为local方式管理:

SQL> execsys.dbms_space_admin.tablespace_migrate_to_local('TBS_TEST') ;

 

查看一下哪个用户在用临时段:

SQL>SELECTusername,sid,serial#,sql_address,machine,program,tablespace,segtype,
contents FROM v$session se,v$sort_usage su WHEREse.saddr=su.session_addr;     

 

查看占io较大的正在运行的session:

SQL>SELECTse.sid,se.serial#,pr.SPID,se.username,se.status,se.terminal,se.program, se.MODULE,se.sql_address,st.event,st.p1text,si.physical_reads,si.block_changesFROM v$session se,v$session_wait st,v$sess_io si,v$process pr WHEREst.sid=se.sid  AND st.sid=si.sid AND se.PADDR=pr.ADDR AND se.sid>6 ANDst.wait_time=0 AND st.event NOT LIKE '%SQL%' ORDER BY physical_reads DESC;

 

查找前十条性能差的sql:

SQL>SELECT * FROM(SELECT PARSING_USER_IDEXECUTIONS,SORTS,COMMAND_TYPE,DISK_READS,sql_text FROM  v$sqlarea ORDER BYdisk_reads DESC) WHERE ROWNUM<10;

 

删除用户下所有表的语句:
SQL>select 'drop table '||table_name||' cascade constraints;' fromuser_tables;

 

 

查看LOCK,并杀掉会话:

SQL>set linesize 132 pagesize 66

 

break on Kill on username on terminal

column Kill heading 'Kill String' formata13

column res heading 'Resource Type' format999

column id1 format 9999990

column id2 format 9999990

column lmode beading 'Lock Held' format a20

column request heading 'Lock Requested'format a20

column serial# format 99999

column username format a10 heading"Username"

column terminal heading Term format a6

column tab format a35 heading "tableName"

column owner format a9

column Address format a18

 

SQL>select nvl(S.USERNAME,'Internal')username,

      nvl(S.TERMINAL,'None') terminal,

      L.SID||','||S.SERIAL# Kill,

      U1.NAME||','||substr(T1.NAME,1,20) tab,

      decode(L.LMODE, 1,'No Lock',

                    2,'Row Share',

                    3,'Row Exclusive',

                    4,'Share',

                    5,'Share Row Exclusive',

                    6,'Exclusive',null) lmode,

      decode(L.REQUEST,1,'No Lock',

                       2,'Row Share',

                       3,'Row Exclusive',

                       4,'Share',

                       5,'Share Row Exclusive',

                       6,'Exclusive',null) request

       fromV$LOCK L,

           V$SESSION S,

           SYS.USER$ U1,

           SYS.OBJ$  T1

       whereL.SID = S.SID

       andT1.OBJ# = decode(L.ID2,0,L.ID1,L.ID2)

       andU1.USER#= T1.OWNER#

       andS.TYPE != 'BACKGROUND'

       orderby 1,2,5;

 

 

--alter system kill session ' , ';

 

column username format A15

column sid     format 9990 heading SID

column type     formatA4

column lmode    format990  heading 'HELD'

column request  format 990 heading 'REQ'

column id1     format 9999990

column id2     format9999990

break on id1 skip 1 dup

spool tfslckwt.lst

 

SQL>select sn.username,

       m.sid,

      m.type,

      DECODE(m.lmode,0,'None',

                   1,'Null',

                   2,'Row Share',

                   3,'Row Excl.',

                   4,'Share',

                   5,'S/Row Excl.',

                   6,'Exclusive',

             lmode,ltrim(to_char(lmode,'990'))) lmode,

     DECODE(m.request,0,'None',

                     1,'Null',

                     2,'Row Share',

                     3,'Row Excl.',

                     4,'Share',

                     5,'S/Row Excl.',

                     6,'Exclusive',

                     request,ltrim(to_char(m.request,'990'))) request,

      m.id1,

      m.id2

      fromv$session sn,

          v$lock    m

      where(sn.sid = m.sid and m.request!= 0)

      or   (sn.sid = m.sid and

            m.request = 0 and lmode != 4 and

            (id1 ,id2) in (select s.id1,

                                 s.id2

                             from v$lock s

            where request != 0 and s.id1 = m.id1 and s.id2 = m.id2)

           )

       orderby id1,id2,m.request;

       spooloff

       clearbreaks

 

查看WACOS表空间下所有的索引:

SQL>select  'analyze index'||segment_name||' validate structure;' from dba_segments wheretablespace_name=’WACOS’and  segment_type=’INDEX’;

 

怎样识别IO竞争和负载平衡:

SQL>col 文件名 format a35

SQL>select

    df.name 文件名,

    fs.phyrds 读次数,

    fs.phywrts 写次数,

   (fs.readtim/decode(fs.phyrds,0,-1,fs.phyrds)) 读时间,

   (fs.writetim/decode(fs.phywrts,0,-1,fs.phywrts)) 写时间

from

    v$datafile df,

    v$filestat fs

where df.file#=fs.file#

order by df.name

/

文件名                                          读次数    写次数    读时间    写时间

------------------------------------------------------ ---------- ---------- ----------

C:\ORACLE\ORADATA\ORADB\DR01.DBF                  885       883          0         0

C:\ORACLE\ORADATA\ORADB\INDX01.DBF                885       883          0         0

C:\ORACLE\ORADATA\ORADB\OEM_REPOSITORY.ORA        885       883         0          0

C:\ORACLE\ORADATA\ORADB\RBS01.DBF                 925     22306          0         0

C:\ORACLE\ORADATA\ORADB\SYSTEM01.DBF            50804    155025         0          0

C:\ORACLE\ORADATA\ORADB\TEMP01.DBF                887       894         0          0

C:\ORACLE\ORADATA\ORADB\TOOLS01.DBF               886       892          0         0

C:\ORACLE\ORADATA\ORADB\USERS01.DBF               885       883          0         0

 

已选择8行。

 

其中:ORADB为数据库名,因为本例中数据库使默认安装,没有进行过优化、调整,

      所以,一直在system表空间上做操作,导致system表空间所在的数据文件SYSTEM01.DBF被读写的次数最多,

      这也说明了,尽量不要在system表空间做与系统无关的操作,应给各个用户建立单独的表空间

 

 

查看哪些session正在使用哪些回滚段:

SQL>col 回滚段名 format a10

SQL>col SID format 9990

SQL>col 用户名 format a10

SQL>col 操作程序 format a80

SQL>col status format a6 trunc

 

SQL>SELECT  r.name 回滚段名,

    s.sid,

    s.serial#,

    s.username 用户名,

    t.status,

    t.cr_get,

    t.phy_io,

    t.used_ublk,

    t.noundo,

    substr(s.program, 1, 78)操作程序

FROM   sys.v_$sessions,sys.v_$transaction t,sys.v_$rollname r

WHERE  t.addr = s.taddr and t.xidusn =r.usn

ORDER  BY t.cr_get,t.phy_io;

 

45.检查谁Lock了什么对象:
set line 200
col "O/S-User" format a10
col "Ora-User" format a10
col "Obj Locked" format a30
select /*+RULE*/s.machine, s.osuser "O/S-User", s.username"Ora-User", s.sid "Session-ID",
s.serial# "Serial", s.process "Process-ID", s.status"Status",l.name "Obj Locked",
l.mode_held "Lock Mode"
from v$session s,dba_dml_locks l,v$process p
where l.session_id = s.sid and p.addr = s.paddr
/


造成等待的LOCK的信息,比如LOCK类型等:
SQL>col event format a30
SQL>set line 160
SQL>col machine format a10
SQL>col username format a15
SQL>selectb.sid,b.serial#,b.username,machine,event,wait_time,chr(bitand(p1,-16777216)/16777215)||chr(bitand(p1,16711680)/65535) "Enqueue Type" from v$session_wait a,v$session b
where event not like 'SQL*N%' and event not like 'rdbms%' and a.sid=b.sid
and b.sid>8 and event='enqueue' order by username;


List of the locked Oracle objects

SQL>set line 120

SQL>column object_name  format a32

SQL>column OS_USER_NAME format a12

SQL>columnorauser      format a12

column sql_text    format a32

columnserial#      format 999999

columnsid          format 99999

SQL>SELECT OS_USER_NAME, ORACLE_USERNAMEAS orauser, s.sid, o.object_name,

   o.object_type, s.serial#,a.sql_text

   FROM v$locked_object l,dba_objects o, v$session s, v$sqlarea a

   WHERE l.object_id =o.object_id

   AND  s.SQL_ADDRESS    = a.address

   AND l.SESSION_ID = s.sid;

   SELECT 'ALTER SYSTEM KILLSESSION '''||TO_CHAR(s.sid)||','||TO_CHAR(s.serial#)||''';'

 

   AS  "Statement tokill"

   FROM v$locked_object l,dba_objects o, v$session s

   WHERE l.object_id =o.object_id

   AND l.SESSION_ID = s.sid;

 

 

oracle数据库性能监控的SQL

监控事例的等待
SQL>select event,sum(decode(wait_Time,0,0,1))"Prev",sum(decode(wait_Time,0,1,0)) "Curr",count(*)"Tot" from v$session_Wait group by event order by 4;

回滚段的争用情况
SQL>select name, waits, gets, waits/gets "Ratio" from v$rollstata, v$rollname b where a.usn = b.usn; 

监控表空间的 I/O 比例
SQL>select df.tablespace_name name,df.file_name "file",f.phyrdspyr,
f.phyblkrd pbr,f.phywrts pyw, f.phyblkwrt pbw from v$filestat f, dba_data_filesdf where f.file# = df.file_id
order by df.tablespace_name;

监控文件系统的 I/O 比例
SQL>select substr(a.file#,1,2) "#", substr(a.name,1,30)"Name", 
a.status,a.bytes,b.phyrds,b.phywrts from v$datafile a, v$filestat b
where a.file# = b.file#; 

在某个用户下找所有的索引
SQL>select user_indexes.table_name, user_indexes.index_name,uniqueness,column_name from user_ind_columns, user_indexes where user_ind_columns.index_name= user_indexes.index_name
and user_ind_columns.table_name = user_indexes.table_name 
order by user_indexes.table_type, user_indexes.table_name,
user_indexes.index_name, column_position;

监控 SGA 的命中率
SQL>select a.value + b.value "logical_reads", c.value"phys_reads",
round(100 * ((a.value+b.value)-c.value) / (a.value+b.value)) "BUFFER HITRATIO" from v$sysstat a, v$sysstat b, v$sysstat c where a.statistic# = 38and b.statistic# = 39 and c.statistic# = 40; 

监控 SGA 中字典缓冲区的命中率
SQL>select parameter, gets,Getmisses , getmisses/(gets+getmisses)*100"miss ratio",(1-(sum(getmisses)/ (sum(gets)+sum(getmisses))))*100"Hit ratio" from v$rowcache where gets+getmisses <>0 group byparameter, gets, getmisses; 

监控 SGA 中共享缓存区的命中率,应该小于1%
SQL>select sum(pins) "Total Pins", sum(reloads) "TotalReloads",
sum(reloads)/sum(pins) *100 libcache from v$librarycache;
SQL>select sum(pinhits-reloads)/sum(pins) "hitradio",sum(reloads)/sum(pins) "reload percent" fromv$librarycache;

显示所有数据库对象的类别和大小
SQL>select count(name) num_instances ,type ,sum(source_size)source_size,sum(parsed_size) parsed_size ,sum(code_size) code_size,sum(error_size) error_size,sum(source_size) +sum(parsed_size) +sum(code_size)+sum(error_size) size_required from dba_object_size group by type order by 2;

监控 SGA 中重做日志缓存区的命中率,应该小于1%
SQL>SELECT name, gets, misses, immediate_gets, immediate_misses,
Decode(gets,0,0,misses/gets*100) ratio1,Decode(immediate_gets+immediate_misses,0,0,immediate_misses/(immediate_gets+immediate_misses)*100) ratio2
FROM v$latch WHERE name IN ('redo allocation', 'redo copy'); 

监控内存和硬盘的排序比率,最好使它小于 .10,增加sort_area_size 
SQL>SELECT name, value FROM v$sysstat WHERE name IN ('sorts (memory)','sorts (disk)'); 


监控当前数据库谁在运行什么SQL语句
SQL>SELECT osuser, username, sql_text from v$session a, v$sqltext b
where a.sql_address =b.address order by address, piece;

监控字典缓冲区
SQL>SELECT (SUM(PINS - RELOADS)) / SUM(PINS) "LIB CACHE" FROMV$LIBRARYCACHE;
SQL>SELECT (SUM(GETS - GETMISSES - USAGE - FIXED)) / SUM(GETS) "ROWCACHE" FROM V$ROWCACHE;
SQL>SELECT SUM(PINS) "EXECUTIONS", SUM(RELOADS) "CACHE MISSESWHILE EXECUTING" FROM V$LIBRARYCACHE;(后者除以前者,此比率小于1%,接近0%为好)
SQL>SELECT SUM(GETS) "DICTIONARY GETS",SUM(GETMISSES)"DICTIONARY CACHE GET MISSES" FROM V$ROWCACHE;

查找ORACLE字符集
SQL>select * from sys.props$ where name='NLS_CHARACTERSET'; 

监控 MTS
SQL>select busy/(busy+idle) "shared servers busy" fromv$dispatcher;
(此值大于0.5时,参数需加大)
SQL>select sum(wait)/sum(totalq) "dispatcher waits" from v$queuewhere type='dispatcher';
SQL>select count(*) from v$dispatcher;
SQL>select servers_highwater from v$mts;
(servers_highwater接近mts_max_servers时,参数需加大)

碎片程度
SQL>select tablespace_name,count(tablespace_name) from dba_free_space groupby tablespace_name having count(tablespace_name)>10;
SQL>alter tablespace name coalesce;
SQL>alter table name deallocate unused;
SQL>create or replace view ts_blocks_v as
select tablespace_name,block_id,bytes,blocks,'free space' segment_name fromdba_free_space
    union all
    select tablespace_name,block_id,bytes,blocks,segment_namefrom dba_extents;

    select * fromts_blocks_v;

SQL>selecttablespace_name,sum(bytes),max(bytes),count(block_id) from dba_free_space groupby tablespace_name;

查看碎片程度高的表
SQL>SELECT segment_name table_name,COUNT(*) extents
FROM dba_segments WHERE owner NOT IN ('SYS', 'SYSTEM') GROUP BY

segment_name HAVING COUNT(*)=(SELECTMAX(COUNT(*)) FROM dba_segments GROUP BY segment_name);

17. 表、索引的存储情况检查
SQL>select segment_name,sum(bytes),count(*) ext_quan from dba_extents wheretablespace_name='&tablespace_name' and segment_type='TABLE' group bytablespace_name,segment_name;
SQL>select segment_name,count(*) from dba_extents where segment_type='INDEX'and owner='&owner' group by segment_name;

18、找使用CPU多的用户session
SQL>select a.sid,spid,status,substr(a.program,1,40) prog,a.terminal,osuser,value/60/100value from v$session a,v$process b,v$sesstat c
where c.statistic#=12 and c.sid=a.sid and a.paddr=b.addr order by value desc;

(12是cpu used by this session)

 

表空间统计

 A、    脚本说明:

这是我最常用的一个脚本,用它可以显示出数据库中所有表空间的状态,如表空间的大小、已使用空间、使用的百分比、空闲空间数及现在表空间的最大块是多大。

B、脚本原文:

SELECT upper(f.tablespace_name) "表空间名",

      d.Tot_grootte_Mb "表空间大小(M)",

      d.Tot_grootte_Mb - f.total_bytes "已使用空间(M)",

      to_char(round((d.Tot_grootte_Mb - f.total_bytes) / d.Tot_grootte_Mb *100,2),'990.99') "使用比",

      f.total_bytes "空闲空间(M)",

      f.max_bytes "最大块(M)"

 FROM     

    (SELECT tablespace_name,

           round(SUM(bytes)/(1024*1024),2) total_bytes,

           round(MAX(bytes)/(1024*1024),2) max_bytes

      FROMsys.dba_free_space

     GROUP BY tablespace_name)f,

    (SELECTdd.tablespace_name, round(SUM(dd.bytes)/(1024*1024),2) Tot_grootte_Mb

     FROM   sys.dba_data_files dd

      GROUP BYdd.tablespace_name) d

WHERE d.tablespace_name =f.tablespace_name   

ORDER BY 4 DESC;

 

查看无法扩展的段

A、  脚本说明:

ORACLE对一个段比如表段或索引无法扩展时,取决的并不是表空间中剩余的空间是多少,而是取于这些剩余空间中最大的块是否够表比索引的“NEXT”值大,所以有时一个表空间剩余几个G的空闲空间,在你使用时ORACLE还是提示某个表或索引无法扩展,就是由于这一点,这时说明空间的碎片太多了。这个脚本是找出无法扩展的段的一些信息。

B、脚本原文:

SELECT segment_name,

            segment_type,

            owner,

            a.tablespace_name "tablespacename",

            initial_extent/1024 "inital_extent(K)",

            next_extent/1024 "next_extent(K)",

            pct_increase,

            b.bytes/1024 "tablespace max free space(K)",

            b.sum_bytes/1024 "tablespace total free space(K)"

  FROM dba_segments a,

      (SELECT tablespace_name,MAX(bytes) bytes,SUM(bytes) sum_bytes FROMdba_free_space GROUP BY tablespace_name) b

 WHEREa.tablespace_name=b.tablespace_name

   AND next_extent>b.bytes

 ORDER BY 4,3,1;

 

查看段(表段、索引段)所使用空间的大小

A、  脚本说明:

有时你可能想知道一个表或一个索引占用多少M的空间,这个脚本就是满足你的要求的,把<>中的内容替换一下就可以了。

B、脚本原文:

SELECT owner,

             segment_name,

             SUM(bytes)/1024/1024

    FROM dba_segments

   WHERE owner=

       And segment_name=

  GROUP BY owner,segment_name

  ORDER BY 3 DESC;

 

查看数据库中的表锁

A、  脚本说明:

 这方面的语句的样式是很多的,各式一样,不过我认为这个是最实用的,不信你就用一下,无需多说,锁是每个DBA一定都涉及过的内容,当你相知道某个表被哪个session锁定了,你就用到了这个脚本。

B、脚本原文:

  SELECT A.OWNER,  

              A.OBJECT_NAME,  

              B.XIDUSN,  

             B.XIDSLOT,  

             B.XIDSQN,  

             B.SESSION_ID,  

             B.ORACLE_USERNAME,  

             B.OS_USER_NAME,  

             B.PROCESS,  

             B.LOCKED_MODE,  

             C.MACHINE,  

             C.STATUS,  

             C.SERVER,  

             C.SID,  

             C.SERIAL#,  

             C.PROGRAM 

    FROM ALL_OBJECTSA,  

        V$LOCKED_OBJECT B,  

        SYS.GV_$SESSION C

   WHERE ( A.OBJECT_ID =B.OBJECT_ID )

     AND (B.PROCESS =C.PROCESS )

   --  AND 

   ORDER BY 1,2;  

 

处理存储过程被锁

A、  脚本说明:

   实际过程中可能你要重新编译某个存储过程理总是处于等待状态,最后会报无法锁定对象,这时你就可以用这个脚本找到锁定过程的那个sid,需要注意的是查v$access这个视图本来就很慢,需要一些耐心。

B、脚本原文:

SELECT * FROM V$ACCESS WHEREowner=<object owner> And object=<procedure name>;

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值