首页 > 开发 > 综合 > 正文

DBA常用SQL语句

2024-07-21 02:07:16
字体:
来源:转载
供稿:网友

 

 自己总结的常用sql语句,发现对自己工作帮助挺大的!

 

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

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

from dba_tablespaces t, dba_data_files d where 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 by tablespace_name;

 

查看回滚段名称及大小:

sql>select segment_name, tablespace_name, r.status,

(initial_extent/1024) initialextent,(next_extent/1024) nextextent,

max_extents, v.curext curextent from dba_rollback_segs r, v$rollstat v

where r.segment_id = v.usn(+) order by segment_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 from v$session where audsid=userenv('sessionid');

 

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

sql>select userenv('language') from dual;

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

 

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

用explain plan产生explain plan,检查plan_table中id=0的position列的值。

sql>select decode(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$parameter instance 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' and v$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 where name ='user_dump_dest') d;

 

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

sql>select sys_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;

 

rem 记录登陆信息的触发器

create or replace trigger logon_history

after logon on database --when (user='wacos') --only for user 'wacos'

begin

insert into session_history

select username,sid,serial#,audsid,osuser,action,sysdate,null,sys_context('userenv','ip_address'),terminal,machine,program

from v$session where audsid = userenv('sessionid');

end;

 

查询当前日期:

sql> select to_char(sysdate,'yyyy-mm-dd,hh24:mi:ss') from dual;

 

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

sql>select distinct file_name,tablespace_name,autoextensible from dba_data_files;

 

查看表空间的使用情况:

sql>select sum(bytes)/(1024*1024) as free_space,tablespace_name

from dba_free_space group by tablespace_name;

 

sql>select a.tablespace_name,a.bytes total,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_used b,sys.sm$ts_free c

where a.tablespace_name=b.tablespace_name and a.tablespace_name=c.tablespace_name;

 

column tablespace_name format a18;
column sum_m format a12;
column used_m format a12;
column free_m format a12;
column pto_m format 9.99;
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 (select b.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)) * 100 freepercentratio 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 by sum(s.freespace)/sum(s.bytes) desc;

 

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

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 by file_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(+);

 

数据文件大小及头大小:

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 by file_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>select a.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,(select tablespace_name,sum(bytes) total  from dba_data_files group by tablespace_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 (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_files dd
 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 by tablespace_name ) f where f.tablespace_name = a.tablespace_name and a.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 by tablespace_name ) f where f.tablespace_name = a.tablespace_name and a.next_extent > f.big_chunk;

 

disk read最高的sql语句的获取:

sql>select sql_text from (select * from v$sqlarea order by disk_reads)

where rownum<=5;

 

查找前十条性能差的sql

select * from  (select parsing_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 * from v$system_event where event not like 'sql%' order by total_waits desc) where rownum<=5;

 

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

col username format a10

set line 120

col event format a30

select se.sid,s.username,se.event,se.total_waits,se.time_waited,se.average_wait

from v$session s,v$session_event se where s.username is not null and se.sid=s.sid

and s.status='active' and se.event not like '%sql*net%';

 

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%' and event != 'wakeup time manager';

 

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

select sw.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 where s.username is not null and sw.sid=s.sid

and sw.event not like '%sql*net%' order by sw.wait_time desc;

 

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

sql>select  segment_name,owner,tablespace_name,initial_extent,next_extent,dba_rollback_segs.status from dba_rollback_segs,v$datafile where file_id=file#;

 

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

col name format a10

set linesize 140        

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的值)

 

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

select s.username, u.name from v$transaction t,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正在忙什么:

select a.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; 

 

数据库共享池性能检查:

select namespace,gets,gethitratio,pins,pinhitratio,reloads,

invalidations from v$librarycache where namespace in

('sqlarea','table/procedure','body','trigger');

 

检查数据重载比率:

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

v$librarycache;

 

检查数据字典的命中率:

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

ratio" from v$rowcache;

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

 

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

select request_misses, request_failures from v$shared_pool_reserved; 

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

 

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

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

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

p.name='physical reads' and b.name='db block gets' and

c.name='consistent gets';

检查buffer pool hit_ratio执行

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

"miss_hit_ratio" from v$buffer_pool_statistics where (db_block_gets+ consistent_gets)> 0;

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

 

数据库回滚段性能检查:

检查ratio执行

select sum(waits)* 100 /sum(gets) "ratio", sum(waits)

   "waits", sum(gets) "gets" from v$rollstat;

检查count/value执行:

select class,count from v$waitstat where class like '%undo%';

select value from v$sysstat where name='consistent gets';

(两者的value值相除)

 

检查average_wait执行:

select event,total_waits,time_waited,average_wait from v$system_event

where event like '%undo%';

 

检查rbs header get ratio执行:

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

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

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

 

杀会话的脚本:

select a.sid,b.spid,a.serial#,a.lockwait,a.username,a.osuser,a.logon_time,a.last_call_et/3600 last_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$sysstat where name in ('sorts (memory)', 'sorts (disk)'); 

7、查看数据库库对象:

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

 

8、查看数据库的版本: 

select * from v$version;

 

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

select created, log_mode, log_mode from v$database;

 

10、捕捉运行很久的sql:

column username format a12

column opname format a16

column progress format a8

select username,sid,opname,round(sofar*100 / totalwork,0) || '%' as progress,time_remaining,sql_text from v$session_longops , v$sql where time_remaining <> 0 and sql_address=address and sql_hash_value = hash_value;

 

11、查看数据表的参数信息:

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 from dba_tab_partitions
--where table_name = :tname and table_owner = :towner
order by partition_position;

 

12、查看还没提交的事务:

select * from v$locked_object;

select * from v$transaction;

 

13、查找object为哪些进程所用:

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.object object_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.status session_status  from v$session s, v$access a, v$process p  where s.paddr = p.addr and s.type = 'user' and a.sid = s.sid  and a.object='subscriber_attr'order by s.username, s.osuser;

 

14、查看回滚段:

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.status status from v$rollstat, sys.dba_rollback_segs, v$rollname where v$rollname.name(+) = sys.dba_rollback_segs.segment_name and v$rollstat.usn (+) = v$rollname.usn order by rownum;

 

15、耗资源的进程(top session):

select s.schemaname schema_name,decode(sign(48 - command), 1, to_char(command), 'action code #' || to_char(command) ) action,status session_status,s.osuser os_user_name,s.sid,p.spid,s.serial# serial_num,nvl(s.username,'[oracle process]') user_name,s.terminal terminal,s.program program,st.value criteria_value from v$sesstat st,v$session s,v$process p where st.sid = s.sid and 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.osuser asc;

 

根据pid查找相应的语句:

select a.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=spid

   and b.addr=a.paddr and a.sql_address=c.address(+) order by c.piece;

 

根据sid找oracle的某个进程:

sql> select pro.spid from v$session ses,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  and s.machine='xxxxx' or username='wacos';

 

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

sql> select user_name,sql_text from v$open_cursor where sid in(select sid from (select sid,serial# from v$session where status='active'));

 

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

 

sql> select program ,sql_address from v$session where paddr in (select addr

from v$process where spid=3556);

 

program                                          sql_address

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

[email protected] (tns v1-v3)                        000000038fcb1a90

 

sql> select sql_text from v$sqlarea where address='000000038fcb1a90';

 

找出消耗cpu最高的进程对应的sql语句:

set line 240

set verify off

column sid format 999

column pid format 999

column s_# format 999

column username format a9 heading "ora user"

column program  format a29

column sql      format a60

column osname format a9 heading "os user"

select p.pid pid,s.sid sid,p.spid spid,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 a where p.addr = s.paddr

and s.sql_address = a.address (+)  and p.spid like '%&1%';

 

enter value for 1: pid(这里输入占用cpu最高的进程对应的pid)

 

 

set termout off

spool maxcpu.txt

select '++'||s.username username,

rtrim(replace(a.sql_text,chr(10),''))||';'from v$process p, v$session s,

v$sqlarea a where p.addr = s.paddr and s.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,process from v$sqlarea,v$session,v$process where v$sqlarea.address=v$session.sql_address and v$sqlarea.hash_value=v$session.sql_hash_value

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

 

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

 

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

 

16、查看锁(lock)情况:

sql>select /*+ rule */ ls.osuser os_user_name, ls.username user_name, 
decode(ls.type,'rw','row wait enqueue lock','tm','dml enqueue lock','tx','transaction enqueue lock','ul','user supplied lock') lock_type,o.object_name object,decode(ls.lmode, 1, null, 2,'row share',3,'row exclusive',4,'share',5,'share row exclusive',6,'exclusive',null)lock_mode,o.owner,ls.sid,ls.serial# serial_num,ls.id1,ls.id2 from sys.dba_objects o,(select s.osuser,s.username,l.type,l.lmode,s.sid,s.serial#,l.id1,l.id2 from v$session s,v$lock l where s.sid=l.sid)ls where o.object_id=ls.id1 and o.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 cache invalida-tion','ls','log start or switch','rw','row wait','sq','sequence number','te','extend table','tt','temp table','unknown') locktype,
rtrim(object_type) || ' ' || rtrim(owner) || '.' || object_name object_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语句:
col owner for a12
col object_name for a16
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>select t2.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$session where sid=;
sql>select * from v$sqltext where address=;

 

sql>select command_type,piece,sql_text from v$sqltext where address=(select sql_address from v$session a where sid=18);   

 

sql>select object_id from v$locked_object;

sql>select object_name,object_type from dba_objects where object_id=’’;

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


17、查看等待(wait)情况:

sql>select v$waitstat.class,v$waitstat.count count, sum(v$sysstat.value) sum_value from v$waitstat,v$sysstat where v$sysstat.name in('db block gets','consistent gets') group by v$waitstat.class,v$waitstat.count;

18、查看sga情况:

sql>select name, bytes from sys.v_$sgastat order by name asc;

19、查看catched object:

sql>select owner,name,db_link,namespace,type,sharable_mem,loads,              executions,locks,pins,kept from v$db_object_cache;
          
20、查看v$sqlarea:

sql>select 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 from v$sqlarea;
 
21、查看object分类数量:

select decode(o.type#,1,'index',2,'table',3,'cluster',4,'view',5,'synonym',6, 'sequence','other') object_type , count(*) quantity from sys.obj$ o where o.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;

22、有关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.program program,      
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查看对应连接的资源占用等情况

select n.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,sysdate finish_time,'>'|| address sql_address,
'n' status from v$sqlarea where address = (select sql_address from v$session where sid=8);

 

根据pid查看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 where spid=&pid)));

 

23、查询表空间使用情况:

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-dd hh24: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 by tablespace_name) a,

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

from dba_free_space f group by tablespace_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# and ff.file#=tf.relfile# and ts.ts#=tf.ts#

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

 

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_files dd
         group by dd.tablespace_name) d
 where d.tablespace_name = f.tablespace_name
 order by 4 desc;

 

24、查询表空间的碎片程度:

 

sql>select tablespace_name,count(tablespace_name) from dba_free_space group by tablespace_name having count(tablespace_name)>10;

 

sql>alter tablespace name coalesce;

sql>alter table table_name deallocate unused;

 

sql>create or replace view ts_blocks_v as

select tablespace_name,block_id,bytes,blocks,'free space' segment_name from dba_free_space union all

select tablespace_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--free space 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的表空间中,很少会遇见有效自由空间的问题。
当一个空间将要接近可比参数时,就需要做碎片整理了。

 

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

select inst_name from v$active_instances;

 

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

select object_id,session_id,locked_mode from v$locked_object;

select t2.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;

 

27、查看表是否是分区表:

select table_name,partitioned from user_tables where table_name='localusage';

table_name                     par

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

localusage                     yes

 

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

select table_name, partition_name,tablespace_name from user_tab_partitions where table_name like ‘%usage%’;

 

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

select index_name, table_name, status, partitioned from user_indexes where table_name like '%usage';

30、如果返回的patitioned为yes,请再执行如下语句来查询分区索引的类型:select index_name,table_name,locality from user_part_indexes;

31、dual是oracle中的一个实际存在的表,任何用户均可读取,常用在没有目标表的select中.

查看系统时间:

select to_char(sysdate,'yy-mm-dd hh24:mi:ss') shijian from dual;

 

32、查看索引段中extent的数量:

select segment_name,count(*) from dba_extents

where segment_type='index' and owner='scott' group by segment_name;

 

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

sql>select count(*) from dba_indexes where tablespace_name=’system’ and owner not in(‘sys’,’system’);

 

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

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 by segment_name,bytes order by segment_name;

 

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

sql>select name,phyrds,phywrts,avgiotim,miniotim,maxiowtm,maxiortm from v$filestat,v$datafile where v$filestat.file#=v$datafile.file#;

 

sql>select fs.name name,f.phyrds,f.phyblkrd,f.phywrts,f.phyblkwrt ,f.readtim,f.writetim

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

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

 

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

sql> exec sys.dbms_space_admin.tablespace_migrate_to_local('tbs_test') ;

 

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

select username,sid,serial#,sql_address,machine,program,tablespace,segtype,
contents from v$session se,v$sort_usage su where se.saddr=su.session_addr;     

 

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

select se.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_changes from v$session se,v$session_wait st,v$sess_io si,v$process pr where st.sid=se.sid  and st.sid=si.sid and se.paddr=pr.addr and se.sid>6 and st.wait_time=0 and st.event not like '%sql%' order by physical_reads desc;

 

39、查找前十条性能差的sql:

select * from(select parsing_user_id executions,sorts,command_type,disk_reads,sql_text from  v$sqlarea order by disk_reads desc) where rownum<10;

 

40、删除用户下所有表的语句:
select 'drop table '||table_name||' cascade constraints;' from user_tables;

 

 

41、查看lock,并杀掉会话:

set linesize 132 pagesize 66

 

break on kill on username on terminal

column kill heading 'kill string' format a13

column res heading 'resource type' format 999

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 "table name"

column owner format a9

column address format a18

 

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

       from v$lock l,

            v$session s,

            sys.user$ u1,

            sys.obj$  t1

       where l.sid = s.sid

       and t1.obj# = decode(l.id2,0,l.id1,l.id2)

       and u1.user#= t1.owner#

       and s.type != 'background'

       order by 1,2,5;

 

 

--alter system kill session ' , ';

 

column username format a15

column sid      format 9990 heading sid

column type     format a4

column lmode    format 990  heading 'held'

column request  format 990  heading 'req'

column id1      format 9999990

column id2     format 9999990

break on id1 skip 1 dup

spool tfslckwt.lst

 

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

      from v$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)

            )

       order by id1,id2,m.request;

       spool off

       clear breaks

 

42.查看wacos表空间下所有的索引:

sql>select  'analyze index '||segment_name||' validate structure;' from dba_segments where tablespace_name=’wacos’and  segment_type=’index’;

 

43. 怎样识别io竞争和负载平衡:

col 文件名 format a35

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 ystem01.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表空间做与系统无关的操作,应给各个用户建立单独的表空间。

 

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

col 回滚段名 format a10

col sid format 9990

col 用户名 format a10

col 操作程序 format a80

col status format a6 trunc

 

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_$session s,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
/
46.造成等待的lock的信息,比如lock类型等:
col event format a30
set line 160
col machine format a10
col username format a15
select b.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
/

 

47. list of the locked oracle objects

set line 120

column object_name  format a32

column os_user_name format a12

column orauser      format a12

column sql_text     format a32

column serial#      format 999999

column sid          format 99999

   select os_user_name, oracle_username as 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 kill session '''||to_char(s.sid)||','||to_char(s.serial#)||''';'

   as  "statement to kill"

   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

1. 监控事例的等待
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;

2. 回滚段的争用情况
sql>select name, waits, gets, waits/gets "ratio" from v$rollstat a, v$rollname b where a.usn = b.usn; 

3. 监控表空间的 i/o 比例
sql>select df.tablespace_name name,df.file_name "file",f.phyrds pyr,
f.phyblkrd pbr,f.phywrts pyw, f.phyblkwrt pbw from v$filestat f, dba_data_files df where f.file# = df.file_id
order by df.tablespace_name;

4. 监控文件系统的 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#; 

5.在某个用户下找所有的索引
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;

6. 监控 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 hit ratio" from v$sysstat a, v$sysstat b, v$sysstat c where a.statistic# = 38 and b.statistic# = 39 and c.statistic# = 40; 

7. 监控 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 by parameter, gets, getmisses; 

8. 监控 sga 中共享缓存区的命中率,应该小于1%
sql>select sum(pins) "total pins", sum(reloads) "total reloads",
sum(reloads)/sum(pins) *100 libcache from v$librarycache;
sql>select sum(pinhits-reloads)/sum(pins) "hit radio",sum(reloads)/sum(pins) "reload percent" from v$librarycache;

9. 显示所有数据库对象的类别和大小
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;

10. 监控 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'); 

11.  监控内存和硬盘的排序比率,最好使它小于 .10,增加 sort_area_size 
sql>select name, value from v$sysstat where name in ('sorts (memory)', 'sorts (disk)'); 


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

13. 监控字典缓冲区
sql>select (sum(pins - reloads)) / sum(pins) "lib cache" from v$librarycache;
sql>select (sum(gets - getmisses - usage - fixed)) / sum(gets) "row cache" from v$rowcache;
sql>select sum(pins) "executions", sum(reloads) "cache misses while executing" from v$librarycache;(后者除以前者,此比率小于1%,接近0%为好)
sql>select sum(gets) "dictionary gets",sum(getmisses) "dictionary cache get misses" from v$rowcache;

14. 查找oracle字符集
sql>select * from sys.props$ where name='nls_characterset'; 

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

16. 碎片程度
sql>select tablespace_name,count(tablespace_name) from dba_free_space group by 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 from dba_free_space
    union all
    select tablespace_name,block_id,bytes,blocks,segment_name from dba_extents;

    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 segment_name table_name,count(*) extents
from dba_segments where owner not in ('sys', 'system') group by 

segment_name having count(*)=(select max(count(*)) from dba_segments group by segment_name);

17. 表、索引的存储情况检查
sql>select segment_name,sum(bytes),count(*) ext_quan from dba_extents where tablespace_name='&tablespace_name' and segment_type='table' group by tablespace_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/100 value 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

      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_files dd

      group by dd.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 from dba_free_space group by tablespace_name) b

 where a.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_objects a,  

         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

 where owner=

and object


?

查看回滚段状态

a、? 脚本说明

这也是dba经常使用的脚本,因为回滚段是online还是full是他们的关怀之列嘛

??? b、select a.segment_name,b.status

? from dba_rollback_segs a,

??????? v$rollstat b

??????? where a.segment_id=b.usn

???????? order by 2

?? ??????

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

????? a、 脚本说明:

?当你发现一个回滚段处理full状态,你想使它变回online状态,这时你便会用alter rollback segment rbs_seg_name shrink,可很多时侯确shrink不回来,主要是由于某个session在用,这时你就用到了这个脚本,找到了sid的serial#余下的事就不用我说了吧。

b、脚本原文

?select? r.name 回滚段名,

??? s.sid,

??? s.serial#,

??? s.username 用户名,

??? s.status,

??? t.cr_get,

??? t.phy_io,

??? t.used_ublk,

??? t.noundo,

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

from?? sys.v_$session s,sys.v_$transaction t,sys.v_$rollname r

where? t.addr = s.taddr and t.xidusn = r.usn

?-- and r.name in ('zhyz_rbs')

order? by t.cr_get,t.phy_io

?

查看正在使用临时段的session

a、 脚本说明:

许多的时侯你在查看哪些段无法扩展时,回显的结果是临时段,或你做表空间统计时发现临段表空间的可用空间几乎为0,这时按oracle的说法是你只有重新启动数据库才能回收这部分空间。实际过程中没那么复杂,使用以下这段脚本把占用临时段的session杀掉,然后用alter tablespace temp coalesce;这个语句就把temp表空间的空间回收回来了。

b、 脚本原文

select username,sid,serial#,sql_address,machine,program,

tablespace,segtype,contents from v$session se,v$sort_usage su

?where se.saddr=su.session_addr;

?

?

dba日常维护程序:

--?free.sql

--to?verify?free?space?in?tablespaces??

--minimum?amount?of?free?space?

--document?your?thresholds:??

--?=??m??

sql>select?tablespace_name,?sum?(?blocks?)?as?free_blk?,?trunc?(?sum?(?bytes?)/(1024*1024)?)?as?free_m,?max?(?bytes?)?/?(1024)?as?big_chunk_k,?count?(*)?as?num_chunks?from?dba_free_space?group?by?tablespace_name;


1.?space.sql??

--?space.sql??

--?to?check?free,?pct_free,?and?allocated?space?within?a?tablespace??

--?11/24/98??

sql> col tablespace_name format a20
sql>select?tablespace_name,largest_free_chunk,nr_free_chunks,sum_alloc_blocks,sum_free_blocks,to_char(100*sum_free_blocks/sum_alloc_blocks,?'09.99')?||?'%'as?pct_free?from?(?select?tablespace_name?,?sum(blocks)?as?sum_alloc_blocks?from?dba_data_files?group?by?tablespace_name)
,(select?tablespace_name?as?fs_ts_name,max(blocks)?as?largest_free_chunk,count(blocks)?as?nr_free_chunks,sum(blocks)?as?sum_free_blocks?from

dba_free_space group?by?tablespace_name)?where?tablespace_name=fs_ts_name;

2.?analyze5pct.sql??

--?analyze5pct.sql??

--?to?analyze?tables?and?indexes?quickly,?using?a?5%?sample?size??

--?(do?not?use?this?script?if?you?are?performing?the?overnight??

--?collection?of?volumetric?data)??

--?11/30/98??

begin??
dbms_utility.analyze_schema?('&owner',?'estimate',?null,?5)?;??
end?;??
/??

3.?nr_extents.sql??

--?nr_extents.sql??

--?to?find?out?any?object?reaching???

--?extents,?and?manually?upgrade?it?to?allow?unlimited??

--?max_extents?(thus?only?objects?we?*expect*?to?be?big??

--?are?allowed?to?become?big)??

--?11/30/98??

select?e.owner,?e.segment_type?,?e.segment_name?,?count(*)?as?nr_extents,s.max_extents,?to_char(sum(e.bytes)?/?(1024?*?1024)?,?'999,999.90')?as?mb?from?dba_extents?e,dba_segments?s?where?e.segment_name?=?s.segment_name?group?by?e.owner,?e.segment_type,e.segment_name?,?s.max_extents?having?count(*)?>?&threshold?or?(?(?s.max_extents?-?count(*)?)??&&threshold?)?order?by?count(*)?desc;??

4.?spacebound.sql??

--?spacebound.sql??

--?to?identify?space-bound?objects.?if?all?is?well,?no?rows?are?returned.??

--?if?any?space-bound?objects?are?found,?look?at?value?of?next?extent??

--?size?to?figure?out?what?happened.??

--?then?use?coalesce?(alter?tablespace??coalesce?.??

--?lastly,?add?another?datafile?to?the?tablespace?if?needed.??

--?11/30/98??

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?by?tablespace_name)?f??
where?f.tablespace_name?=?a.tablespace_name?and?a.next_extent?>?f.big_chunk;??

b.?每晚处理程序??

1.?mk_volfact.sql??

--?mk_volfact.sql?(only?run?this?once?to?set?it?up;?do?not?run?it?nightly!)??

--?--?table?utl_vol_facts??

create?table?utl_vol_facts(??
table_name?varchar2(30),??
num_rows?number,??
meas_dt?date?)??
tablespace?platab??
storage(initial?128k??
next?128k??
pctincrease?0??
minextents?1??
maxextents?unlimited)??
/??

--?public?synonym??

create?public?synonym?utl_vol_facts?for?&owner..utl_vol_facts??

/??

--?grants?for?utl_vol_facts??

grant?select?on?utl_vol_facts?to?public??

/??

2.?analyze_comp.sql??

--??

--?analyze_comp.sql??

--??

begin??

sys.dbms_utility.analyze_schema?(?'&owner','compute');??

end?;??

/??

3.?pop_vol.sql??

--??

--?pop_vol.sql??

--??

insert?into?utl_vol_facts??

select?table_name??

,?nvl?(?num_rows,?0)?as?num_rows??

,?trunc?(?last_analyzed?)?as?meas_dt??

from?all_tables?--?or?just?user_tables??

where?owner?in?('&owner')?--?or?a?comma-separated?list?of?owners??

/??

commit??

/??

 ??

c.?每周处理程序??

1.?nextext.sql??

--??

--?nextext.sql??

--??

--?to?find?tables?that?don't?match?the?tablespace?default?for?next?extent.??

--?the?implicit?rule?here?is?that?every?table?in?a?given?tablespace?should??

--?use?the?exact?same?value?for?next,?which?should?also?be?the?tablespace's??

--?default?value?for?next.??

--??

--?this?tells?us?what?the?setting?for?next?is?for?these?objects?today.??

--??

--?11/30/98??

select?segment_name,?segment_type,?ds.next_extent?as?actual_next??

,?dt.tablespace_name,?dt.next_extent?as?default_next??

from?dba_tablespaces?dt,?dba_segments?ds??

where?dt.tablespace_name?=?ds.tablespace_name??

and?dt.next_extent?!=ds.next_extent??

and?ds.owner?=?upper?(?'&owner'?)??

order?by?tablespace_name,?segment_type,?segment_name??

2.?existext.sql??

--??

--?existext.sql??

--??

--?to?check?existing?extents??

--??

--?this?tells?us?how?many?of?each?object's?extents?differ?in?size?from??

--?the?tablespace's?default?size.?if?this?report?shows?a?lot?of?different??

--?sized?extents,?your?free?space?is?likely?to?become?fragmented.?if?so,??

--?this?tablespace?is?a?candidate?for?reorganizing.??

--??

--?12/15/98??

select?segment_name,?segment_type??

,?count(*)?as?nr_exts??

,?sum?(?decode?(?dx.bytes,dt.next_extent,0,1)?)?as?nr_illsized_exts??

,?dt.tablespace_name,?dt.next_extent?as?dflt_ext_size??

from?dba_tablespaces?dt,?dba_extents?dx??

where?dt.tablespace_name?=?dx.tablespace_name??

and?dx.owner?=?'&owner'??

group?by?segment_name,?segment_type,?dt.tablespace_name,?dt.next_extent??

3.?no_pk.sql??

--??

--?no_pk.sql??

--??

--?to?find?tables?without?pk?constraint??

--??

--?11/2/98??

select?table_name??

from?all_tables??

where?owner?=?'&owner'??

minus??

select?table_name??

from?all_constraints??

where?owner?=?'&&owner'??

and?constraint_type?=?'p'??

4.?dispk.sql??

--??

--?dispk.sql??

--??

--?to?find?out?which?primary?keys?are?disabled??

--??

--?11/30/98??

select?owner,?constraint_name,?table_name,?status??

from?all_constraints??

where?owner?=?'&owner'?and?status?=?'disabled’?and?constraint_type?=?'p'??

5.?nonupk.sql??

--??

--?nonupk.sql??

--??

--?to?find?tables?with?nonunique?pk?indexes.?requires?that?pk?names??

--?follow?a?naming?convention.?an?alternative?query?follows?that??

--?does?not?have?this?requirement,?but?runs?more?slowly.??

--??

--?11/2/98??

select?index_name,?table_name,?uniqueness??

from?all_indexes??

where?index_name?like?'&pkname%'??

and?owner?=?'&owner'?and?uniqueness?=?'nonunique'??

select?c.constraint_name,?i.tablespace_name,?i.uniqueness??

from?all_constraints?c?,?all_indexes?i??

where?c.owner?=?upper?(?'&owner'?)?and?i.uniqueness?=?'nonunique'??

and?c.constraint_type?=?'p'?and?i.index_name?=?c.constraint_name??

6.?mkrebuild_idx.sql??

--??

--?mkrebuild_idx.sql??

--??

--?rebuild?indexes?to?have?correct?storage?parameters??

--??

--?11/2/98??

select?'alter?index?'?||?index_name?||?'?rebuild?'??

,?'tablespace?indexes?storage?'??

||?'?(?initial?256?k?next?256?k?pctincrease?0?)?;?'??

from?all_indexes??

where?(?tablespace_name?!=?'indexes'??

or?next_extent?!=?(?256?*?1024?)??

)??

and?owner?=?'&owner'??

/??

7.?datatype.sql??

--??

--?datatype.sql??

--??

--?to?check?datatype?consistency?between?two?environments??

--??

--?11/30/98??

select??

table_name,??

column_name,??

data_type,??

data_length,??

data_precision,??

data_scale,??

nullable??

from?all_tab_columns?--?first?environment??

where?owner?=?'&owner'??

minus??

select??

table_name,??

column_name,??

data_type,??

data_length,??

data_precision,??

data_scale,??

nullable??

[email protected]&my_db_link?--?second?environment??

where?owner?=?'&owner2'??

order?by?table_name,?column_name??

8.?obj_coord.sql??

--??

--?obj_coord.sql??

--??

--?to?find?out?any?difference?in?objects?between?two?instances??

--??

--?12/08/98??

select?object_name,?object_type??

from?user_objects??

minus??

select?object_name,?object_type??

[email protected]&my_db_link?

?

?

show_space函数包用法:

create or replace

procedure show_space

( p_segname in varchar2,

p_owner in varchar2 default user,

p_type in varchar2 default 'table',

p_partition in varchar2 default null )

as

l_free_blks number;

l_total_blocks number;

l_total_bytes number;

l_unused_blocks number;

l_unused_bytes number;

l_lastusedextfileid number;

l_lastusedextblockid number;

l_last_used_block number;

procedure p( p_label in varchar2, p_num in number )

is

begin

dbms_output.put_line( rpad(p_label,40,'.') ||

p_num );

end;

begin

?

dbms_space.free_blocks

( segment_owner => p_owner,

segment_name => p_segname,

segment_type => p_type,

partition_name => p_partition,

freelist_group_id => 0,

free_blks => l_free_blks );

?

dbms_space.unused_space

( segment_owner => p_owner,

segment_name => p_segname,

segment_type => p_type,

partition_name => p_partition,

total_blocks => l_total_blocks,

total_bytes => l_total_bytes,

unused_blocks => l_unused_blocks,

unused_bytes => l_unused_bytes,

last_used_extent_file_id => l_lastusedextfileid,

last_used_extent_block_id => l_lastusedextblockid,

last_used_block => l_last_used_block );

p( 'free blocks', l_free_blks );

p( 'total blocks', l_total_blocks );

p( 'total bytes', l_total_bytes );

p( 'unused blocks', l_unused_blocks );

p( 'unused bytes', l_unused_bytes );

p( 'last used ext fileid', l_lastusedextfileid );

p( 'last used ext blockid', l_lastusedextblockid );

p( 'last used block', l_last_used_block );

end;

/

?

sql> set serveroutput on

sql> execute show_space('dsf');

free blocks.............................0

total blocks............................128

total bytes.............................1048576

unused blocks...........................127

unused bytes............................1040384

last used ext fileid....................21

last used ext blockid...................9

last used block.........................1

?

pl/sql procedure successfully completed.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表