巡檢常用:
select instance_name,host_name,startup_time,status,database_status from v$instance;
select name,log_mode,open_mode,protection_mode,database_role from v$database;
tail -100 /ORACLE_HOME/bdump/xxx.log | grep -iE "ora-|err|fail" | sort -u
select name,is_recovery_dest_file,status from v$controlfile;
select tablespace_name,status from dba_tablespaces;
select name,status from v$datafile;
select segment_name,status from dba_rollback_segs -檢查回滾段
select owner,object_name,object_type from dba_objects where status!='VALID' and owner!='SYS' and owner!='SYSTEM'; --檢查無效的對象
select sid,serial#,username,program,machine,status from v$session where sid in (156,157);
select resource_name,max_utilization,initial_allocation,limit_value from v$resource_limit;
select owner,object_name,object_type from dba_objects where status!='VALID' and owner!='SYS' and owner!='SYSTEM';
col FILE_NAME for a45
select file_name,status from dba_data_files;
col MEMBER for a40
select group#,status,type,member from v$logfile;
檢查回滾段狀態:
select segment_name,status from dba_rollback_segs;
set pagesize 100
col SID for 99999
col USERNAME for a8
col PROGRAM for a21
col MACHINE for a21
select sid,serial#,username,program,machine,status from v$session;
檢查表空間使用情況
select f.tablespace_name,a.total,f.free,round((f.free / a.total) * 100) "% Free" from (select tablespace_name, sum(bytes / (1024 * 1024)) total
from dba_data_files group by tablespace_name) a, (select tablespace_name, round(sum(bytes / (1024 * 1024))) free from dba_free_space group by tablespace_name) f
WHERE a.tablespace_name = f.tablespace_name(+) order by "% Free";
检查一些扩展异常的对象
select Segment_Name,Segment_Type,TableSpace_Name, (Extents / Max_extents) * 100 Percent From sys.DBA_Segments Where Max_Extents != 0 and (Extents / Max_extents) * 100 >= 95
order By Percent;
检查system表空间内的内容
select distinct (owner) from dba_tables where tablespace_name = 'SYSTEM' and owner != 'SYS' and owner != 'SYSTEM' union select distinct (owner) from dba_indexes
where tablespace_name = 'SYSTEM' and owner != 'SYS' and owner != 'SYSTEM';
检查对象的下一扩展与表空间的最大扩展值
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;
检查数据库备份日志信息
cat /…/backup-XXX.log | grep –i error
检查backup卷中文件产生的时间
ls –lt /…
检查数据库的等待事件
set pages 80
set lines 120
col event for a40
select sid, event, p1, p2, p3, WAIT_TIME, SECONDS_IN_WAIT from v$session_wait where event not like 'SQL%' and event not like 'rdbms%';
获取Disk Read最高的5条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个系统等待事件
SELECT * FROM (SELECT * FROM V$SYSTEM_EVENT WHERE EVENT NOT LIKE 'SQL%' ORDER BY TOTAL_WAITS DESC) WHERE ROWNUM <= 5;
检查运行很久的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;
检查消耗CPU最高的进程
SET LINE 240
SET VERIFY OFF
COLUMN SID FORMAT 999
COLUMN PID FORMAT 999
COLUMN S_# FORMAT 999
COLUMN USERNAME FORMAT A9
COLUMN PROGRAM FORMAT A29
COLUMN SQL FORMAT A60
COLUMN OSNAME FORMAT A9
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,
TRIM(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%';
检查碎片程度高的表
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);
检查表空间的I/O比例
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;
检查文件系统的I/O比例
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#;
检查死锁及处理查询目前锁对象信息
select sid,serial#,username,SCHEMANAME,osuser,MACHINE,terminal,PROGRAM,owner,object_name,object_type,o.object_id from dba_objects o, v$locked_object l, v$session s
where o.object_id = l.object_id and s.sid = l.session_id;
oracle级kill掉该session:
alter system kill session '&sid,&serial#';
查看是否有僵死进程:
select spid from v$process where addr not in (select paddr from v$session);
检查行链接/迁移
select table_name, num_rows, chain_cnt From dba_tables Where owner = 'NAME01' And chain_cnt <> 0;
检查缓冲区命中率 如果命中率低于90%则需加大数据库参数db_cache_size
SELECT a.VALUE + b.VALUE logical_reads,c.VALUE phys_reads,round(100 * (1 - c.value / (a.value + b.value)), 4) hit_ratio FROM v$sysstat a, v$sysstat b, v$sysstat c
WHERE a.NAME = 'db block gets' AND b.NAME = 'consistent gets' AND c.NAME = 'physical reads';
检查共享池命中率,如低于95%,则需要调整应用程序使用绑定变量,或者调整数据库参数shared pool的大小
select sum(pinhits) / sum(pins) * 100 from v$librarycache;
检查日志缓冲区 如果redo buffer allocation retries/redo entries超过1%,则需要增大log_buffer。
select name,value from v$sysstat where name in ('redo entries','redo buffer allocation retries');
检查系统安全日志信息 在出现的日志信息中没有错误(Invalid、refused)提示,如果没有(Invalid、refused)视为系统正常,出现错误提示,应作出系统告警通知。
检查登录成功的日志:# grep -i accepted /var/log/secure
检查登录失败的日志:# grep -i inval /var/log/secure && grep -i failed /var/log/secure
检查当前crontab任务是否正常 crontab -l
Oracle Job是否有失败
select job,what,last_date,next_date,failures,broken from dba_jobs Where schema_user='XXXXX';
如有问题建议重建job:
exec sys.dbms_job.remove(1);
commit;
exec sys.dbms_job.isubmit(1,'REFRESH_ALL_SNAPSHOT;',SYSDATE+1/1440,'SYSDATE+4/1440');
commit;
监控数据量的增长情况
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;
根据本周每天的检查情况找到空间扩展很快的数据库对象,并采取相应的措施:
--删除历史数据
移动规定数据库中至少保留6个月的历史数据,所以以前的历史数据可以考虑备份然后进行清除以便释放其所占的资源空间。
---扩表空间
alter tablespace add datafile ‘’ size autoextend off;
注意:在数据库结构发生变化时,如增加了表空间,增加了数据文件或重做日志文件这些操作,都会造成Oracle数据库控制文件的变化,DBA应及进行控制文件的备份,备份方法是:
执行SQL语句:alter database backup controlfile to '/home/backup/control.bak'; 或 alter database backup controlfile to trace;
这样,会在USER_DUMP_DEST(初始化参数文件中指定)目录下生成创建控制文件的SQL命令。
检查失效的索引
select index_name, table_name, tablespace_name, status From dba_indexes Where owner = 'XXXXXX' And status <> 'VALID';
注:分区表上的索引status为N/A是正常的,如有失效索引则对该索引做rebuild,如:
alter index INDEX_NAME rebuild tablespace TABLESPACE_NAME;
检查不起作用的约束
SELECT owner, constraint_name, table_name, constraint_type, status FROM dba_constraints WHERE status = 'DISABLE' and constraint_type = 'P';
如有失效约束则启用,如:
alter Table TABLE_NAME Enable Constraints CONSTRAINT_NAME;
检查无效的trigger
SELECT owner, trigger_name, table_name, status FROM dba_triggers WHERE status = 'DISABLED';
如有失效触发器则启用,如:
alter Trigger TRIGGER_NAME Enable;
RAC:
CRS各组件的运行状态检查:
crs_stat -t|awk '{print $4}'|grep -v ONLINE|grep -v GSD
CRS各组件的状态是否为online(GSD服务为offline可以接受)
crsd.log中的错误信息及大小检查
cd $ORA_CRS_HOME/log/[hostname]/crsd/
cat crsd.log|grep -iE 'WARNING|fail|errs|'ORA-'|abort|corrupt|bad|"not complete"'
crsd.log中的关键字:WARNING|fail|errs|ORA-|abort|corrupt|bad|not complete和日志大小
ocssd.log中错误信息和大小检查
cd $ORA_CRS_HOME/log/[hostname]/cssd/
cat ocssd.log|grep -iE 'WARNING|fail|errs|'ORA-'|abort|corrupt|bad|"not complete"'
ocssd.log中的关键字:WARNING|fail|errs|ORA-|abort|corrupt|bad|not complete和日志大小
OCR状态 succded返回4行,且Device不包括+SYS为正常
cd $ORA_CRS_HOME/bin/
ocrcheck root用户
voting disk状态 结果返回三个online为正常,否则不正常
cd $ORA_CRS_HOME/bin/
crsctl query css votedisk root用户执行
RAC中并行参数未设置合适有可能会导致并行操作同时耗尽RAC所有节点的CPU资源
select value from gv$parameter where name='parallel_instance_group' order by value;
影响方式:RAC中参数未设置合适有可能会导致并行操作同时耗尽RAC所有节点的CPU资源
规避方式:提前进行设置,并行查询限制在实例内
DataGaurd检查
主、备库查看当前日志状况
select sequence#,status from v$log;
备库查看RFS接收日志和MRP应用日志同步主库情况
select process, sequence#, status, delay_mins from v$managed_standby;
备库查看已经归档的redo
select REGISTRAR,CREATOR,THREAD#,APPLIED,sequence#,first_change#,next_change#, COMPLETION_TIME from v$archived_log;
主、备库查看是否有gap
主:select status,gap_status from v$archive_dest_status where dest_id=2;
备:select * from v$archive_gap;
1.监控事例的等待:
select event,sum(decode(wait_time,0,0,1)) prev, sum(decode(wait_time,0,1,0)) curr,count(*) from v$session_wait group by event order by 4;
2.回滚段的争用情况:
select name,waits,gets,waits/gets ratio from v r o l l s t a t a , v rollstat a,v rollstata,vrollname b where a.usn=b.usn;
3.监控表空间的I/O比例:
select df.tablespace_name name,df.file_name “ile”,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
4.监控文件系统的I/O比例:
select substr(a.file#,1,2) “#”,substr(a.name,1,30) “name”,a.status,a.bytes,
b.phyrds,b.phywrts
from v d a t a f i l e a , v datafile a,v datafilea,vfilestat b
where a.file#=b.file#
5.在某个用户下找所有的索引:
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 的命中率
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 s y s s t a t a , v sysstat a, v sysstata,vsysstat b, v$sysstat c
where a.statistic# = 38 and b.statistic# = 39
and c.statistic# = 40;
监控 SGA 中字典缓冲区的命中率
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;
监控 SGA 中共享缓存区的命中率,应该小于1%
select sum(pins) “Total Pins”, sum(reloads) “Total Reloads”,
sum(reloads)/sum(pins) *100 libcache
from v l i b r a r y c a c h e ; s e l e c t s u m ( p i n h i t s − r e l o a d s ) / s u m ( p i n s ) " h i t r a d i o " , s u m ( r e l o a d s ) / s u m ( p i n s ) " r e l o a d p e r c e n t " f r o m v librarycache; select sum(pinhits-reloads)/sum(pins) "hit radio",sum(reloads)/sum(pins) "reload percent" from v librarycache;selectsum(pinhits−reloads)/sum(pins)"hitradio",sum(reloads)/sum(pins)"reloadpercent"fromvlibrarycache;
显示所有数据库对象的类别和大小
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%
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
SELECT name, value FROM v$sysstat WHERE name IN (‘sorts (memory)’,
‘sorts (disk)’);
监控当前数据库谁在运行什么SQL语句
SELECT osuser, username, sql_text from v s e s s i o n a , v session a, v sessiona,vsqltext b
where a.sql_address =b.address order by address, piece;
监控字典缓冲区
SELECT (SUM(PINS - RELOADS)) / SUM(PINS) “LIB CACHE” FROM
V L I B R A R Y C A C H E ; S E L E C T ( S U M ( G E T S − G E T M I S S E S − U S A G E − F I X E D ) ) / S U M ( G E T S ) " R O W C A C H E " F R O M V LIBRARYCACHE; SELECT (SUM(GETS - GETMISSES - USAGE - FIXED)) / SUM(GETS) "ROW CACHE" FROM V LIBRARYCACHE;SELECT(SUM(GETS−GETMISSES−USAGE−FIXED))/SUM(GETS)"ROWCACHE"FROMVROWCACHE;
SELECT SUM(PINS) “EXECUTIONS”, SUM(RELOADS) “CACHE MISSES
WHILE EXECUTING” FROM V$LIBRARYCACHE;
后者除以前者,此比率小于1%,接近0%为好。
SELECT SUM(GETS) “DICTIONARY GETS”,SUM(GETMISSES)
“DICTIONARY CACHE GET MISSES”
FROM V$ROWCACHE
找ORACLE字符集
select * from sys.props$ where name=‘NLS_CHARACTERSET’;
监控 MTS
select busy/(busy+idle) “shared servers busy” from v d i s p a t c h e r ; 此 值 大 于 0.5 时 , 参 数 需 加 大 s e l e c t s u m ( w a i t ) / s u m ( t o t a l q ) " i s p a t c h e r w a i t s " f r o m v dispatcher; 此值大于0.5时,参数需加大 select sum(wait)/sum(totalq) "ispatcher waits" from v dispatcher;此值大于0.5时,参数需加大selectsum(wait)/sum(totalq)"ispatcherwaits"fromvqueue where
type=‘dispatcher’;
select count(*) from v d i s p a t c h e r ; s e l e c t s e r v e r s h i g h w a t e r f r o m v dispatcher; select servers_highwater from v dispatcher;selectservershighwaterfromvmts;
servers_highwater接近mts_max_servers时,参数需加大
碎片程度
select tablespace_name,count(tablespace_name) from dba_free_space
group by tablespace_name
having count(tablespace_name)>10;
alter tablespace name coalesce;
alter table name deallocate unused;
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;
select tablespace_name,sum(bytes),max(bytes),count(block_id) from
dba_free_space
group by tablespace_name;
查看碎片程度高的表
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);
表、索引的存储情况检查
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;
select segment_name,count(*) from dba_extents where
segment_type=‘INDEX’ and wner=’&wner’
group by segment_name;
18、找使用CPU多的用户session
12是cpu used by this session
select a.sid,spid,status,substr(a.program,1,40) prog,a.terminal,osuser,value/60/100 value from v s e s s i o n a , v session a,v sessiona,vprocess b,v$sesstat c
where c.statistic#=12 and c.sid=a.sid and a.paddr=b.addr order by value desc;
19、查看运行过的SQL语句:
“SELECT SQL_TEXT FROM V$SQL”
20.监控log_buffer的使用情况:(值最好小于1%,否则增加log_buffer 的大小)
select rbar.name,rbar.value,re.name,re.value,
(rbar.value*100)/re.value||’%’ “radio”
from v s y s s t a t r b a r , v sysstat rbar,v sysstatrbar,vsysstat re
where rbar.name=‘redo buffer allocation retries’
and re.name=‘redo entries’;
SGA相關:
show sga; v$sga, v$sgainfo, v$sgastat
SYS@testdb> select component,current_size/1024/1024,min_size/1024/1024 from v$memory_dynamic_components;
EXP-00091
查詢字符集
數據庫中的字符集
SQL>select * from v$NLS_PARAMETERS WHERE PARAMETER='NLS_CHARACTERSET';
SQL>select userenv('language') from dual; /客戶端字符集
WINDOWS/LINUX 客戶端設置字符集:
set NLS_LANG=AMERICAN_AMERICA.ZHS16GBK/export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
select * from props$;
exp system/sys123sys full=y file=/tmp/foxconn_bmp.dmp log=/tmp/exp.log rows=n
exp system/sys123sys full=y file=/tmp/foxconn_bmp_full.dmp log=/tmp/exp_full.log buffer=65535
exp system/sys123sys@ceswf owner=EMD3WF file=/tmp/EMD3WF.dmp log=/tmp/EMD3WF.log buffer=65535
imp system/Foxconn123@ceswf fromuser=EMD3WF touser=EMD3WF file=/data/oradata/EMD3WF.dmp log=/tmp/EMD3WF.log IGNORE=y commit=y
create user EMD3WF identified by emd3wf;
create tablespace CWMLITE DATAFILE '/home/oracle/oradata/ceswf/cwmlite01.dbf' size 200M AUTOEXTEND ON NEXT 20M MAXSIZE UNLIMITED;
遷移148數據文件
查詢用戶所屬表空間
SQL> select username,default_tablespace from dba_users;
SQL> select tablespace_name,file_id,file_name from dba_data_files;
SQL> alter tablespace WORKFLOWDATA offline;
SQL> ho mv /home/oracle/oradata/ceswf/WORKFLOWDATA01.dbf /data/oradata/ceswf2/
SQL> alter database rename file '/home/oracle/oradata/ceswf/WORKFLOWDATA01.dbf' to '/data/oradata/ceswf2/WORKFLOWDATA01.dbf';
SQL> alter tablespace WORKFLOWDATA online;
SELECT PROPERTY_VALUE FROM DATABASE_PROPERTIES WHERE PROPERTY_NAME = 'DEFAULT_TBS_TYPE';
安裝到86%報錯的地方?
$(MK_EMAGENT_NMECTL) -lnnz11
第一個字是英文L
最後2個是數字11
查看數據庫角色
select database_role from v$database;
查看可切換的角色
select switchover_status from v$database;
查詢保護模式
select protection_mode from v$database;
啟動備庫:
alter database mount standby database;
查看進程:
select process,pid,status,client_process from v$managed_standby;
啟動日志應用
alter database recover managed standby database disconnect from session;
驗證REDO apply進程,MRP0.
select process,pid,status,client_process from v$managed_standby;
查詢當前日誌序列號:
select sequence# from vKaTeX parse error: Expected 'EOF', got '#' at position 52: …select sequence#̲ from vlog;
查詢備庫的日誌號:
查詢歸檔日誌:
select name,sequence#,thread# from v$archived_log;
查看當前用戶所屬對象佔用的空間
SQL>select sum(bytes)/1024/1024 M from user_sgements;
查看多個用戶
SQL>select owner, sum(bytes)/1024/1024/1024 G from dba_segments where owner in (‘INFO’,‘TEST’,‘SCOTT’)
GROUP BY OWNER ORDER BY 2 DESC
查看索引
create index idx_1 on emp(empno);
create unique index idx_1 on emp (ename,deptno)
select index_name,table_name from dba_indexes where owner=‘SCOTT’;
select index_type,table_name,uniqueness,status from user_indexes where index_name = ‘xxx’;
select table_name,column_name from user_ind_columns where index_name = ‘xxx’;
查看約束
select constraint_name, constraint_type, status from user_constraints where table_name=‘xxx’;
select constraint_name, table_name,column_name from user_cons_columns where table_name=‘xxx’;
alter table xxx add (constraint pk_sno primary key(sno),constraint gen_check check (gender in ('男','女'))); --not null不能用add添加,只能用 alter table table_name modify(
列名 constraint 約束名 not null);
alter table xxx drop constraint 約束名; --主鍵約束必須使用CASCADE
alter table xxx disable/enable constraint xxxx;
視圖:
create view as select 語句 with read only with check option;
select or replace text from user_views where view_name=‘xxx’;
序列:
查詢序列:
select min_value,max_value,increment_by,last_number,cycle_flag from user_sequences where sequence_name=‘xxx’
alter sequence
select seq1.nextval(currval) from dual;
同義詞:
create SYNONYM 同義詞 for 用戶名.對象
Production-Standby時時同步
查看tablespace的使用情況(範例三)
select tablespace_name, sum (blocks) as free_block, sum (bytes/(1024*1024)) as free_space, count (*) as pieces from dba_free_space group by tablespace_name
切换Standby 与 PRIMARY 角色:
验证Standby DB数据同步状态
SELECT name,db_unique_name,database_role,protection_mode,SWITCHOVER_STATUS FROM V$DATABASE;
切换当前Primary DB 为Standby DB
ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY WITH SESSION SHUTDOWN; WAIT;
重啟一庫到mount狀態:
shutdown immediate;
startup mount;
select database_role,switchover_status from v$database;
原備庫切換成主庫:
验证Standby DB数据同步状态
SELECT SWITCHOVER_STATUS FROM V$DATABASE;
确认archive log 同步状态与原始Primary DB是否同步
Archive log list
退出自动recover模式
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE Cancel;
切换当前Standby DB为Primary DB
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN; WAIT;
alter database open;
alter system switch logfile;
select sequence#,applied from v$archived_log where sequence#>x;
在新備庫上啟動日誌應用:
recover managed standby database using current logfile disconnect;
recove managed standby database cancel;
alter database recover managed standby database disconnect from session;
alter database open;
驗證REDO apply進程,MRP0.
select process,pid,status,client_process from v$managed_standby;
start real-time apply:
alter database recover managed standby database using current logfile disconnect from session;
stop Redo apply:
alter database recover managed standby database cancel;
check the Redo apply service status:
select thread#,sequence#,process,client_process,status,blocks from v$managed_standby;
check the lastest log sequence:
select sequence#,applied from v$archived_log order by sequence#;
last archived sequence(can use also on primary)
select max(sequence#) from v$archived_log;
last applied sequence
select max(sequence#) from v$archived_log where applied=‘YES’;
Fail over:
備庫上檢查歸檔日誌的GAP;
select thread#,low_sequence#,high_sequence# from v$archive_gap;
now rows selected
將缺少的日誌從主庫複製到備庫,并用以下指令註冊這些歸檔:
alter database register physical logfile ‘filespec1’;
主備庫查詢每個線程對應的最大歸檔日誌序列號:
select thread#,max(sequence#) from v$archived_log group by thread#;
備庫執行下面命令初始化Failover
alter database recover managed standby database finish force;
select database_role,switchover_status from v$database;
FAIL over后,主庫重新加入備庫:必須啟動了Flashback database功能
1.在新主庫上獲得原先備庫切換為主庫時的scn:
select standby_became_primary_scn from v$database;
2.啟動原主庫到Mount狀態:
3.閃回原主庫到SCN:
flashback database to scn xxxxx;
4.alter database convert to physical standby;
5.shutdown immediate;
6.startup mount;
7.alter system archive log current;
8.select dest_id,dest_name,status,destination from v$archive_dest_status;
9.如果不是valid,用下面指令啟動:
alter system set log_archive_dest_state_n=enable;
10.alter database recover managed standby database disconnect from session;
11.如果是實時應用:
alter database recover managed standby database using current logfile disconnect;
select name,open_mode,protection_mode,database_role,switchover_status from v$database;
取消standby的redo應用:
alter database recover managed standby database cancel;
standby_file_management參數
alter system set standby_file_management=auto/manual;
查詢當前保護模式和角色等信息:
select protection_mode,protection_level,database_role,switchover_status from vKaTeX parse error: Expected 'EOF', got '#' at position 68: …rocess,sequence#̲,status from vmanaged_standby;
查詢邏輯standby已歸檔日誌文件信息:
select name,sequence#,applied,completion_time from v a r c h i v e d l o g ; 查 詢 當 前 d a t a g u a r d 記 錄 的 事 件 信 息 s e l e c t m e s s a g e f r o m v archived_log; 查詢當前dataguard記錄的事件信息 select message from v archivedlog;查詢當前dataguard記錄的事件信息selectmessagefromvdataguard_status;
取消standby的redo應用:
alter database recover managed standby database cancel;
standby_file_management參數
alter system set standby_file_management=auto/manual;
RMAN
快閃區需要設置兩個參數:
DB_RECOVERY_FILE_DEST_SIZE,DB_RECOVERY_FILE_DEST
V$RECOVERY_FILE_DEST 查看快閃恢復區的空間使用情況及文件數量
增加空間:
1.alter system set db_recovery_file_dest_size=4g;
2.crosscheck和delete obsolete
3.alter system set db_recovery_file_dest=’/u01/backup/newflasharea’; --修改新的路徑
select file_type,percent_space_used,percent_space_reclaimable,number_of_files from v$flash_recovery_area_usage;
RMAN>show all;
configure default device type to disk;
configure backup optimization off/on;
configure controlfile autobackup on/off;
configure device type disk parallelism 3 backup type to copy;
沒啟用快閃備份控制文件:
RMAN>backup current controlfile format ‘f:\pump\backup_ctl_%u.dbf’;
啟用快閃:
RMAN>backup current controlfile;
聯機備份:
RMAN>backup as compressed backupset database plus archivelog delete all input;
執行操作系統腳本
d:>rman catalog rman_backup/rman@orcl target system/Oracle@orcl cmdfile ‘rman_backup.rcv’
rman>restore controlfile from ‘xxxx/xxx’
alter database mount;
restore database;
recover database noredo;
alter database open resetlogs;
rman>backup validate datafile 6;
sql>select * from v$database_block_corruption;
rman>blockrecover datafile 6 block 1119 from backupset;
rman>validate backupset 5;
rman>list backup summary;
rman>restore tablespace users validate; 驗證
rman>restore datafile ‘/u01/app/oracle/oradata/prod/system01.dbf’ validate;
rman>restore database preview; 驗證所需文件是否存在。
rman>list backup of tablespace users;
rman>list backup of datafile 1;
rman>list backp of controlfile/spfile
rman>list copy of controlfile;
alter system set log_archive_max_processes=3;
show parameter log_archive_dest;
alter system set log_archive_dest_1=‘location=/u01/arc1 mandatory/optional’
show parameter log_archive_min_succeed_dest=2
sql>col file_name for a47
sql>col tablespace_name for a10
sql>select file_id,file_name,tablespace_name from dba_data_files;
select * from vKaTeX parse error: Expected 'EOF', got '#' at position 46: …eckpoint_change#̲,file# from vdatafile; 查看所有數據文件SCN號
SQL> select * from gv$lock where block=1;
alter system kill session ‘sid,serial#’;
select spid,osuser,s.program from v s e s s i o n s , v session s, v sessions,vprocess p where s.paddr=p.addr and s.sid=&sid; /根據sid查找操作系統的spid
[oracle@ostjgscmte02 ~]$ oerr ora 00257
select sid,serial#,username,program,machine,status from v$session where status=‘ACTIVE’;
select spid,osuser,s.program from v s e s s i o n s , v session s, v sessions,vprocess p where s.paddr=p.addr and s.sid=&sid;
alter system kill session ‘13,1063’ immediate;
select * from v$flash_recovery_area_usage;
show parameter db_recovery;
alter system set db_recovery_file_dest_size=10G;
SQL> select * from v$flash_recovery_area_usage;
SQL> show parameter db_recovery;
RMAN> DELETE ARCHIVELOG ALL COMPLETED BEFORE ‘SYSDATE-2’;
RMAN> delete archivelog until time ‘sysdate-7’;
RMAN>delete force noprompt archivelog until time “to_date(‘2019-08-12 13:30:00’,‘yyyy-mm-dd hh24:mi:ss’)”;
RMAN>delete force noprompt archivelog until sequence 123;
RMAN>list archivelog all;
list expired archivelog all;
/home/oracle/fast_recovery_area/CESWF/archivelog
select * from dba_tablespaces;
select * from dba_data_files;
select group#,bytes/(1024*1024) from v$log;
alter database add logfile group 5 ‘/home/oracle/oradata/ceswf/redo05.log’ size 50m;
SELECT * FROM (SELECT hash_value,address,substr(sql_text,1,40) sql, buffer_gets, executions, buffer_gets/executions “Gets/Exec”
FROM V$SQLAREA WHERE buffer_gets > 100000 AND executions > 10 ORDER BY buffer_gets DESC) WHERE rownum <= 10;
脚本: FREESPACE.SQL
SELECT a.tablespace_name, ROUND (100 - b.free / a.total *100) used_pct,
ROUND ( a.total / 1024 / 1024) “total(MB)”,
ROUND ( b.free / 1024 / 1024) “Free_total(MB)”,
ROUND ( b.max_free / 1024 / 1024) “Free_max(MB)”,b.free_cnt fragment
from (select tablespace_name, sum(bytes) total from dba_data_files group by tablespace_name) a,
(select tablespace_name,sum(bytes) free, max(bytes) max_free,count(bytes) free_cnt from dba_free_space
group by tablespace_name) b where a.tablespace_name=b.tablespace_name
優化
SYS@testdb> show parameter optimizer_mode;
實例級:
alter system set optimizer_mode=first_row_10 scope=both;
會話級
alter session set optimizer_mode=all_rows
查看當前運行的JOBs信息:
SYS@testdb> select job_name,state,owner from dba_scheduler_jobs;
查看scott的表的統計分析情況:
SYS@testdb> select last_analyzed,table_name,owner,num_rows,sample_size from dba_tables where owner=‘SCOTT’;
DBMS_STATS手工收集統計信息:
gather_database_statistics 統計全庫
gather_schema_statistics 統計模式
gather_table_statistics 統計一個表
gather_system_stats 統計操作系統數據 保存在sys.aux_stats$中
gather_fixed_objects_stats 收集固定字典表的統計數據 gather_dictionary_stats
SQL>execute dbms_stats.gather_schema_stats(ownname=>'scott');
show parameter job_queue_processes;
select num_rows,avg_space,avg_row_len,num_freelist_blocks,last_analyzed from dba_tab_statistics where table_name='EMP';
dba_tab_col_statistics
函數索引:
create index scott_emp_upper_ename on scott.emp(upper(ename));
執行計劃:
SQL>@/home/oracle/product/11.2.4/dbhome_1/rdbms/admin/utlxplan.sql
desc plan_table;
SYS@testdb> explain plan for
2 select * from scott.emp;
Explained.
SYS@testdb> col id for 999
SYS@testdb> col operation for a20
SYS@testdb> col options for a20
SYS@testdb> col object_name for a20
SYS@testdb> select id,operation,options,object_name,position from plan_table;
ID OPERATION OPTIONS OBJECT_NAME POSITION
---- -------------------- -------------------- -------------------- ----------
0 SELECT STATEMENT 3
1 TABLE ACCESS FULL EMP 1
使用AUTOTRACE指令:
alter system set sql_trace = true;
show parameter sql_trace;
YS@testdb> set autotrace traceonly;
SYS@testdb> select count(*) from scott.emp;
Execution Plan
----------------------------------------------------------
Plan hash value: 2937609675
-------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
-------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 1 (0)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | INDEX FULL SCAN| PK_EMP | 14 | 1 (0)| 00:00:01 |
-------------------------------------------------------------------
Statistics
----------------------------------------------------------
1 recursive calls
0 db block gets
1 consistent gets
1 physical reads
0 redo size
526 bytes sent via SQL*Net to client
524 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
SYS@testdb> set autotrace off;
SYS@testdb> alter system set sql_trace = false;
查看執行計劃:
SYS@testdb> select ename,job,mgr,deptno from scott.emp where sal*12<30000;
SYS@testdb> select id,operation,options,object_name,object_owner from v$sql_plan where object_name like 'EMP%';
ID OPERATION OPTIONS OBJECT_NAME OBJECT_OWNER
---- -------------------- -------------------- -------------------- ------------------------------
1 TABLE ACCESS BY INDEX ROWID EMP SCOTT
select sql_text,executions,disk_reads from v$sql where disk_reads>&number order by disk_reads desc;
select sql_text,buffer_gets,parse_calls from v$sql where buffer_gets>&number order by buffer_gets
select sql_text,cpu_time,buffer_gets from (select sql_text,cpu_time,buffer_gets from v$sql order by cpu_time desc) where rownum < 24
SYS@testdb> show parameter sga_max_size; 修改需要重啟
查看等待事件:
select sw.sid,s.username,sw.event,sw.wait_time from v$session s,v$session_wait sw where sw.event not like 'rdbms%' and sw.sid=s.sid
order by sw.wait_time,sw.event;
查看latch相關信息:
v$latch
SYS@testdb> select name,value/1024/1024 "M" from v$parameter where name='log_buffer'; 修改此值需要重啟
v$sysstat
v$pgastat
SYS@testdb> select name,value,isdefault from v$parameter where name in ('pga_aggregate_target','workar
ea_size_policy');
NAME VALUE ISDEFAULT
-------------------- ------------------------------ ---------
pga_aggregate_target 0 TRUE
workarea_size_policy AUTO TRUE
AWR
SYS@testdb> show parameter statistics_level;
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
statistics_level string TYPICAL
select max(snap_id) from dba_hist_snapshot;
SYS@testdb> begin
2 dbms_workload_repository.create_snapshot();
3 end;
4 /
select min(snap_id),max(snap_id) from dba_hist_snapshot;
查看快照保留策略
SYS@testdb> select dbid,snap_interval,retention from dba_hist_wr_control
創建報告:
@?/rdbms/admin/awrrpt.sql
@/home/oracle/product/11.2.3/db_1/rdbms/admin/awrrpt.sql
awrrpt_1_55533_55538.html
ASH
@?/rdbms/admin/ashrpt.sql
select * from v$sysstat;
select * from dba_tablespaces;
select * from dba_users;
select * from dba_directories;
select * from all_tab_privs;
select * from user_tab_privs;
select * from all_tab_privs;
臨時表空間使用:
select f.tablespace_name,d.file_name “Tempfile name”,round((f.bytes_free + f.bytes_used) /1024 /1024,2) “Total MB”,
round((f.bytes_free + f.bytes_used) - nvl(p.bytes_used,0) /1024 /1024,2) “Free MB”,
round(nvl(p.bytes_used,0) /1024 /1024,2) “Used MB”,
round((round(nvl(p.bytes_used,0) /1024 /1024,2)/round((f.bytes_free + f.bytes_used)/1024/1024,2))*100,2) as “Used_Rate”
from sys.v_KaTeX parse error: Expected group after '_' at position 45: …_FILES d, SYS.V_̲TEMP_EXTENT_POOL p
where f.tablespace_name(+) = d.tablespace_name and f.file_id(+) = d.file_id and p.file_id(+) = d.file_id;
alter TABLESPACE TEMP ADD TEMPFILE ‘/home/oracle/oradata/ceswf/temp02.dbf’ size 100M autoextend on next 10M;
alter database TEMPFILE ‘/home/oracle/oradata/ceswf/temp01.dbf’ RESIZE 100M;
select * from dba_temp_files;
select b.file_id, b.tablespace_name,b.bytes/1024/1024 || ‘M’,(b.bytes - sum(nvl(a.bytes,0)))/1024/1024 || ‘M’ “used”,
sum(nvl(a.bytes,0)))/1024/1024 || ‘M’ “leftspace” from dba_free_space a, dba_data_files b where a.file_id=b.file_id and
b.tablespace_name = ‘WORKFLOWDATA’;
select tablespace_name, file_id, file_name,round(bytes/(1024*1024),0) total_space from dba_data_files
where TABLESPACE_NAME = ‘WORKFLOWDATA’;
lsnrctl set log_status off
mv listener.log listener.log.10
lsnrctl set log_status on
expdp system/sys123sys directory=EXPBAK dumpfile=exp20190808_SFIS1.dmp tables=SFIS1.C_COMPONENT_LANG_T,SFIS1.C_MESSAGE_T nologfile=y job_name=SFIS1_tables
create directory expbak as ‘/data/expbak’;
grant read,write on directory expbak to system;
select grantee,privilege from dba_sys_privs where grantee=‘SFIS1’;
SYS@testdb> select * from dba_role_privs a where a.grantee=‘U1’;
impdp system/Foxconn123 directory=expbak dumpfile=exp20190808_SFIS1.dmp tables=SFIS1.C_COMPONENT_LANG_T,SFIS1.C_MESSAGE_T remap_schema=SFIS1:SFIS1 remap_tablespace=log_data:log_data schemas=SFIS1 table_exists_action=replac
e transform=segment_attributes:n
[oracle@nick-testdb ~]$ impdp SFIS1/SFIS1 directory=expbak dumpfile=exp20190808_SFIS1.dmp tables=SFIS1.C_COMPONENT_LANG_T,SFIS1.C_MESSAGE_T table_exists_action=replace
transform=segment_attributes:n
create table table_name_new as select * from table_name_old
create table table_name_new as select * from table_name_old where 1=2;
或者:
create table table_name_new like table_name_old
如果两个表结构一样:
insert into table_name_new select * from table_name_old
如果两个表结构不一样:
insert into table_name_new(column1,column2…) select column1,column2… from table_name_old
GRANT 權限 ON 資料庫物件 TO 使用者名稱;
Sample:開放 USMS.ER01 TABLE 權限給 SREV
– Sample 1
– QUERY REWRITE:
GRANT DELETE,INSERT,SELECT,QUERY REWRITE ON USMS.ER01 TO SREV ;
– Sample 2
– 開放全部功能,並給與轉授權權限
GRANT ALL ON USMS.ER01 TO SREV WITH GRANT OPTION;
轉授權
將 ER01 的權限開放給 ER02,ER02 的資料若需要再開放給其他人讀取…其他功能,則需要可轉授權
詳:http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/12/08/with-grant-option.aspx
★ 查詢被授與權限
SELECT * FROM USER_TAB_PRIVS WHERE TABLE_NAME = ‘資料表名稱’
– Sample
SELECT * FROM USER_TAB_PRIVS WHERE TABLE_NAME = ‘ER01’
grant drop any table to EPO_AP;
74.72
SYS EXPDATA /data/expdata
/data/expdata/exp20190808_SFIS1.dmp
impdp system/sys123sys directory=EXPDATA dumpfile=exp20190808_SFIS1.dmp tables=SFIS1.C_COMPONENT_LANG_T,SFIS1.C_MESSAGE_T transform=segment_attributes
:n