淘先锋技术网

首页 1 2 3 4 5 6 7

一线运维 DBA 五年经验常用 SQL 大全(一)
1.查看表空间使用率。
set line 220
select total.tablespace_name,round(total.MB, 2) as Total_MB,round(total.MB - free.MB, 2) as Used_MB,round((1 - free.MB / total.MB) * 100, 2) || ‘%’ as Used_Pct
from (select tablespace_name,sum(bytes) / 1024 / 1024 as MB from dba_free_space group by tablespace_name) free,
(select tablespace_name,sum(bytes) / 1024 / 1024 as MB from dba_data_files group by tablespace_name) total
where free.tablespace_name = total.tablespace_name order by used_pct desc;
1.1查询单个表空间使用率。
select total.tablespace_name,
round(total.MB, 2) as Total_MB,
round(total.MB - free.MB, 2) as Used_MB,
round((1 - free.MB / total.MB) * 100, 2) || ‘%’ as Used_Pct from
(select tablespace_name,sum(bytes) / 1024 / 1024 as MB from dba_free_space where tablespace_name=‘TBL_SPACE’ group by tablespace_name) free,
(select tablespace_name,sum(bytes) / 1024 / 1024 as MB from dba_data_files where tablespace_name=‘TBL_SPACE’ group by tablespace_name) total
where free.tablespace_name = total.tablespace_name order by used_pct desc;
2.查看临时表空间数据文件位置,大小,及是否自动扩展。
select tablespace_name,file_name,bytes/1024/1024 mb ,autoextensible from dba_data_files where tablespace_name in (’’) order by tablespace_name;
select tablespace_name,file_name,bytes/1024/1024 file_size,autoextensible from dba_temp_files;
–查看所有临时表空间大小
SELECT D.TABLESPACE_NAME,SPACE “SUM_SPACE(M)”,BLOCKS SUM_BLOCKS,
USED_SPACE “USED_SPACE(M)”,ROUND(NVL(USED_SPACE,0)/SPACE100,2) “USED_RATE(%)”,
NVL(FREE_SPACE,0) “FREE_SPACE(M)”
FROM
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES)/(1024
1024),2) SPACE,SUM(BLOCKS) BLOCKS
FROM DBA_TEMP_FILES
GROUP BY TABLESPACE_NAME) D,
(SELECT TABLESPACE_NAME,ROUND(SUM(BYTES_USED)/(10241024),2) USED_SPACE,
ROUND(SUM(BYTES_FREE)/(1024
1024),2) FREE_SPACE
FROM V T E M P S P A C E H E A D E R G R O U P B Y T A B L E S P A C E N A M E ) F W H E R E D . T A B L E S P A C E N A M E = F . T A B L E S P A C E N A M E ( + ) ; 3. 查 看 A S M 磁 盘 空 间 。 s e l e c t n a m e , s t a t e , t y p e , f r e e m b , t o t a l m b , u s a b l e f i l e m b f r o m v TEMP_SPACE_HEADER GROUP BY TABLESPACE_NAME) F WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME(+); 3.查看ASM磁盘空间。 select name,state,type,free_mb,total_mb,usable_file_mb from v TEMPSPACEHEADERGROUPBYTABLESPACENAME)FWHERED.TABLESPACENAME=F.TABLESPACENAME(+);3.ASMselectname,state,type,freemb,totalmb,usablefilembfromvasm_diskgroup;
4.查询oracle的连接数
select count() from v s e s s i o n ; 5. 查 看 不 同 用 户 的 连 接 数 s e l e c t u s e r n a m e , c o u n t ( u s e r n a m e ) f r o m v session; 5.查看不同用户的连接数 select username,count(username) from v session;5.selectusername,count(username)fromvsession where username is not null group by username;
6.查看回收站
show recyclebin
7.清空回收站
PURGE recyclebin
8.删除表,不进入回收站
drop table tableName purge;
9.查询用户下所有创建表的语句
select
‘select dbms_metadata.get_ddl(’||’’’’||‘TABLE’||’’’’||’,’||’’’’||table_name||’’’’||’) from dual;’||chr(10)||‘select ‘||’’’’||’/’||’’’’|| ’ from dual;’
from user_tables;
10.查询当时创建用户的语句
select dbms_metadata.get_ddl(‘USER’,‘USERNAME’) from dual;
11.查询普通用户语句
select username from dba_users where account_status=‘OPEN’;
12.修改数据文件大小
alter database datafile ‘&path_name’ resize 10G;
alter database datafile &{file_id} resize 10G;
13.添加数据文件
alter tablespace &tablespace_name ADD datafile ‘&datafile_name’ SIZE xxx;
14.临时表空间扩容,填加临时表空间数据文件
ALTER TABLESPACE &tablespace_name ADD TEMPFILE ‘&datafile_name’ SIZE xxx;
15.大文件表空间扩容
ALTER TABLESPACE &tablespace_name RESIZE xxx;
16.查询告警日志文件位置
show parameter dump
select * from vKaTeX parse error: Expected 'EOF', got '#' at position 191: …,b.sid,b.serial#̲,logon_time fro…lock_object a,v s e s s i o n b w h e r e a . s e s s i o n i d = b . s i d o r d e r b y b . l o g o n t i m e ; 21. 查 询 数 据 库 中 所 有 用 户 下 占 用 物 理 空 间 内 存 大 小 s e l e c t o w n e r , s u m ( b y t e s ) / 1024 / 1024 M B f r o m d b a s e g m e n t s g r o u p b y o w n e r ; 22. 日 志 切 换 a l t e r s y s t e m s w i t c h l o g f i l e ; 23. 查 看 归 档 是 否 开 启 a r c h i v e l o g l i s t ; s e l e c t l o g m o d e f r o m v session b where a.session_id = b.sid order by b.logon_time; 21.查询数据库中所有用户下占用物理空间内存大小 select owner,sum(bytes)/1024/1024 MB from dba_segments group by owner; 22.日志切换 alter system switch logfile; 23.查看归档是否开启 archive log list; select log_mode from v sessionbwherea.sessionid=b.sidorderbyb.logontime;21.selectowner,sum(bytes)/1024/1024MBfromdbasegmentsgroupbyowner;22.altersystemswitchlogfile;23.archiveloglist;selectlogmodefromvdatabase;
24.开启归档
alter system set log_archive_dest_1=‘LOCATION=+ARCH’ scope=both sid=’
’;
shu immediate
startup mount
alter database archivelog
alter database open
25.监听注册
alter system set LOCAL_LISTENER=’(ADDRESS = (PROTOCOL = TCP)(HOST = JiekeXu)(PORT = 1522))’;
alter system set LOCAL_LISTENER=’(ADDRESS = (PROTOCOL = TCP)(HOST = 10.X.X.6)(PORT = 1521))’ SID=‘JiekeDBR2’ scope=both;
26.数据库注册监听
alter system register;
27.创建DBLINK
create public database link HO
connect to SKDATA identified by oracle
using ‘(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.X.X.6)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = JiekeXuDB)
)
)’;
28.删除DBLINK
drop public database link &dblinkname;
29.查询DBLINK
select * from dba_db_links
30.查询本地用户登陆进程
ps -ef|grep LOCAL=NO
31.批量杀进程执行 ,注意检查oracle_sid。
ps -ef|grep $ORACLE_SID|grep -v ora_|grep LOCAL=NO|awk ‘{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲'|xargs kill -9…database;
33.查询控制文件中数据文件的SCN命令
select name,file#,checkpoint_change# from vKaTeX parse error: Expected 'EOF', got '#' at position 55: …eckpoint_change#̲ from vdatafile_header;
35. 控制文件中的数据文件终止scn
select name,last_change# from v d a t a f i l e ; 36. 解 锁 用 户 命 令 a l t e r u s e r 用 户 名 a c c o u n t u n l o c k ; − − − − 这 个 只 会 解 锁 账 号 , 而 不 会 取 消 密 码 过 期 。 37. 设 置 密 码 无 期 限 A L T E R P R O F I L E D E F A U L T L I M I T P A S S W O R D L I F E T I M E U N L I M I T E D ; 将 概 要 文 件 ( 如 d e f a u l t ) 的 密 码 有 效 期 由 默 认 的 180 天 修 改 成 “ 无 限 制 ” ( 修 改 之 后 不 需 要 重 启 动 数 据 库 , 会 立 即 生 效 ) 38. 查 询 字 符 集 命 令 s e l e c t u s e r e n v ( ′ l a n g u a g e ′ ) f r o m d u a l ; 39. 查 询 数 据 库 里 某 个 表 空 间 里 所 占 用 的 大 小 : s e l e c t O W N E R , S E G M E N T T Y P E , T A B L E S P A C E N A M E , B Y T E S / 1024 / 1024 a s M B f r o m d b a s e g m e n t s w h e r e T A B L E S P A C E N A M E = ′ A T 0 1 ′ o r d e r b y 4 d e s c ; 40 关 于 D G 认 清 主 备 库 。 s e l e c t d . N A M E , d . L O G M O D E , d . O P E N M O D E , d . P R O T E C T I O N M O D E , d . D A T A B A S E R O L E f r o m v datafile; 36.解锁用户命令 alter user 用户名 account unlock; ----这个只会解锁账号,而不会取消密码过期。 37.设置密码无期限 ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED; 将概要文件(如default)的密码有效期由默认的180天修改成“无限制”(修改之后不需要重启动数据库,会立即生效) 38.查询字符集命令 select userenv ('language') from dual; 39.查询数据库里某个表空间里所占用的大小: select OWNER,SEGMENT_TYPE,TABLESPACE_NAME,BYTES/1024/1024 as MB from dba_segments where TABLESPACE_NAME='AT01' order by 4 desc; 40关于DG认清主备库。 select d.NAME,d.LOG_MODE,d.OPEN_MODE,d.PROTECTION_MODE,d.DATABASE_ROLE from v datafile;36.alteruseraccountunlock;37.ALTERPROFILEDEFAULTLIMITPASSWORDLIFETIMEUNLIMITED;(default)18038.selectuserenv(language)fromdual;39.selectOWNER,SEGMENTTYPE,TABLESPACENAME,BYTES/1024/1024asMBfromdbasegmentswhereTABLESPACENAME=AT01orderby4desc;40DGselectd.NAME,d.LOGMODE,d.OPENMODE,d.PROTECTIONMODE,d.DATABASEROLEfromvdatabase d;
名字,日志模式,开启模式,保护模式,数据库角色。其中数据库角色就是看主备库的.
PRIMARY为主库 PHYSICAL STANDBY物理备库,LOGICAL STANDBY逻辑备库.
在备库中查询:
show parameter fal_server
得出的值在与tns中找相匹配的server_name然后在寻找对应的IP地址。
开启恢复
SQL> recover managed standby database disconnect from session using current logfile;
ADG相关命令:
select name,db_unique_name,database_role,protection_mode,open_mode from vKaTeX parse error: Expected 'EOF', got '#' at position 51: …status,sequence#̲ from vmanaged_standby;–查看相关进程
recover managed standby database cancel; --关闭mrp功能
recover managed standby database disconnect from session using current logfile;–开启当前日志应用
alter database recover managed standby database disconnect from session;—开启不同步当前日志应用
select dest_id,error,status,log_sequence,applied_scn from vKaTeX parse error: Expected 'EOF', got '#' at position 40: …SELECT SEQUENCE#̲,APPLIED FROM VARCHIVED_LOG ORDER BY SEQUENCE#;—查询传输至备库的日志是否应用。
41.添加ASM磁盘所需命令
在AIX系统中查询新加入的盘符 lspv
在AIX系统中查询盘空间大小: getconf DISK_SIZE /dev/hdisk1
在数据库中查询ASM的中是否使用了此硬盘:col PATH for a44
select GROUP_NUMBER,DISK_NUMBER,TOTAL_MB/1024,FREE_MB/1024,NAME,FAILGROUP,PATH,FAILGROUP_TYPE from v a s m d i s k ; 42. 使 用 轻 松 连 接 模 式 远 程 登 录 数 据 库 s q l p l u s s j g l t / s j g l t @ 1 X . 1 X X . 1 X 6.16 : 1521 / o r c l 43. 更 改 备 份 保 存 时 间 a l t e r s y s t e m s e t c o n t r o l f i l e r e c o r d k e e p t i m e = 39 ; 44. 查 看 a s m 磁 盘 使 用 哪 些 盘 命 令 : c o l n a m e f o r a 20 c o l p a t h f o r a 20 c o l F A I L G R O U P f o r a 20 s e l e c t G R O U P N U M B E R , D I S K N U M B E R , T O T A L M B / 1024 , F R E E M B / 1024 , N A M E , F A I L G R O U P , P A T H , F A I L G R O U P f r o m v asm_disk; 42. 使用轻松连接模式远程登录数据库 sqlplus sjglt/[email protected]:1521/orcl 43. 更改备份保存时间 alter system set control_file_record_keep_time=39; 44.查看asm磁盘使用哪些盘命令: col name for a20 col path for a20 col FAILGROUP for a20 select GROUP_NUMBER,DISK_NUMBER,TOTAL_MB/1024,FREE_MB/1024,NAME,FAILGROUP,PATH,FAILGROUP from v asmdisk;42.使sqlplussjglt/sjglt@1X.1XX.1X6.16:1521/orcl43.altersystemsetcontrolfilerecordkeeptime=39;44.asm使colnamefora20colpathfora20colFAILGROUPfora20selectGROUPNUMBER,DISKNUMBER,TOTALMB/1024,FREEMB/1024,NAME,FAILGROUP,PATH,FAILGROUPfromvasm_disk;
45.查询oracle连接最大值命令:
select resource_name,MAX_UTILIZATION,LIMIT_VALUE from v r e s o u r c e l i m i t w h e r e r e s o u r c e n a m e i n ( ′ p r o c e s s e s ′ , ′ s e s s i o n s ′ ) ; M A X U T I L I Z A T I O N 代 表 数 据 库 自 上 次 启 动 以 来 达 到 的 最 大 值 , L I M I T V A L U E 代 表 设 置 的 最 大 值 。 46. 查 询 锁 S Q L : s e l e c t ′ b l o c k e r ( ′ ∣ ∣ l b . s i d ∣ ∣ ′ : ′ ∣ ∣ s b . u s e r n a m e ∣ ∣ ′ ) − s q l : ′ ∣ ∣ q b . s q l t e x t b l o c k e r s , ′ w a i t e r ( ′ ∣ ∣ l w . s i d ∣ ∣ ′ : ′ ∣ ∣ s w . u s e r n a m e ∣ ∣ ′ ) − s q l : ′ ∣ ∣ q w . s q l t e x t w a i t e r s f r o m v resource_limit where resource_name in ('processes','sessions'); MAX_UTILIZATION代表数据库自上次启动以来达到的最大值,LIMIT_VALUE代表设置的最大值。 46.查询锁SQL: select 'blocker('||lb.sid||':'||sb.username||')-sql:'|| qb.sql_text blockers, 'waiter ('||lw.sid||':'||sw.username||')-sql:'|| qw.sql_text waiters from v resourcelimitwhereresourcenamein(processes,sessions);MAXUTILIZATIONLIMITVALUE46.SQL:selectblocker(lb.sid:sb.username)sql:qb.sqltextblockers,waiter(lw.sid:sw.username)sql:qw.sqltextwaitersfromvlock lb,
v l o c k l w , v lock lw, v locklw,vsession sb,
v s e s s i o n s w , v session sw, v sessionsw,vsql qb,
v s q l q w w h e r e l b . s i d = s b . s i d a n d l w . s i d = s w . s i d a n d s b . p r e v s q l a d d r = q b . a d d r e s s a n d s w . s q l a d d r e s s = q w . a d d r e s s a n d l b . i d 1 = l w . i d 1 a n d s w . l o c k w a i t i s n o t n u l l a n d s b . l o c k w a i t i s n u l l a n d l b . b l o c k = 1 ; 47. 查 询 数 据 库 数 据 量 s e l e c t s u m ( b y t e s ) / 1024 / 1024 / 1024 t o t a l g b f r o m d b a s e g m e n t s 48. 查 看 s q l 内 容 s e l e c t s q l f u l l t e x t f r o m v sql qw where lb.sid=sb.sid and lw.sid=sw.sid and sb.prev_sql_addr=qb.address and sw.sql_address=qw.address and lb.id1=lw.id1 and sw.lockwait is not null and sb.lockwait is null and lb.block=1 ; 47.查询数据库数据量 select sum(bytes)/1024/1024/1024 total_gb from dba_segments 48.查看sql内容 select sql_fulltext from v sqlqwwherelb.sid=sb.sidandlw.sid=sw.sidandsb.prevsqladdr=qb.addressandsw.sqladdress=qw.addressandlb.id1=lw.id1andsw.lockwaitisnotnullandsb.lockwaitisnullandlb.block=1;47.selectsumbytes/1024/1024/1024totalgbfromdbasegments48.sqlselectsqlfulltextfromvsqlarea where sql_id=’&sql_id’;
49.查看sql的执行计划
select * from vKaTeX parse error: Expected 'EOF', got '&' at position 24: … where sql_id='&̲sql_id'; 50.查看绑…sql_bind_capture sbc where sql_id=’&sql_id’;
51.关于rman归档问题
rman> crosscheck archivelog all;
rman> delete noprompt expired archivelog all;
rman> delete force noprompt archivelog until time ‘sysdate - 30’;
单节点:
delete noprompt archivelog until sequence ${Seq};
rac(thread后面加节点数):
delete noprompt archivelog until sequence 1 thread C u r T h r e a d ; 删 除 7 天 前 的 归 档 : D E L E T E A R C H I V E L O G A L L C O M P L E T E D B E F O R E ′ S Y S D A T E − 7 ′ ; 按 时 间 删 除 归 档 : d e l e t e f o r c e a r c h i v e l o g a l l c o m p l e t e d b e f o r e ′ S Y S D A T A − 1 / 2 4 ′ ; 查 看 归 档 每 天 切 换 频 率 以 及 大 小 s e l e c t m a x ( f i r s t t i m e ) m a x f i r s t t i m e , t o c h a r ( f i r s t t i m e , ′ y y y y − m m − d d ′ ) d a y , c o u n t ( r e c i d ) c o u n t n u m b e r , c o u n t ( r e c i d ) ∗ 200 s i z e m b f r o m v {CurThread}; 删除7天前的归档: DELETE ARCHIVELOG ALL COMPLETED BEFORE 'SYSDATE-7'; 按时间删除归档: delete force archivelog all completed before 'SYSDATA-1/24'; 查看归档每天切换频率以及大小 select max (first_time) max_first_time, to_char (first_time, 'yyyy-mm-dd') day, count (recid) count_number, count (recid) * 200 size_mb from v CurThread;7DELETEARCHIVELOGALLCOMPLETEDBEFORESYSDATE7;deleteforcearchivelogallcompletedbeforeSYSDATA1/24;selectmax(firsttime)maxfirsttime,tochar(firsttime,yyyymmdd)day,count(recid)countnumber,count(recid)200sizembfromvlog_history
group by to_char (first_time, ‘yyyy-mm-dd’)
order by 1;
按天计算日志生成量
set pages 9999
select to_char(first_time,‘yyyymmdd’),count(*) from vKaTeX parse error: Expected 'EOF', got '#' at position 141: …A.SID, A.SERIAL#̲, A.STATUS, C.P…SESSION A,
V S Q L T E X T C W H E R E A . S I D I N ( S E L E C T D I S T I N C T T 2. S I D F R O M V SQLTEXT C WHERE A.SID IN (SELECT DISTINCT T2.SID FROM V SQLTEXTCWHEREA.SIDIN(SELECTDISTINCTT2.SIDFROMVLOCKED_OBJECT T1,
V S E S S I O N T 2 W H E R E T 1. S E S S I O N I D = T 2. S I D ) A N D A . S Q L A D D R E S S = C . A D D R E S S ( + ) O R D E R B Y C . P I E C E ; 53. 查 询 D B 负 载 情 况 S E L E C T ∗ F R O M ( S E L E C T A . I N S T A N C E N U M B E R , A . S N A P I D , B . B E G I N I N T E R V A L T I M E + 0 B E G I N T I M E , B . E N D I N T E R V A L T I M E + 0 E N D T I M E , R O U N D ( V A L U E − L A G ( V A L U E , 1 , ′ 0 ′ ) O V E R ( O R D E R B Y A . I N S T A N C E N U M B E R , A . S N A P I D ) ) " D B T I M E " F R O M ( S E L E C T B . S N A P I D , I N S T A N C E N U M B E R , S U M ( V A L U E ) / 1000000 / 60 V A L U E F R O M D B A H I S T S Y S T I M E M O D E L B W H E R E B . D B I D = ( S E L E C T D B I D F R O M V SESSION T2 WHERE T1.SESSION_ID = T2.SID) AND A.SQL_ADDRESS = C.ADDRESS(+) ORDER BY C.PIECE; 53.查询DB负载情况 SELECT * FROM ( SELECT A.INSTANCE_NUMBER, A.SNAP_ID, B.BEGIN_INTERVAL_TIME + 0 BEGIN_TIME, B.END_INTERVAL_TIME + 0 END_TIME, ROUND(VALUE - LAG( VALUE, 1 , '0') OVER(ORDER BY A.INSTANCE_NUMBER, A.SNAP_ID)) "DB TIME" FROM (SELECT B.SNAP_ID, INSTANCE_NUMBER, SUM(VALUE ) / 1000000 / 60 VALUE FROM DBA_HIST_SYS_TIME_MODEL B WHERE B.DBID = (SELECT DBID FROM V SESSIONT2WHERET1.SESSIONID=T2.SID)ANDA.SQLADDRESS=C.ADDRESS(+)ORDERBYC.PIECE;53.DBSELECTFROM(SELECTA.INSTANCENUMBER,A.SNAPID,B.BEGININTERVALTIME+0BEGINTIME,B.ENDINTERVALTIME+0ENDTIME,ROUND(VALUELAG(VALUE,1,0)OVER(ORDERBYA.INSTANCENUMBER,A.SNAPID))"DBTIME"FROM(SELECTB.SNAPID,INSTANCENUMBER,SUM(VALUE)/1000000/60VALUEFROMDBAHISTSYSTIMEMODELBWHEREB.DBID=(SELECTDBIDFROMVDATABASE)
AND UPPER (B.STAT_NAME) IN UPPER((‘DB TIME’ ))
GROUP BY B.SNAP_ID, INSTANCE_NUMBER) A,
DBA_HIST_SNAPSHOT B
WHERE A.SNAP_ID = B.SNAP_ID
AND B.DBID = (SELECT DBID FROM V$DATABASE)
AND B.INSTANCE_NUMBER = A.INSTANCE_NUMBER)
WHERE TO_CHAR(BEGIN_TIME, ‘YYYY-MM-DD’) = TO_CHAR(SYSDATE , ‘YYYY-MM-DD’)
ORDER BY BEGIN_TIME;

54.杀应用连接
ps -ef |grep LOCAL=NO |awk ‘{print $2}’|xargs kill -9

55.查询某个时间点的scn
select timestamp_to_scn(to_timestamp(‘2021-01-06 10:00:00’,‘yyyy-mm-dd hh24:mi:ss’)) from dual;
56.闪回到某个scn点:(闪回前请先进行备份)
alter table tb_flash1 enable row movement
flashback table tb_flash1 to 115398523;
57.查询数据库最近一次重启时间
alter session set nls_date_format=‘yyyy-mm-dd hh24:mi:ss’;
select startup_time from v i n s t a n c e ; 58. 查 看 日 志 每 小 时 文 件 切 换 频 率 c o l u m n h 0 f o r m a t 999 c o l u m n h 1 f o r m a t 999 c o l u m n h 2 f o r m a t 999 c o l u m n h 3 f o r m a t 999 c o l u m n h 4 f o r m a t 999 c o l u m n h 5 f o r m a t 999 c o l u m n h 6 f o r m a t 999 c o l u m n h 7 f o r m a t 999 c o l u m n h 8 f o r m a t 999 c o l u m n h 9 f o r m a t 999 c o l u m n h 10 f o r m a t 999 c o l u m n h 11 f o r m a t 999 c o l u m n h 12 f o r m a t 999 c o l u m n h 13 f o r m a t 999 c o l u m n h 14 f o r m a t 999 c o l u m n h 15 f o r m a t 999 c o l u m n h 16 f o r m a t 999 c o l u m n h 17 f o r m a t 999 c o l u m n h 18 f o r m a t 999 c o l u m n h 19 f o r m a t 999 c o l u m n h 20 f o r m a t 999 c o l u m n h 21 f o r m a t 999 c o l u m n h 22 f o r m a t 999 c o l u m n h 23 f o r m a t 999 c o l u m n a v g f o r m a t 999.99 c o l u m n d a y f o r m a t a 6 S E L E C T T R U N C ( f i r s t t i m e ) " D a t e " , T O C H A R ( f i r s t t i m e , ′ D y ′ ) " D a y " , C O U N T ( 1 ) " T o t a l " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 0 ′ , 1 , 0 ) ) h 0 , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 1 ′ , 1 , 0 ) ) " h 1 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 2 ′ , 1 , 0 ) ) " h 2 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 3 ′ , 1 , 0 ) ) " h 3 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 4 ′ , 1 , 0 ) ) " h 4 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 5 ′ , 1 , 0 ) ) " h 5 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 6 ′ , 1 , 0 ) ) " h 6 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 7 ′ , 1 , 0 ) ) " h 7 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 8 ′ , 1 , 0 ) ) " h 8 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 0 9 ′ , 1 , 0 ) ) " h 9 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 0 ′ , 1 , 0 ) ) " h 10 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 1 ′ , 1 , 0 ) ) " h 11 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 2 ′ , 1 , 0 ) ) " h 12 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 3 ′ , 1 , 0 ) ) " h 13 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 4 ′ , 1 , 0 ) ) " h 14 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 5 ′ , 1 , 0 ) ) " h 15 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 6 ′ , 1 , 0 ) ) " h 16 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 7 ′ , 1 , 0 ) ) " h 17 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 8 ′ , 1 , 0 ) ) " h 18 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 1 9 ′ , 1 , 0 ) ) " h 19 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 2 0 ′ , 1 , 0 ) ) " h 20 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 2 1 ′ , 1 , 0 ) ) " h 21 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 2 2 ′ , 1 , 0 ) ) " h 22 " , S U M ( D E C O D E ( T O C H A R ( f i r s t t i m e , ′ h h 2 4 ′ ) , ′ 2 3 ′ , 1 , 0 ) ) " h 23 " , t o c h a r ( R O U N D ( C O U N T ( 1 ) / 24 , 2 ) , ′ f m 99999999990.0 0 ′ ) " A v g " F R O M g v instance; 58.查看日志每小时文件切换频率 column h0 format 999 column h1 format 999 column h2 format 999 column h3 format 999 column h4 format 999 column h5 format 999 column h6 format 999 column h7 format 999 column h8 format 999 column h9 format 999 column h10 format 999 column h11 format 999 column h12 format 999 column h13 format 999 column h14 format 999 column h15 format 999 column h16 format 999 column h17 format 999 column h18 format 999 column h19 format 999 column h20 format 999 column h21 format 999 column h22 format 999 column h23 format 999 column avg format 999.99 column day format a6 SELECT TRUNC (first_time) "Date", TO_CHAR (first_time, 'Dy') "Day", COUNT (1) "Total", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '00', 1, 0)) h0, SUM (DECODE (TO_CHAR (first_time, 'hh24'), '01', 1, 0)) "h1", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '02', 1, 0)) "h2", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '03', 1, 0)) "h3", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '04', 1, 0)) "h4", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '05', 1, 0)) "h5", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '06', 1, 0)) "h6", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '07', 1, 0)) "h7", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '08', 1, 0)) "h8", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '09', 1, 0)) "h9", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '10', 1, 0)) "h10", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '11', 1, 0)) "h11", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '12', 1, 0)) "h12", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '13', 1, 0)) "h13", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '14', 1, 0)) "h14", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '15', 1, 0)) "h15", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '16', 1, 0)) "h16", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '17', 1, 0)) "h17", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '18', 1, 0)) "h18", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '19', 1, 0)) "h19", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '20', 1, 0)) "h20", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '21', 1, 0)) "h21", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '22', 1, 0)) "h22", SUM (DECODE (TO_CHAR (first_time, 'hh24'), '23', 1, 0)) "h23", to_char(ROUND (COUNT (1) / 24, 2),'fm99999999990.00') "Avg" FROM gv instance;58.columnh0format999columnh1format999columnh2format999columnh3format999columnh4format999columnh5format999columnh6format999columnh7format999columnh8format999columnh9format999columnh10format999columnh11format999columnh12format999columnh13format999columnh14format999columnh15format999columnh16format999columnh17format999columnh18format999columnh19format999columnh20format999columnh21format999columnh22format999columnh23format999columnavgformat999.99columndayformata6SELECTTRUNC(firsttime)"Date",TOCHAR(firsttime,Dy)"Day",COUNT(1)"Total",SUM(DECODE(TOCHAR(firsttime,hh24),00,1,0))h0,SUM(DECODE(TOCHAR(firsttime,hh24),01,1,0))"h1",SUM(DECODE(TOCHAR(firsttime,hh24),02,1,0))"h2",SUM(DECODE(TOCHAR(firsttime,hh24),03,1,0))"h3",SUM(DECODE(TOCHAR(firsttime,hh24),04,1,0))"h4",SUM(DECODE(TOCHAR(firsttime,hh24),05,1,0))"h5",SUM(DECODE(TOCHAR(firsttime,hh24),06,1,0))"h6",SUM(DECODE(TOCHAR(firsttime,hh24),07,1,0))"h7",SUM(DECODE(TOCHAR(firsttime,hh24),08,1,0))"h8",SUM(DECODE(TOCHAR(firsttime,hh24),09,1,0))"h9",SUM(DECODE(TOCHAR(firsttime,hh24),10,1,0))"h10",SUM(DECODE(TOCHAR(firsttime,hh24),11,1,0))"h11",SUM(DECODE(TOCHAR(firsttime,hh24),12,1,0))"h12",SUM(DECODE(TOCHAR(firsttime,hh24),13,1,0))"h13",SUM(DECODE(TOCHAR(firsttime,hh24),14,1,0))"h14",SUM(DECODE(TOCHAR(firsttime,hh24),15,1,0))"h15",SUM(DECODE(TOCHAR(firsttime,hh24),16,1,0))"h16",SUM(DECODE(TOCHAR(firsttime,hh24),17,1,0))"h17",SUM(DECODE(TOCHAR(firsttime,hh24),18,1,0))"h18",SUM(DECODE(TOCHAR(firsttime,hh24),19,1,0))"h19",SUM(DECODE(TOCHAR(firsttime,hh24),20,1,0))"h20",SUM(DECODE(TOCHAR(firsttime,hh24),21,1,0))"h21",SUM(DECODE(TOCHAR(firsttime,hh24),22,1,0))"h22",SUM(DECODE(TOCHAR(firsttime,hh24),23,1,0))"h23",tochar(ROUND(COUNT(1)/24,2),fm99999999990.00)"Avg"FROMgvlog_history
WHERE first_time >= trunc(SYSDATE) - 30
and thread# = inst_id
GROUP BY TRUNC (first_time), TO_CHAR (first_time, ‘Dy’)
ORDER BY 1 DESC;
59.更改会话时间显示格式
alter session set nls_date_format=‘yyyy-mm-dd hh24:mi:ss’;
60.查阻塞
col username for a15
col program for a30
col event for a30
select sid,serial#,username,blocking_session,last_call_et,prev_sql_id,final_blocking_session,event,machine,program,WAIT_TIME
from gvKaTeX parse error: Expected 'EOF', got '&' at position 291: …e table_name='&̲1'; 62.查看执行计划 s…session s where s.SID in(
select sid from v s e s s i o n w h e r e p a d d r i n ( s e l e c t a d d r f r o m v session where paddr in (select addr from v sessionwherepaddrin(selectaddrfromvprocess where spid in (
30342,
30076,
28599,
13151 )
));
66.杀会话
select ‘alter system kill session ‘’’||sid||’,’||serial#||’’’; 'from v s e s s i o n s w h e r e s . S T A T U S = ′ I N A C T I V E ′ a n d L O G O N T I M E < = ( s y s d a t e − 1 ) ; s e l e c t ′ k i l l − 9 ′ ∣ ∣ s p i d f r o m v session s where s.STATUS='INACTIVE' and LOGON_TIME<=(sysdate-1); select 'kill -9 '||spid from v sessionswheres.STATUS=INACTIVEandLOGONTIME<=(sysdate1);selectkill9spidfromvprocess where addr in (select paddr from v s e s s i o n w h e r e s i d i n ( s e l e c t s i d f r o m v session where sid in ( select sid from v sessionwheresidin(selectsidfromvsession s
where s.STATUS=‘INACTIVE’ and LOGON_TIME<=(sysdate-1/24)
));

select ‘alter system kill session ‘’’||sid||’,’||serial#||’’’; 'from v s e s s i o n w h e r e S I D i n ( s e l e c t B L O C K E R S I D f r o m v session where SID in (select BLOCKER_SID from v sessionwhereSIDin(selectBLOCKERSIDfromvwait_chains where IN_WAIT_SECS>100);

本文 SQL 命令由于编辑器原因可能出现格式错误不能执行,这里将其保存至文本文件中方便复制粘贴执行,如有需要的小伙伴们在本公众号【JiekeXu之路】扫描最下方二维码 后台回复 【SQL大全】 即可获取。
1, 清除 column 格式
clear columns
2, 创建永久性表空间
create tablespace myspace
datafile ‘文件路径’
size 文件大小
autoextend on next 自动增加大小
maxsize 文件最大值
语法说明:
1>,temporary|undo(创建撤销表空间)
2>,teblespace_name
3>,datafile|tempfile’file_name’
4>,size
5>,reuse 若存在,则删掉并重新创建
6>,autoextend off|on
7>, next number 自动扩展的大小
8>,maxsize unlimited|number 指定数据文件最大大小
9>,mininum extent number 盘区可以分配到的最小尺寸
10>,blocksize number 设置数据块大小
11>,online|offline
12>,logging|nologging
13>,force logging 强制表空间数据库对象任何操作都产生日志,否定 12
14,default storage storage 指定保存在表空间中的数据库对象默认存储参数
15>,compress|nocompress 是否压缩数据(消除列中的重复值)
16>,permanent|temporary 指定表空间中数据的保存形式
17>,extent management dictionary(数据字典形式管理)|local(本地化形式管理)
18>,autoallocate|uniform size number 右边为指定表中盘区大小
19>,segment space management auto |manual 指定表空间中段的管理方式
3,查看表空间属性
SELECT * FROM dba_tablespace wheretablespace_name = ‘表空间名’;
4, 修改表空间状态、名字
alter tablespace 表空间名 表空间状态;
alter tablespace 表空间名 1 rename to 表空间名 2;
5,查看闪回区 、快速恢复区空间使用率
select sum(percent_space_used)||’%’ “已使用空间比例”
from V R E C O V E R Y A R E A U S A G E ; 或 s e l e c t r o u n d ( 100 ∗ ( a . s p a c e u s e d / s p a c e l i m i t ) , 2 ) ∣ ∣ ′ f r o m v RECOVERY_AREA_USAGE; 或 select round(100*(a.space_used/space_limit),2)||'%' "已使用空间比例",a.* from v RECOVERYAREAUSAGE;selectround(100(a.spaceused/spacelimit),2)fromvrecovery_file_dest a;
6,利用数据字典查看空闲空间信息
SELECT * FROM dba_free_space
WHERE tablespace_name = ‘表空间名称’;
7, 利用数据字典查看表空间数据文件信息
SELECT * FROM dba_data_files wheretablespace_name = ‘表空间名称’;
8, 修改表空间对应的数据文件大小
alter database
datafile ‘表空间文件路径名称’
resize 大小
9、根据 sid 查 spid 或根据 spid 查 sid
select s.sid,s.serial#,p.spid,s.terminal,s.LOGON_TIME,s.status,s.PROGRAM,s.CLIENT_IDENTIFIER,s.machine,s.action,s.MODULE,s.PROCESS “客户端机器进程号”,s.osuser 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=XX or p.spid=YY;
10、查询堵塞别的会话超过30分钟且自身是不活动的会话
select username,sid,serial#,status,seconds_in_wait,LAST_CALL_ET from v s e s s i o n w h e r e s i d i n ( s e l e c t F I N A L B L O C K I N G S E S S I O N f r o m v session where sid in (select FINAL_BLOCKING_SESSION from v sessionwheresidin(selectFINALBLOCKINGSESSIONfromvsession
where state=‘WAITING’ and BLOCKING_SESSION_STATUS=‘VALID’ and FINAL_BLOCKING_SESSION_STATUS=‘VALID’) and status=‘INACTIVE’
and sql_id is null and seconds_in_wait>1800;
11、查询正在执行的 SCHEDULER_JOB
select owner,job_name,sid,b.SERIAL#,b.username,spid from ALL_SCHEDULER_RUNNING_JOBS,v s e s s i o n b , v session b,v sessionb,vprocess
where session_id=sid and paddr=addr;
12、查询正在执行的 dbms_job
select job,b.sid,b.SERIAL#,b.username,spid from DBA_JOBS_RUNNING a ,v s e s s i o n b , v session b,v sessionb,vprocess
where a.sid=b.sid and paddr=addr;
13、查询当前正在消耗临时空间的 SQL 语句
Select distinct se.username,se.sid,
su.blocks * to_number(rtrim(p.value))/1024/1024 as space_G,
su.tablespace,sql_text
from V T E M P S E G U S A G E s u , v TEMPSEG_USAGE su, v TEMPSEGUSAGEsu,vparameter p, v s e s s i o n s e , v session se, v sessionse,vsql s
where p.name = ‘db_block_size’ and su.session_addr=se.saddr
and su.sqlhash=s.hash_value and su.sqladdr=s.address and se.STATUS=‘ACTIVE’;
14、查看临时表空间使用率
SELECT temp_used.tablespace_name,round(total),used,
round(total - used) as “Free”,
round(nvl(total-used, 0) * 100/total,1) “Free percent”
FROM (SELECT tablespace_name, SUM(bytes_used)/1024/1024 used
FROM GV T E M P S P A C E H E A D E R G R O U P B Y t a b l e s p a c e n a m e ) t e m p u s e d , ( S E L E C T t a b l e s p a c e n a m e , S U M ( d e c o d e ( a u t o e x t e n s i b l e , ′ Y E S ′ , M A X B Y T E S , b y t e s ) ) / 1024 / 1024 t o t a l F R O M d b a t e m p f i l e s G R O U P B Y t a b l e s p a c e n a m e ) t e m p t o t a l W H E R E t e m p u s e d . t a b l e s p a c e n a m e = t e m p t o t a l . t a b l e s p a c e n a m e 或 S E L E C T a . t a b l e s p a c e n a m e , r o u n d ( a . B Y T E S / 1024 / 1024 ) t o t a l M , r o u n d ( a . b y t e s / 1024 / 1024 − n v l ( b . b y t e s / 1024 / 1024 , 0 ) ) f r e e M , r o u n d ( b . b y t e s / 1024 / 1024 ) u s e d , r o u n d ( b . u s i n g / 1024 / 1024 ) u s i n g F R O M ( S E L E C T t a b l e s p a c e n a m e , S U M ( d e c o d e ( a u t o e x t e n s i b l e , ′ Y E S ′ , M A X B Y T E S , b y t e s ) ) b y t e s F R O M d b a t e m p f i l e s G R O U P B Y t a b l e s p a c e n a m e ) a , ( S E L E C T t a b l e s p a c e n a m e , S U M ( b y t e s c a c h e d ) b y t e s , s u m ( b y t e s u s e d ) u s i n g F R O M v TEMP_SPACE_HEADER GROUP BY tablespace_name) temp_used, (SELECT tablespace_name, SUM(decode(autoextensible,'YES',MAXBYTES,bytes))/1024/1024 total FROM dba_temp_files GROUP BY tablespace_name) temp_total WHERE temp_used.tablespace_name = temp_total.tablespace_name 或 SELECT a.tablespace_name, round(a.BYTES/1024/1024) total_M, round(a.bytes/1024/1024 - nvl(b.bytes/1024/1024, 0)) free_M, round(b.bytes/1024/1024) used,round(b.using/1024/1024) using FROM (SELECT tablespace_name, SUM (decode(autoextensible,'YES',MAXBYTES,bytes)) bytes FROM dba_temp_files GROUP BY tablespace_name) a, (SELECT tablespace_name, SUM (bytes_cached) bytes,sum(bytes_used) using FROM v TEMPSPACEHEADERGROUPBYtablespacename)tempused,(SELECTtablespacename,SUM(decode(autoextensible,YES,MAXBYTES,bytes))/1024/1024totalFROMdbatempfilesGROUPBYtablespacename)temptotalWHEREtempused.tablespacename=temptotal.tablespacenameSELECTa.tablespacename,round(a.BYTES/1024/1024)totalM,round(a.bytes/1024/1024nvl(b.bytes/1024/1024,0))freeM,round(b.bytes/1024/1024)used,round(b.using/1024/1024)usingFROM(SELECTtablespacename,SUM(decode(autoextensible,YES,MAXBYTES,bytes))bytesFROMdbatempfilesGROUPBYtablespacename)a,(SELECTtablespacename,SUM(bytescached)bytes,sum(bytesused)usingFROMvtemp_extent_pool GROUP BY tablespace_name) b
WHERE a.tablespace_name = b.tablespace_name(+);
15、查看当前会话的 SID
select * from V$MYSTAT where rownum<2;
16、统计每个用户使用表空间率
SELECT c.owner “用户”,
a.tablespace_name “表空间名”,
total/1024/1024 “表空间大小M”,
free/1024/1024 “表空间剩余大小M”,
( total - free )/1024/1024 “表空间使用大小M”,
Round(( total - free ) / total, 4) * 100 “表空间总计使用率 %”,
c.schemas_use/1024/1024 “用户使用表空间大小M”,
round((schemas_use)/total,4)*100 “用户使用表空间率 %”
FROM (SELECT tablespace_name,
Sum(bytes) free
FROM DBA_FREE_SPACE
GROUP BY tablespace_name) a,
(SELECT tablespace_name,
Sum(bytes) total
FROM DBA_DATA_FILES
GROUP BY tablespace_name) b,
(Select owner ,Tablespace_Name,
Sum(bytes) schemas_use
From Dba_Segments
Group By owner,Tablespace_Name) c
WHERE a.tablespace_name = b.tablespace_name
and a.tablespace_name =c.Tablespace_Name
order by “用户”,“表空间名”;

关于 SQL 命令还有很多,由于篇幅就先写这么多,有机会在分享。上述 SQL 命令由于编辑器原因可能出现格式错误不能执行,
这里将其保存至 文本文件中方便复制粘贴执行,如有需要的小伙伴们在本公众号 JiekeXu之路【ID 为 JiekeXu_IT】后台回复 【SQL大全】 即可获取。
也可添加微信 ID:JiekeXu_DBA 一起学习数据库。

手工创建快照的语句,AWR设置每隔30分钟收集一次报告,保留40天的报告
exec dbms_workload_repository.create_snapshot;
exec DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(retention=>402460, interval=>30);
select * from dba_hist_wr_control;
AWR基线查看和创建
select * from dba_hist_baseline;
exec DBMS_WORKLOAD_REPOSITORY.CREATE_BASELINE(start_snap_id=>7550,end_snap_id=>7660,baseline_name=>‘am_baseline’);
导出AWR报告的SQL语句
select * from dba_hist_snapshot
select * from table(dbms_workload_repository.awr_report_html(DBID, INSTANCE_NUMBER, startsnapid,endsnapid))
select * from TABLE(DBMS_WORKLOAD_REPOSITORY.awr_diff_report_html(DBID, INSTANCE_NUMBER, startsnapid,endsnapid, DBID, INSTANCE_NUMBER, startsnapid,endsnapid));
导出最新ADDM的报告(需要sys用户)
select dbms_advisor.get_task_report(task_name) from dba_advisor_tasks
where task_id =(
select max(t.task_id) from dba_advisor_tasks t, dba_advisor_log l where
t.task_id=l.task_id and t.advisor_name=‘ADDM’ and l.status=‘COMPLETED’ );
select task_id,task_name,description from dba_advisor_tasks order by 1 desc
select dbms_advisor.get_task_report(task_name) from dba_advisor_tasks where task_id =XX
查询Rman备份集详细信息(未过期的,过期并已删除的查不到)
SELECT B.RECID BackupSet_ID,
A.SET_STAMP,
DECODE (B.INCREMENTAL_LEVEL,
‘’, DECODE (BACKUP_TYPE, ‘L’, ‘Archivelog’, ‘Full’),
1, ‘Incr-1级’,
0, ‘Incr-0级’,
B.INCREMENTAL_LEVEL)
“Type LV”,
B.CONTROLFILE_INCLUDED “包含CTL”,
DECODE (A.STATUS,
‘A’, ‘AVAILABLE’,
‘D’, ‘DELETED’,
‘X’, ‘EXPIRED’,
‘ERROR’)
“STATUS”,
A.DEVICE_TYPE “Device Type”,
A.START_TIME “Start Time”,
A.COMPLETION_TIME “Completion Time”,
A.ELAPSED_SECONDS “Elapsed Seconds”,
A.BYTES/1024/1024/1024 “Size(G)”,
A.COMPRESSED,
A.TAG “Tag”,
A.HANDLE “Path”
FROM GV B A C K U P P I E C E A , G V BACKUP_PIECE A, GV BACKUPPIECEA,GVBACKUP_SET B
WHERE A.SET_STAMP = B.SET_STAMP AND A.DELETED = ‘NO’
ORDER BY A.COMPLETION_TIME DESC;
查询Rman备份进度
SELECT SID, SERIAL#, opname,ROUND(SOFAR/TOTALWORK100)||’%’ “%_COMPLETE”,
TRUNC(elapsed_seconds/60) || ‘:’ || MOD(elapsed_seconds,60) elapsed,
TRUNC(time_remaining/60) || ‘:’ || MOD(time_remaining,60) remaining,
CONTEXT,target,SOFAR, TOTALWORK
FROM V S E S S I O N L O N G O P S W H E R E O P N A M E L I K E ′ R M A N A N D O P N A M E N O T L I K E ′ A N D T O T A L W O R K ! = 0 A N D S O F A R < > T O T A L W O R K ; 查 询 死 事 务 需 要 多 长 的 回 滚 时 间 X SESSION_LONGOPS WHERE OPNAME LIKE 'RMAN%' AND OPNAME NOT LIKE '%aggregate%' AND TOTALWORK != 0 AND SOFAR <> TOTALWORK; 查询死事务需要多长的回滚时间 X SESSIONLONGOPSWHEREOPNAMELIKERMANANDOPNAMENOTLIKEANDTOTALWORK!=0ANDSOFAR<>TOTALWORK;XKTUXE:[K]ernel [T]ransaction [U]ndo Transa[x]tion [E]ntry (table)
X K T U X E 表 的 一 个 重 要 功 能 是 , 可 以 获 得 无 法 通 过 v KTUXE表的一个重要功能是,可以获得无法通过v KTUXEvtransaction来观察的死事务信息,当一个数据库发生异常中断,或者进行延迟事务恢复时,数据库启动后,无法通过V T R A N S A C T I O N 来 观 察 事 务 信 息 , 但 是 X TRANSACTION来观察事务信息,但是X TRANSACTIONXKTUXE可以帮助我们获得这些信息。该表中的KTUXECFL代表了事务的Flag标记,通过这个标记可以找到那些Dead事务:
SQL> select distinct KTUXECFL,count(
) from x k t u x e g r o u p b y K T U X E C F L ; K T U X E C F L C O U N T ( ∗ ) − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − D E A D 1 N O N E 2393 K T U X E S I Z 用 来 记 录 事 务 使 用 的 回 滚 段 块 数 , 可 以 通 过 观 察 这 个 字 段 来 评 估 恢 复 进 度 , 例 如 如 下 事 务 回 滚 经 过 测 算 需 要 大 约 3 小 时 : : S Q L > s e l e c t A D D R , K T U X E U S N , K T U X E S L T , K T U X E S Q N , K T U X E S I Z f r o m x ktuxe group by KTUXECFL; KTUXECFL COUNT(*) ------------------------ ---------- DEAD 1 NONE 2393 KTUXESIZ用来记录事务使用的回滚段块数,可以通过观察这个字段来评估恢复进度,例如如下事务回滚经过测算需要大约3小时:: SQL> select ADDR,KTUXEUSN,KTUXESLT,KTUXESQN,KTUXESIZ from x ktuxegroupbyKTUXECFL;KTUXECFLCOUNT()DEAD1NONE2393KTUXESIZ使,3SQL>selectADDR,KTUXEUSN,KTUXESLT,KTUXESQN,KTUXESIZfromxktuxe where KTUXECFL =‘DEAD’;
ADDR KTUXEUSN KTUXESLT KTUXESQN KTUXESIZ
---------------- ---------- ---------- ---------- ----------
FFFFFFFF7D07B91C 10 39 2567412 1086075
SQL> select ADDR,KTUXEUSN,KTUXESLT,KTUXESQN,KTUXESIZ from x k t u x e w h e r e K T U X E C F L = ′ D E A D ′ ; A D D R K T U X E U S N K T U X E S L T K T U X E S Q N K T U X E S I Z − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − F F F F F F F F 7 D 07 B 91 C 103925674121086067 S Q L > d e c l a r e l s t a r t n u m b e r ; l e n d n u m b e r ; b e g i n s e l e c t k t u x e s i z i n t o l s t a r t f r o m x ktuxe where KTUXECFL ='DEAD'; ADDR KTUXEUSN KTUXESLT KTUXESQN KTUXESIZ ---------------- ---------- ---------- ---------- ---------- FFFFFFFF7D07B91C 10 39 2567412 1086067 SQL> declare l_start number; l_end number; begin select ktuxesiz into l_start from x ktuxewhereKTUXECFL=DEAD;ADDRKTUXEUSNKTUXESLTKTUXESQNKTUXESIZFFFFFFFF7D07B91C103925674121086067SQL>declarelstartnumber;lendnumber;beginselectktuxesizintolstartfromxktuxe where KTUXEUSN=10 and KTUXESLT=39;
dbms_lock.sleep(60);
select ktuxesiz into l_end from x$ktuxe where KTUXEUSN=10 and KTUXESLT=39;
dbms_output.put_line(‘time_H:’|| round(l_end/(l_start -l_end)/60,2));
end;
/
time_H:3

把XXX用户下面的某些YYY表赋权给user,XXX\YYY要大写
set serveroutput on
–XXX要大写
declare tablename varchar2(200);
begin
for x IN (SELECT * FROM dba_tables where owner=‘XXX’ and table_name like ‘%YYY%’) loop
tablename:=x.table_name;
dbms_output.put_line(‘GRANT SELECT ON XXX.’||tablename||’ to user’);
EXECUTE IMMEDIATE ‘GRANT SELECT ON XXX.’||tablename||’ TO user’;
end loop;
end;

一线运维 DBA 五年经验常用 SQL 大全(二)
1、查看数据文件信息:
col file_name for a55
select tablespace_name,file_name,bytes/1024/1024/1024 gb,AUTOEXTENSIBLE from dba_data_files where tablespace_name=‘AM_DATA’;
alter tablespace UNDOTBS1 add datafile ‘+DATA’ size 30G;

2、查看ASM磁盘组信息:
select group_number,name,total_mb/1024 total_gb,free_mb/1024 free_gb,TYPE from v$asm_diskgroup;

—调整ASM磁盘均衡级别
ALTER DISKGROUP DATA REBALANCE POWER 10;

—查看ASM磁盘均衡时间:
select * from v$asm_operation;

3、查看ASM磁盘组磁盘的信息
set lin 1000 pagesize 999
col PATH for a33
col NAME for a15
col FAILGROUP for a15
select GROUP_NUMBER,DISK_NUMBER,TOTAL_MB/1024,FREE_MB/1024,NAME,FAILGROUP,PATH,FAILGROUP_TYPE from v$asm_disk where GROUP_NUMBER=‘1’;

4、查看表空间大小:
SELECT a.tablespace_name,round(total/1024/1024/1024) “Total g”,
round(free/1024/1024/1024) “Free g”,ROUND((total-free)/total,4)*100 “USED%”
FROM (SELECT tablespace_name,SUM(bytes) free 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
ORDER BY 4;

5、查某个表空间内的前五个大表
col TABLE_NAME for a30
set pagesize 200
set linesize 200
col TABLE_NAME for a30
set linesize 200
select * from (select TABLESPACE_NAME,OWNER,SEGMENT_NAME “TABLE_NAME”,to_number(decode(substr(BYTES/1024/1024,1,1),’.’,‘0’||BYTES/1024/1024,BYTES/1024/1024)) total_MB
from dba_segments where TABLESPACE_NAME =’&tablespacename’ and SEGMENT_TYPE=‘TABLE’ order by total_MB desc ) where rownum<=5;

SELECT * FROM (SELECT OWNER,SEGMENT_NAME, SUM(BYTES) / 1024 / 1024 MB FROM DBA_SEGMENTS WHERE TABLESPACE_NAME = ‘SYSTEM’ GROUP BY SEGMENT_NAME,OWNER ORDER BY 3 DESC) WHERE ROWNUM <=5;

OWNER SEGMENT_NAME MB


SYS XX_RECNAME_RB_IX 11136
SYS XXXXX_ORIGINNOTE_IX 9152
SYS XXXXX_ABSTRACT_IX 6388
SYS XXX_PAYDATE_NU_NC 5490

SELECT OWNER,SEGMENT_NAME ,segment_type FROM DBA_SEGMENTS WHERE segment_name in (‘PAYMENTS_RECNAME_RB_IX’,‘XXXXX_ORIGINNOTE_IX’,‘XXXXX_ABSTRACT_IX’,‘XXX_PAYDATE_NU_NC’);

OWNER SEGMENT_NAME SEGMENT_TYPE


SYS XXX_PAYDATE_NU_NC INDEX
SYS XXXXX_ORIGINNOTE_IX INDEX
SYS XXXXX_ABSTRACT_IX INDEX
SYS XXXMENTS_RECNAME_RB_IX INDEX

6、查看shared_pool的大小
select sum(bytes)/1024/1024/1024 from v s g a s t a t w h e r e p o o l = ′ s h a r e d p o o l ′ ; 查 看 空 闲 的 : s e l e c t ∗ f r o m v sgastat where pool='shared pool'; 查看空闲的: select * from v sgastatwherepool=sharedpool;selectfromvsgastat where name = ‘free memory’ and pool = ‘shared pool’;
统计活动的undo
select sum(bytes /(102410241024)) from dba_undo_extents where status=‘ACTIVE’;

7、查看占用内存100k的sql语句:
select sql_text ,sharable_mem from v$sql where sharable_mem > ‘100000’ order by sharable_mem

8、查看字符集
select userenv(‘language’) from dual;
select * from nls_database_parameters;

9、Oracle查询temp表空间的名字和位置
select tablespace_name,file_name from dba_temp_files;
col FILE_NAME for a55
select TABLESPACE_NAME,FILE_NAME,BYTES/1024/1024/1024 total_gb,USER_BYTES/1021/1024/1024 gb from dba_temp_files;

create temporary tablespace temp1 tempfile ‘/rhzxdata/tempdata/pbc/temp01.dbf’ size 20G autoextend on maxsize 30G

Oracle查询temp表空间的使用率
select tablespace_name,round(free_space/1024/1024/1024,2) “free(GB)”,round(tablespace_size/1024/1024/1024,2) “total(GB)”,round(nvl(free_space,0)*100/tablespace_size,3) “Free percent”
from dba_temp_free_space;

注意:Primary 端涉及到的临时表空间创建维护、临时文件创建的操作是不会传导到 standby 端的。

10、查看数据库版本
set line 150
col ACTION_TIME for a30
col ACTION for a8
col NAMESPACE for a8
col VERSION for a10
col BUNDLE_SERIES for a5
col COMMENTS for a20
select * from dba_registry_history;

=================================================================================================
本文 SQL 命令由于微信编辑器原因可能出现格式错误不能执行,这里将其保存至文本文件中方便复制粘贴执行,
如有需要的小伙伴们在本公众号【JiekeXu DBA之路】扫描最下方二维码后台回复 【SQL大全二】即可获取。

11、查看补丁版本:
JIEKED2:/app/product/11.2.0/db/OPatch$opatch lsinventory

12、查看锁表
SELECT l.session_id sid, s.serial#, l.locked_mode,l.oracle_username,
l.os_user_name,s.machine, s.terminal, o.object_name, s.logon_time
FROM v l o c k e d o b j e c t l , a l l o b j e c t s o , v locked_object l, all_objects o, v lockedobjectl,allobjectso,vsession s
WHERE l.object_id = o.object_id
AND l.session_id = s.sid
ORDER BY sid, s.serial# ;

查出锁定表的 session 的 sid, serial#,os_user_name, machine name, terminal 和执行的语句:

SELECT l.session_id sid, s.serial#, l.locked_mode, l.oracle_username, s.user#,
l.os_user_name,s.machine, o.object_name,s.terminal,a.sql_text, a.action
FROM v s q l a r e a a , v sqlarea a,v sqlareaa,vsession s, v$locked_object l,all_objects o
WHERE l.session_id = s.sid
AND s.prev_sql_addr = a.address
ORDER BY sid, s.serial#;

13、查看视图对应的表:
select * from dba_dependencies where NAME=‘视图名’ and TYPE=‘VIEW’;

14、杀会话命令
alter system kill session ‘sid,serial#’;

15、查看表大小
select TABLESPACE_NAME,OWNER,SEGMENT_NAME,sum(BYTES)/1024/1024 total_mb
from dba_segments where TABLESPACE_NAME=‘NEWCAR02’ group by TABLESPACE_NAME,OWNER,SEGMENT_NAME;

16、查看 GI 兼容版本
select name,compatibility,database_compatibility from v$asm_diskgroup;

17、查看aix操作系统的资源情况
prtconf|more
lparstat -i
ortconf
AIX 磁盘扫描命令
root 执行
cfgmgr -v

–查看那个进程占用磁盘空间
fuser -dV /app

AIX 查看错误日志并输出到 messages
JIekeXuY1:/#errpt -dH
IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION
DE3B8540 1012214419 P H hdisk18 PATH HAS FAILED
4B436A3D 1012214119 T H fscsi0 LINK ERROR
4B436A3D 1012214119 T H fscsi0 LINK ERROR
4B436A3D 1012214119 T H fscsi0 LINK ERROR

/bin/errpt -a > messages.out
你要查那些hdisk的?lunid
AIX查看LUNID信息
lscfg -vpl hdisk187 输出结果里的serial number就是存储要的lunid

lscfg -vpl hdisk11

hdisk11 U9080.MME.680A6E8-V7-C2-T1-W500507680C25ADBA-LB000000000000 MPIO FC 2145

    Manufacturer................IBM     
    Machine Type and Model......2145            
    ROS Level and ID............0000
    Device Specific.(Z0)........0000063268181002
    Device Specific.(Z1)........0203202
    Serial Number...............600507680C808570080000000000042B

PLATFORM SPECIFIC

Name: disk
Node: disk
Device Type: block

— 检查磁盘大小(单位M)
bootinfo -s hdisk0

— 查看磁盘的详细信息
lsattr -El hdisk0

HP:machinfo
(diskinfo /dev/rdisk/disk* 查看磁盘大小)

WIN:msinfo32

SUSE:cat /proc/cpuinfo (model name )

—查看资源使用情况:
HP:glance/top
AIX:nmon/topas

–AIX查看版本号
oslevel
JIEKEXuR2:/app/product/11.2.0/grid/network/log$oslevel
6.1.0.0

—查看内存大小:
HP: /usr/contrib/bin/machinfo | grep -i Memory
AIX: /usr/sbin/lsattr -E -l sys0 -a realmem

—查看swap分区:
HP:/usr/sbin/swapinfo -a
AIX:/usr/sbin/lsps -s

18、用户相关操作
select USERNAME,DEFAULT_TABLESPACE,TEMPORARY_TABLESPACE from dba_users;
create user agriproduct identified by product default tablespace users;
grant conncet,resource,create view to product;
–解锁用户
set linesize 500
col USERNAME for a15
col ACCOUNT_STATUS for a15
select USERNAME,ACCOUNT_STATUS,LOCK_DATE,EXPIRY_DATE,DEFAULT_TABLESPACE from dba_users where USERNAME =‘SQLMON’;
alter user SQLMON identified by “SQLMON” account unlock;
alter user SQLMON account unlock;
alter user SQLMON identified by “SQLMON”;
conn SQLMON/SQLMON
#查看用户具有的权限
1、查询用户有哪些角色:
select * from dba_role_privs where grantee=’&username’;
2、查询角色包含哪些权限:
select * from role_sys_privs where role=’&role’;
3、查询用户系统权限:
select * from dba_sys_privs where grantee=’&username’;
select * from dba_tab_privs where grantee=’&username’;

–创建 dblink 权限
grant create database link to user ;
grant create public database link to user ;

删除用户:drop user XXX cascade;
解锁用户
alter user muar_rb account unlock identified by &PASSWORD;

查看表空间下的用户
select distinct s.owner from dba_segments s where s.tablespace_name =’&TBSNAME’

19、查看数据量:
select sum(bytes)/1024/1024/1024 Gb from dba_segments;

20、查看 REDOLOG 大小
select group#,members,bytes/1024/1024,status from v$log;

21、清理垃圾文件
cd &DIR
find ./ -ctime +3 |xargs rm
查看大于1024M的文件
find / -type f -size +1024M -print0 | xargs -0 du -h | sort -nr

22、AIX 操作系统下 ASM 磁盘相关操作

— 检查磁盘大小(单位M)
bootinfo -s hdisk0

— 查看磁盘的详细信息
lsattr -El hdisk0

JIEKEXu:/dev#lsattr -El /dev/hdisk322
lsattr: 0514-519 The following device was not found in the customized
device configuration database:
/dev/hdisk322
JIEKEXu:/dev#su - grid
JIEKEXu:/home/grid$kfed read /dev/rhdisk322
kfbh.endian: 0 ; 0x000: 0x00
kfbh.hard: 130 ; 0x001: 0x82
kfbh.type: 1 ; 0x002: KFBTYP_DISKHEAD
kfbh.datfmt: 1 ; 0x003: 0x01
kfbh.block.blk: 0 ; 0x004: blk=0
kfbh.block.obj: 2147483953 ; 0x008: disk=305
kfbh.check: 3956950460 ; 0x00c: 0xebda45bc
kfbh.fcn.base: 2632 ; 0x010: 0x00000a48
kfbh.fcn.wrap: 0 ; 0x014: 0x00000000

— 检查权限 hdisk是块设备,而rhdisk是字符设备。
ls -l /dev/hdisk*
【排序查看ls -ltr /dev |grep rhdisk】

运行命令lsattr -E -a rw_timeout -F value -l Name,查看rw_timeout的值。
JIEKEY1:/app/grid/diag/asm/+asm/+ASM1/trace$lsattr -E -a rw_timeout -F value -l hdisk16
60
— 检查PVID
lspv | grep hdiskn

— 检查保留策略
lsattr -E -l hdisk5 | grep reserve_policy

— 查看磁盘是否为共享磁盘
lsattr -El hdisk0
比对两个主机对应的磁盘号是否一致:unique_id

— 查看磁盘是否可用
lspv
看PVID是否为none,若为none则数据库可用,再查看数据库当前有没有使用,若没有则可用来扩容ASM磁盘组

23、AIX 下按用户查看占用多少内存
svmon -U grid -w |more
svmon -U oracle -w | more

24、AIX 下查看用户下有多少进程
svmon -PO unit=GB |grep aioserver |wc
svmon -PO unit=GB |grep oracle |wc

lsvg |lsvg -i -p
lsdev -c disk

25、查看服务器底层用的存储类型:
lscfg -vpl hdisk40

26、生成AWR报告
-----某个节点的 AWR
@?/rdbms/admin/awrrpti.sql
-----AWR报告
@?/rdbms/admin/awrrpt.sql
– AWR 两个时间段的比较报告
@?/rdbms/admin/awrddrpt.sql
-----ASH报告
@ O R A C L E H O M E / r d b m s / a d m i n / a s h r p t . s q l − − − − − 细 粒 度 的 A S H ( E n t e r v a l u e f o r s l o t w i d t h : 1 ) s l o t 槽 为 1 的 A S H @ ORACLE_HOME/rdbms/admin/ashrpt.sql -----细粒度的 ASH (Enter value for slot_width:1)slot 槽为 1 的 ASH @ ORACLEHOME/rdbms/admin/ashrpt.sqlASHEntervalueforslotwidth:1slot1ASH@ORACLE_HOME/rdbms/admin/ashrpti.sql

关于physical reads ,db block gets 和 consistent gets 这三个参数之间有一个换算公式:
数据缓冲区的使用命中率=1 - ( physical reads / (db block gets + consistent gets) )。
用以下语句可以查看数据缓冲区的命中率:
SELECT name, value FROM v$sysstat WHERE name IN (‘db block gets’, ‘consistent gets’,‘physical reads’);

查询出来的结果 Buffer Cache 的命中率应该在 90% 以上,否则需要增加数据缓冲区的大小。

27、查看ASM磁盘挂载时间:
set lines 500 pages 2000
col g_name format a10
col g_n format 99
col d_n format 999
col m_status format a7
col mo_status format a7
col h_status format a11
col name format a20
col path format a20
col failgroup format a15
select g.group_number g_n,
g.disk_number d_n,
g.name name,
g.failgroup,
g.mount_status m_status,
g.header_status h_status,
g.mode_status mo_status,
g.path ,
to_char(g.mount_date, ‘YYYY/MM/DD HH24:MI:SS’) m_date
from v$asm_disk g
order by g_n, d_n

28、查看某个用户所拥有的角色
select * from dba_role_privs where grantee='JXJL_NEW_QRY ';

29、查看某个角色所拥有的权限
select * from dba_sys_privs where grantee=‘SKDATA’;

30、修改LINUX操作系统/dev/shm文件系统大小
开机自启动:
tmpfs /dev/shm tmpfs defaults,size=20G 0 0
立即生效:
mount -t tmpfs shmfs -o size=20g /dev/shm

31、trace 追踪监听文件
$ ps aux |sort -rnk3 |more

侦听器进程的Pstack / Truss / Strace / Tusc 注意110888.1如何跟踪Unix系统调用
Pstack <PID_of_listener>

Sun:truss -aefdDo /tmp/truss-lsnr.log -p <PID_of_listener>
Linux:strace -frT -o /tmp/strace-lsnr.log -p <PID_of_listener>
HP:tusc -aef -o /tmp/tusc-lsnr.log -T“%H:%M:%S” -p <PID_of_listener>

32、删除当前目录下十天前 .dmp 文件
find ./ -name '
.dmp’ -mtime +10 -exec rm -f {}

33、dds 同步软件
su - ddsdt 用户,vshmt -c 可以看到同步情况
/ddssoftware/ddt/ddsdt/bin/dds_pput -x
DDS同步软件 类似于OGG的同步软件
10.10.19X.XXX localhost
10.10.19X.XX JiekeADG
JiekeADG:/app/oracle/diag/rdbms/picccash/picccash/trace$
hostname:/#su - ddsdt
JiekeADG:/ddssoftware/ddt/ddsdt/dtKaTeX parse error: Expected 'EOF', got '#' at position 1963: … 0-N 1-N SRC#̲0 : SO…

===================================================================================================
关于 SQL 命令还有很多,由于篇幅就先写这么多,有机会在分享。上述 SQL 命令由于编辑器原因可能出现格式
错误不能执行,这里将其保存至文本文件中方便复制粘贴执行,如有需要的小伙伴们在本公众号 JiekeXu DBA之路
【ID 为 JiekeXu_IT】后台回复 【SQL大全二】 即可获取。也可添加微信 ID:JiekeXu_DBA 一起学习数据库。

34、根据归档号从带库恢复归档日志
rman target /
run
{
Allocate channel t1 type ‘sbt_tape’ parms ‘ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt)’;
restore archivelog sequence between 63145 and 63149 thread 1;
restore archivelog sequence between 62697 and 62700 thread 2;
Release channel t1;
}

35、JDBC 连接串
jdbc:Oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(HOST=10.1XX.XXX.XXX)(PROTOCOL=TCP)(PORT=1521))(ADDRESS=(HOST=10.1XX.XXX.XXX)(PROTOCOL=TCP)(PORT=1521)))(LOAD_BALANCE=yes)(FAILOVER=yes)(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Jieker)))

36、数据泵导入
impdp user/password dumpfile=temp.dmp directory=dump remap_tablespace=[old_table_space]:[new_table_space]
old是指server1机器上的tablespace_name,new是指server2上的

37、切换日志打检查点,关闭实例时使用
alter system switch logfile;
alter system switch logfile;
alter system checkpoint;

38、修改内存
alter system set memory_max_target=0 scope=spfile;
alter system set memory_target =0 scope=spfile;
alter system set sga_max_size=13G scope=spfile;
alter system set sga_target=13G scope=spfile;
alter system set pga_aggregate_target=6G scope=spfile;
###############################################################
安装数据库报错:
/bin/dd if=/var/tmp/.oracle/npohasd of=/dev/null bs=1024 count=1
$GRID_HOME/crs/install/roothas.pl -deconfig -force -verbose //GI回退 root.sh 脚本
###############################

39、停 oem 杀会话
停 oem 服务再停数据库
/app/oms/bin/emctl start/stop oms
Ps -ef | grep -i local=no | grep -v grep | awk ‘{print $2}’| xargs kill -9

40、ASM 掉盘重新挂盘重启 crsd 进程
su - grid
crsctl query crs softwareversion --查看集群版本
asmcmd
lsdg
mount ocr
exit
crsctl start res ora.crsd -init

41、Linux 6 下查看数据库有哪些 IP 连接进来
netstat -anop | grep ESTABLISHED | awk ‘$4 ~/:1521/’
–解压 10g 的 cpio 类型安装软件
cpio -idmvc <*.cpio //cpio解压

42、清理垃圾文件
cd &DIR
find ./ -ctime +3 |xargs rm
查看大于20M的文件
find / -type f -size +20M -print0 | xargs -0 du -h | sort -nr

43、查看备库进程:
set pages 9999
set lines 200
select process,client_process,sequence#,thread#,status from v$managed_standby;

—mrp0当前正在应用的日志序列
select process,status,sequence# from v$managed_standby;

—查询dg应用情况
set linesize 150;
set pagesize 20;
column name format a13;
column value format a20;
column unit format a30;
column TIME_COMPUTED format a30;
select name,value,unit,time_computed from v$dataguard_stats where name in (‘transport lag’,‘apply lag’);

44、查询数据库负载
set pages 9999
set lines 200
alter session set nls_date_format=‘yyyy-mm-dd hh24:mi:ss’;
SELECT *
FROM ( SELECT A.INSTANCE_NUMBER,
A.SNAP_ID,
B.BEGIN_INTERVAL_TIME + 0 BEGIN_TIME,
B.END_INTERVAL_TIME + 0 END_TIME,
ROUND(VALUE - LAG( VALUE, 1 , ‘0’)
OVER(ORDER BY A.INSTANCE_NUMBER, A.SNAP_ID)) “DB TIME”
FROM (SELECT B.SNAP_ID,
INSTANCE_NUMBER,
SUM(VALUE ) / 1000000 / 60 VALUE
FROM DBA_HIST_SYS_TIME_MODEL B
WHERE B.DBID = (SELECT DBID FROM V D A T A B A S E ) A N D U P P E R ( B . S T A T N A M E ) I N U P P E R ( ( ′ D B T I M E ′ ) ) G R O U P B Y B . S N A P I D , I N S T A N C E N U M B E R ) A , D B A H I S T S N A P S H O T B W H E R E A . S N A P I D = B . S N A P I D A N D B . D B I D = ( S E L E C T D B I D F R O M V DATABASE) AND UPPER (B.STAT_NAME) IN UPPER(('DB TIME' )) GROUP BY B.SNAP_ID, INSTANCE_NUMBER) A, DBA_HIST_SNAPSHOT B WHERE A.SNAP_ID = B.SNAP_ID AND B.DBID = (SELECT DBID FROM V DATABASE)ANDUPPER(B.STATNAME)INUPPER((DBTIME))GROUPBYB.SNAPID,INSTANCENUMBER)A,DBAHISTSNAPSHOTBWHEREA.SNAPID=B.SNAPIDANDB.DBID=(SELECTDBIDFROMVDATABASE)
AND B.INSTANCE_NUMBER = A.INSTANCE_NUMBER)
WHERE TO_CHAR(BEGIN_TIME, ‘YYYY-MM-DD’) = TO_CHAR(SYSDATE , ‘YYYY-MM-DD’)
ORDER BY BEGIN_TIME;

本文 SQL 命令由于微信编辑器原因可能出现格式错误不能执行,这里将其保存至文本文件中方便复制粘贴执行,
如有需要的小伙伴们在本公众号【JiekeXu DBA之路】扫描最下方二维码后台回复 【SQL大全二】即可获取。

45、连接数相关查看
show parameter process
–查看最大连接数
select value from v$parameter where name =‘processes’;

–查两个节点连接数
select INST_ID,count(*) from gv$session group by inst_id;

–查看起库以来最大连接数
select resource_name,MAX_UTILIZATION,LIMIT_VALUE from v$resource_limit where resource_name in (‘processes’,‘sessions’);

–查看并发连接数
Select INST_ID,count(*) from gv$session where status=‘ACTIVE’ group by inst_id;

–查看不同用户的连接数
select username,count(username) from v$session where username is not null group by username;

46、查当前的等待事件
col wait_class for a20
set lines 200 pages 200
col event for a60
select event,count(*),wait_class from v$session_wait group by event,wait_class order by 3;

47、查看归档是否有错误
select dest_name,error from v$archive_dest;

48、查看数据库运行时间
select to_char(startup_time,‘DD-MON-YYYY HH24:MI:SS’) ‘启动时间’,
TRUNC(sysdate-(startup_time))||‘天’||TRUNC(24*((sysdate-startup_time)-TRUNC(sysdate-startup_time)))
||‘小时’||MOD(TRUNC(1440*((SYSDATE-startup_time)-TRUNC(sysdate-startup_time))),60)
||‘分’||MOD(TRUNC(86400*((SYSDATE-STARTUP_TIME)-TRUNC(SYSDATE-startup_time))),60)||‘秒’ ‘运行时间’
from gv$instance;

49、查询dg同步延迟
select ceil((sysdate-next_time)2460) “M” from vKaTeX parse error: Expected 'EOF', got '#' at position 46: …S' AND SEQUENCE#̲=(SELECT MAX(SE…ARCHIVED_LOG WHERE applied=‘YES’);

50、查询数据库安装时间
select a.name,to_char(a.created,‘yyyy.mm.dd’),b.instance_name from gv d a t a b a s e a , g v database a,gv databasea,gvinstance b where a.inst_id=b.inst_id;

51、查看 sys 用户使用情况
select b.username,h.machine,to_char(h.sample_time,‘yyyymmdd hh24:mi:ss’) time,count(*)
from dba_hist_active_sess_history h ,dba_users b
where h.user_id=b.user_id and b.username in(‘SYSTEM’,‘SYS’) and h.MACHINE not in (select host_name from gv$instance)
and h.sample_time>to_date(‘20210208’,‘yyyymmdd’)
group by b.username,h.machine,to_char(h.sample_time,‘yyyymmdd hh24:mi:ss’);

52、查询redo每天切换次数
select trunc(FIRST_TIME,‘dd’),count(1)
from v$log_history
where trunc(FIRST_TIME,‘dd’)>sysdate-10
group by trunc(FIRST_TIME,‘dd’)
order by 1;

53、查看每天归档产生数据量 归档量
–按天计算
select trunc(FIRST_TIME,‘dd’) Time,sum(BLOCKS*BLOCK_SIZE)/1024/1024/1024 Total_GB from v$archived_log
group by trunc(FIRST_TIME,‘dd’) order by 1;

–按小时计算
select trunc(FIRST_TIME,‘hh’) Time,sum(BLOCKS*BLOCK_SIZE)/1024/1024/1024 Total_GB from v$archived_log
group by trunc(FIRST_TIME,‘hh’) order by 1;

54、redo日志产生频率
select a.recid,to_char(a.first_time,‘yyyy-mm-dd hh24:mi:ss’) begin_time,
b.recid,to_char(b.first_time,‘yyyy-mm-dd hh24:mi:ss’) end_time,
round((b.first_time-a.first_time)2460,2) minutes
from v l o g h i s t o r y a , v log_history a,v loghistorya,vlog_history b
where b.recid = a.recid+1 and to_char(a.first_time,‘yyyy-mm-dd hh24:mi:ss’) >=to_char(sysdate-10,‘yyyy-mm-dd hh24:mi:ss’) ;

desc dba_hist_active_sess_history; ----可以查询执行过的sql的主机

55、AIX 查看僵尸进程
ps -ef | grep defunct

56、清理LOCAL=NO连接
ps -ef | grep LOCAL=NO | grep -v grep | awk ‘{print $2}’ |xargs kill -9

57、AIX 系统查看错误
errpt | head -20

58、rman查看归档备份
rman target /
list backup of archivelog all;

59、查看 rman 备份进度
set line 200 pages 1000
col MESSAGE for a60
col TARGET for a20
select sid,SERIAL#,TARGET,START_TIME,ELAPSED_SECONDS,TIME_REMAINING,MESSAGE,ROUND(SOFAR/TOTALWORK*100,2) “%_COMPLETE”
from v$session_longops
where 1=1 --and sid=2983 and SERIAL#=5
and TIME_REMAINING>0 ;

60、查询创建用户的日期
select t.username, t.account_status, t.created, t.default_tablespace from DBA_USERS t
where username= ‘ABASE’ order by t.created desc;

61、rman全库备份
run {
allocate channel c1 type disk ;
allocate channel c2 type disk ;
allocate channel c3 type disk ;
allocate channel c4 type disk ;
backup as compressed backupset database format ‘/backup/%d_%I_%s_%p.bak’;
backup as compressed backupset archivelog all format ‘/backup/%d_%I_%s_%p.arc’;
backup current controlfile for standby format ‘/backup/%d_%I_%s_%p.ctl’;
release channel c1;
release channel c2;
release channel c3;
release channel c4;
}

–压缩全库备份
backup database format=’/u01/app/backup/rman/eweaverstb_%s.bak’ filesperset 4;
run{
backup as compressed backupset database format=’/u01/app/backup/ewverstb_%s.bak’ plus archivelog delete input skip inaccessible;
}

62、数据泵导入导出相关命令
–expdp导入导出
select * from dba_directories where directory_name =‘DATA_PUMP_DIR’;
如果目录过小或者不存在,则
create directory expdp_dir as ‘/u01/app/backup/expdp_dir’;
grant read,write on directory expdp_dir to public;
expdp ‘/ as sysdba’ directory=expdp_dir dumpfile=full_bak.dmp full=y;

impdp ‘/ as sysdba’ directory=expdp_dir dumpfile=full_bak.dmp full=y;

impdb ‘/ as sysdba’ DIRECTORY=dump_dir DUMPFILE=full.dmp FULL=y;

–使用 par 文件全库导出
more full_expdp_query.par
directory=exp_dir1
logfile=full_new_exclude.log
dumpfile=full_new_exclude_%U.dmp
exclude=table:“in(‘LOGSAVE2017’,‘LOGSAVE_20210115’)”
query=ECARGO.POLICYATTACHMENTS:“where createtime>=to_date(‘20200901’,‘YYYYMMDD’)”
exclude=statistics
full=y
parallel=8
cluster=N

nohup expdp “/ as sysdba” parfile=full_expdp_query.par &

–导入
more full_impdp_query.par
directory=imp_dir1
logfile=impdp_full_query.log
dumpfile=full_expdp_query_%U.dmp
CLUSTER=N
parallel=8

nohup impdp “/ as sysdba” parfile=full_impdp_query.par &

expdp ‘/ as sysdba’ directory=expdp_dir dumpfile=tbs_bak.dmp tables=(XXX,XXX)

expdp ‘/ as sysdba’ directory=expdp_dir dumpfile=tbs_bak.dmp tables=(YHZXPROD.SU_ACTUALCOMPEMRESPONINFO,YHZXPROD.SU_BASICINFO,YHZXPROD.SU_SENDXML,YHZXPROD.SU_SENDXMLBATCH) fromuser=xxx touser=xxx log=tab.log

expdp ‘/ as sysdba’ directory=ANTIF_DP dumpfile=PICCATSSIX_20190808.DMP logfile=PICCATSSIX_20190809.log fromuser=PICCATSSIX touser=ATS

expdp ‘/ as sysdba’ directory=expdp_dir dumpfile=bbruser.dmp logfile=bbruser.log fromuser=bbruser touser=bbinfo

–只导出全库索引
expdp ’ / as sysdba ’ directory=exp_dir dumpfile=index.dmp logfile=out_index.log cluster=n include=INDEX full=y
Export: Release 11.2.0.3.0 - Production on Wed Feb 3 14:45:50 2021

Copyright © 1982, 2011, Oracle and/or its affiliates. All rights reserved.
;;;
Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
FLASHBACK automatically enabled to preserve database integrity.
Starting “SYS”.“SYS_EXPORT_FULL_01”: “ FORCE_MATCHING_SIGNATURE from v SQLwhereFORCEMATCHINGSIGNATUREin(select/+unnest/FORCEMATCHINGSIGNATUREfromvsql
where FORCE_MATCHING_SIGNATURE > 0
and FORCE_MATCHING_SIGNATURE != EXACT_MATCHING_SIGNATURE
group by FORCE_MATCHING_SIGNATURE
having count(1) > 10);
28、查询产生热块较多的对象
SELECT e.owner, e.segment_name, e.segment_type, b.tch
FROM dba_extents e, (SELECT *
FROM (SELECT dbarfil, dbablk, tch
FROM x b h O R D E R B Y t c h D E S C ) W H E R E R O W N U M < 11 ) b W H E R E e . r e l a t i v e f n o = b . d b a r f i l A N D e . b l o c k i d < = b . d b a b l k A N D e . b l o c k i d + e . b l o c k s > b . d b a b l k ; 29 、 查 询 7 天 的 d b t i m e T H s y s s t a t A S ( s e l e c t s n . b e g i n i n t e r v a l t i m e b e g i n i n t e r v a l t i m e , s n . e n d i n t e r v a l t i m e e n d i n t e r v a l t i m e , s s . s t a t n a m e s t a t n a m e , s s . v a l u e e v a l u e , l a g ( s s . v a l u e , 1 ) o v e r ( o r d e r b y s s . s n a p i d ) b v a l u e f r o m d b a h i s t s y s s t a t s s , d b a h i s t s n a p s h o t s n w h e r e t r u n c ( s n . b e g i n i n t e r v a l t i m e ) > = s y s d a t e − 7 a n d s s . s n a p i d = s n . s n a p i d a n d s s . d b i d = s n . d b i d a n d s s . i n s t a n c e n u m b e r = s n . i n s t a n c e n u m b e r a n d s s . d b i d = ( s e l e c t d b i d f r o m v bh ORDER BY tch DESC) WHERE ROWNUM < 11) b WHERE e.relative_fno = b.dbarfil AND e.block_id <= b.dbablk AND e.block_id + e.blocks > b.dbablk; 29、查询 7 天的 db time TH sysstat AS (select sn.begin_interval_time begin_interval_time, sn.end_interval_time end_interval_time, ss.stat_name stat_name, ss.value e_value, lag(ss.value, 1) over(order by ss.snap_id) b_value from dba_hist_sysstat ss, dba_hist_snapshot sn where trunc(sn.begin_interval_time) >= sysdate - 7 and ss.snap_id = sn.snap_id and ss.dbid = sn.dbid and ss.instance_number = sn.instance_number and ss.dbid = (select dbid from v bhORDERBYtchDESC)WHEREROWNUM<11)bWHEREe.relativefno=b.dbarfilANDe.blockid<=b.dbablkANDe.blockid+e.blocks>b.dbablk;297dbtimeTHsysstatAS(selectsn.beginintervaltimebeginintervaltime,sn.endintervaltimeendintervaltime,ss.statnamestatname,ss.valueevalue,lag(ss.value,1)over(orderbyss.snapid)bvaluefromdbahistsysstatss,dbahistsnapshotsnwheretrunc(sn.beginintervaltime)>=sysdate7andss.snapid=sn.snapidandss.dbid=sn.dbidandss.instancenumber=sn.instancenumberandss.dbid=(selectdbidfromvdatabase)
and ss.instance_number = (select instance_number from v$instance)
and ss.stat_name = ‘DB time’)
select to_char(BEGIN_INTERVAL_TIME, ‘mm-dd hh24:mi’) ||
to_char(END_INTERVAL_TIME, ’ hh24:mi’) date_time, stat_name, round((e_value - nvl(b_value, 0)) /
(extract(day from(end_interval_time - begin_interval_time)) * 24 * 60 * 60 +
extract(hour from(end_interval_time - begin_interval_time)) * 60 * 60 +
extract(minute from(end_interval_time - begin_interval_time)) * 60 +
extract(second from(end_interval_time - begin_interval_time))), 0) per_sec
from sysstat
where (e_value - nvl(b_value, 0)) > 0
and nvl(b_value, 0) > 0
30、导出 AWR 报告的 SQL 语句
select * from dba_hist_snapshot
select * from table(dbms_workload_repository.awr_report_html(DBID, INSTANCE_NUMBER, startsnapid,endsnapid))
select * from TABLE(DBMS_WORKLOAD_REPOSITORY.awr_diff_report_html(DBID, INSTANCE_NUMBER, startsnapid,endsnapid, DBID, INSTANCE_NUMBER, startsnapid,endsnapid));
31、自动定时任务调整
col WINDOW_NAME for a15
col REPEAT_INTERVAL for a60
col DURATION for a30
set linesize 120
SELECT t1.window_name, t1.repeat_interval, t1.duration
FROM dba_scheduler_windows t1, dba_scheduler_wingroup_members t2
WHERE t1.window_name = t2.window_name
AND t2.window_group_name IN
(‘MAINTENANCE_WINDOW_GROUP’, ‘BSLN_MAINTAIN_STATS_SCHED’);
WINDOW_NAME REPEAT_INTERVAL
DURATION



MONDAY_WINDOW freq=daily;byday=MON;byhour=22;byminute=0; bysecond=0 +000 04:00:00
TUESDAY_WINDOW freq=daily;byday=TUE;byhour=22;byminute=0; bysecond=0 +000 04:00:00
WEDNESDAY_WINDO freq=daily;byday=WED;byhour=22;byminute=0; bysecond=0 +000 04:00:00
THURSDAY_WINDOW freq=daily;byday=THU;byhour=22;byminute=0; bysecond=0 +000 04:00:00
FRIDAY_WINDOW freq=daily;byday=FRI;byhour=22;byminute=0; bysecond=0 +000 04:00:00
SATURDAY_WINDOW freq=daily;byday=SAT;byhour=6;byminute=0; bysecond=0 +000 20:00:00
SUNDAY_WINDOW freq=daily;byday=SUN;byhour=6;byminute=0; bysecond=0 +000 20:00:00 --备注:
#freq=daily:每天收集;
#;byday=SUN:一周之内的星期,例如这里是星期日;
#byhour=22 :每天的时间点时,这里是 22 时;
#byminute=0:每天的的时间点分,这里是 0 分,则第 1 分;
#bysecond=0:每天的时间点秒,这里是 0 秒,则第 1 秒;
#+000 20:00:00 :表示收集信息的时间区间长,这里表示 20 小时。
—修改自动收集统计信息计划任务时间:
–首先停止原来计划;
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“THURSDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“MONDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“TUESDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“WEDNESDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“FRIDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“SATURDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.DISABLE(
name => ‘“SYS”.“SUNDAY_WINDOW”’);
end;
/
–修改计划任务的执行时间:
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“THURSDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“MONDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“TUESDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“WEDNESDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“FRIDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“SATURDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“SUNDAY_WINDOW”’,
attribute => ‘REPEAT_INTERVAL’,
value =>
‘freq=daily;byday=THU;byhour=3;byminute=0;bysecond=0’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“SATURDAY_WINDOW”’,
attribute => ‘DURATION’,
value =>
‘+000 04:00:00’);
end;
/
BEGIN
DBMS_SCHEDULER.SET_ATTRIBUTE(
name => ‘“SYS”.“SUNDAY_WINDOW”’,
attribute => ‘DURATION’,
value =>
‘+000 04:00:00’);
end;
/
–启用新的计划任务的执行时间:
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“THURSDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“MONDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“TUESDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“WEDNESDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“FRIDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“SATURDAY_WINDOW”’);
end;
/
BEGIN
DBMS_SCHEDULER.ENABLE(
name => ‘“SYS”.“SUNDAY_WINDOW”’);
end;
/
禁用 SQL TUNING TASK
BEGIN
dbms_auto_task_admin.disable(
client_name => ‘sql tuning advisor’,
operation => NULL,
window_name => NULL);
END;
/
BEGIN
dbms_auto_task_admin.disable(
client_name => ‘auto space advisor’,
operation => NULL,
window_name => NULL);
END;
/
32.非常详细的查看表空间使用率
SET PAGESIZE 9999 LINESIZE 180;
TTI ‘Tablespace Usage Status’
COL TABLESPACE_NAME FOR A20;
COL TBS_MAX_SIZE FOR 99999.99;
COL TABLESPACE_SIZE FOR 99999.99;
COL TBS_AVABLE_SIZE FOR 999999.99;
COL “USED_RATE(%)” FOR A16;
COL “ACT_USED_RATE(%)” FOR A16;
COL “FREE_SIZE(GB)” FOR 99999999.99;
SELECT UPPER(F.TABLESPACE_NAME)
AS “TABLESPACE_NAME”, ROUND(D.MAX_BYTES,2)
AS “TBS_MAX_SIZE” , ROUND(D.AVAILB_BYTES ,2)
AS “ACT_TABLESPACE_SIZE”, ROUND((D.AVAILB_BYTES - F.USED_BYTES),2)
AS “TBS_USED_SIZE”, ROUND(F.USED_BYTES, 2)
AS “FREE_SIZE(GB)”, TO_CHAR(ROUND((D.AVAILB_BYTES - F.USED_BYTES) / D.AVAILB_BYTES * 100, 2),
‘999.99’)
AS “USED_RATE(%)”, TO_CHAR(ROUND((D.AVAILB_BYTES -
F.USED_BYTES)/D.MAX_BYTES100, 2),
‘999.99’)
AS “ACT_USED_RATE(%)”, ROUND(D.MAX_BYTES - D.AVAILB_BYTES
+USED_BYTES,2) AS “TBS_AVABLE_SIZE”
FROM (SELECT TABLESPACE_NAME, ROUND(SUM(BYTES) / (1024 * 1024 *
1024), 6) USED_BYTES, ROUND(MAX(BYTES) / (1024 * 1024 *
1024), 6) MAX_BYTES
FROM SYS.DBA_FREE_SPACE
GROUP BY TABLESPACE_NAME) F, (SELECT DD.TABLESPACE_NAME, ROUND(SUM(DD.BYTES) / (1024 * 1024 *
1024), 6) AVAILB_BYTES, ROUND(SUM(DECODE(DD.MAXBYTES, 0, DD.BYTES, DD.MAXBYTES))/(1024
1024*1024),6)
MAX_BYTES
FROM SYS.DBA_DATA_FILES DD
GROUP BY DD.TABLESPACE_NAME) D
WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME
ORDER BY “ACT_USED_RATE(%)” DESC;
vim get_tablespace_used_v3.sql
set pagesize 1000 linesize 180
tti ‘Tablespace Usage Status’
col “TOTAL(GB)” for 99,999,999.999
col “USAGE(GB)” for 99,999,999.999
col “FREE(GB)” for 99,999,999.999
col “EXTENSIBLE(GB)” for 99,999,999.999
col “MAX_SIZE(GB)” for 99,999,999.999
col “FREE PCT %” for 999.99
col “USED PCT OF MAX %” for 999.99
col “NO_AXF_NUM” for 9999
col “AXF_NUM” for 999
select d.tablespace_name “TBS_NAME”
,d.contents “TYPE”
,nvl(a.bytes /1024/1024/1024,0) “TOTAL(GB)”
,nvl(a.bytes - nvl(f.bytes,0),0)/1024/1024/1024
“USAGE(GB)”
,nvl(f.bytes,0)/1024/1024/1024 “FREE(GB)”
,nvl((a.bytes - nvl(f.bytes,0))/a.bytes * 100,0) “FREE
PCT %”
,nvl(a.ARTACAK,0)/1024/1024/1024
“EXTENSIBLE(GB)”
,nvl(a.MAX_BYTES,0)/1024/1024/1024
“MAX_SIZE(GB)”
,nvl((a.bytes - nvl(f.bytes,0))/ (a.bytes +
nvl(a.ARTACAK,0)) * 100,0) “USED PCT OF MAX %”
,a.NO_AXF_NUM
,a.AXF_NUM
from sys.dba_tablespaces d, (select tablespace_name
,sum(bytes) bytes
,sum(decode(autoextensible,‘YES’,maxbytes - bytes,0 ))
ARTACAK
,count(decode(autoextensible,‘NO’,0))
NO_AXF_NUM
,count(decode(autoextensible,‘YES’,0)) AXF_NUM
,sum(decode(maxbytes, 0, BYTES, maxbytes))
MAX_BYTES
from dba_data_files
group by tablespace_name
) a,
(select tablespace_name
,sum(bytes) bytes
from dba_free_space
group by tablespace_name
) f
where d.tablespace_name = a.tablespace_name(+)
and d.tablespace_name = f.tablespace_name(+)
and not (d.extent_management like ‘LOCAL’and d.contents
like ‘TEMPORARY’)
union all
select d.tablespace_name “TBS_NAME”
,d.contents “TYPE”
,nvl(a.bytes /1024/1024/1024,0) “TOTAL(GB)”
,nvl(t.bytes,0)/1024/1024/1024 “USAGE(GB)”
,nvl(a.bytes - nvl(t.bytes,0),0)/1024/1024/1024
“FREE(GB)”
,nvl(t.bytes/a.bytes * 100,0) “FREE PCT %”
,nvl(a.ARTACAK,0)/1024/1024/1024
“EXTENSIBLE(GB)”
,nvl(a.MAX_BYTES,0)/1024/1024/1024
“MAX_SIZE(GB)”
,nvl(t.bytes/(a.bytes + nvl(a.ARTACAK,0)) * 100,0)
“USED PCT OF MAX %”
,a.NO_AXF_NUM
,a.AXF_NUM
from sys.dba_tablespaces d, (select tablespace_name
,sum(bytes) bytes
,sum(decode(autoextensible,‘YES’,MAXbytes - bytes,0 )) ARTACAK
,count(decode(autoextensible,‘NO’,0)) NO_AXF_NUM
,count(decode(autoextensible,‘YES’,0)) AXF_NUM
,sum(decode(maxbytes, 0, BYTES, maxbytes))
MAX_BYTES
from dba_temp_files
group by tablespace_name
) a, (select tablespace_name
, sum(bytes_used) bytes
from vKaTeX parse error: Expected 'EOF', got '&' at position 519: …NC (SYSDATE) - &̲days_back AND s…session a, v s q l b w h e r e s t a t u s = ′ A C T I V E ′ a n d u s e r n a m e i s n o t n u l l a n d a . s q l i d = b . s q l i d a n d a . s q l c h i l d n u m b e r = b . c h i l d n u m b e r a n d s q l t e x t n o t l i k e ′ sql b where status = 'ACTIVE' and username is not null and a.sql_id = b.sql_id and a.sql_child_number = b.child_number and sql_text not like '%from v sqlbwherestatus=ACTIVEandusernameisnotnullanda.sqlid=b.sqlidanda.sqlchildnumber=b.childnumberandsqltextnotlikesession a, vKaTeX parse error: Expected 'EOF', got '#' at position 128: …:为 sid 和 serial#̲的值。 EVENT:等待事件。…session_longops L,V$SESSION S
where time_remaining > 0 AND L.SID=S.SID
order by start_time;
39.selectivity <5 一般选择性小于 5% 就属于选择性差
select a.OWNER, a.INDEX_NAME, a.TABLE_NAME, a.DISTINCT_KEYS Cardinality,
a.NUM_ROWS, round(a.DISTINCT_KEYS / NUM_ROWS * 100, 2)
selectivity
from dba_ind_statistics a
where a.NUM_ROWS > 0
and round(a.DISTINCT_KEYS / NUM_ROWS * 100, 2) <=
5
and A.OWNER = upper(’&owner’); --如果统计信息有可能不是最新的 最好使用下面的语句
select table_name,index_name,round(distinct_keys/num_rows *
100, 2) selectivity from user_indexes;
40.如何查看列的选择性和基数呢?
select a.column_name, b.num_rows, a.num_distinct Cardinality, round(a.num_distinct / b.num_rows * 100, 2) selectivity, a.histogram, a.num_buckets
from dba_tab_col_statistics a, dba_tables b
where a.owner = b.owner
and a.table_name = b.table_name
and a.owner = upper(’&owner’)
and a.table_name = upper(’&table_name’)
and a.column_name = upper(’&column_name’);
欢迎关注我的公众号【JiekeXu DBA 之路】,第一时间一起学习新知识!
————————————————————————————
公众号:JiekeXu DBA 之路
CSDN :https://blog.csdn.net/JiekeXu
墨天轮:https://www.modb.pro/u/4347
腾讯云:https://cloud.tencent.com/developer/user/5645107 ————————————————————————————