Oracle数据库基本知识点

Oracle数据库

基础部分

序列

Create sequence seq_name
Minvalue 1
Maxvalue 999999999999999999999999999
Start with 1
Increment by 1
Cache 3000;

create table ACTIVITYSTATEEVENTAUDITS (
 keyvalue VARCHAR2(30) not null,
  ……………………..
)
-- Create/Recreate primary, unique andforeign key constraints
alter table ACTIVITYSTATEEVENTAUDITS add constraint ACTIVITYSTATEEVENTAUDITS5 primary key (OID)

视图

Create or replace view view_name as
Select * from table_name
Where ………;

Dblink

create database link db_name
connect to Q_PSMIS

同义词

create or replace synonym syno_name for table_name@dblink_name;

包头

CREATE OR REPLACE PACKAGE pag_name
AS
/******************************************************************************
 descript
******************************************************************************/   
PROCEDURE pro_name (
     obj_name      IN   VARCHAR,
     ……………….
     errmess       out   VARCHAR,
   );
END pro_name;

包体

CREATE OR REPLACE PACKAGE BODY  pag_name
AS
/******************************************************************************
descript
******************************************************************************/
PROCEDURE pro_name (
     obj_name      IN  VARCHAR,
     ……………….
     errmess       out   VARCHAR,
   );
   IS
     tmpvar   NUMBER;
  BEGIN
    -------------处理的主体部分
  END;
END pro_name;

存储过程

Create or replace procedure pro_name(
   Var  varchar2 in ;
   Num  number in ;
   Var  varchar2 out;
)
As
Beging
 --------------过程主体部分
End;

函数

create or replace function func_name(变量名 in 类型,………..) return 返回的类型
is
变量 变量类型;
………………
Begin
 --------处理主体部分
 Return值(与返回的类型一样)
end  func_name;

触发器

Create or replace trigger tri_name
 Alter/before ……------这里是触发时间类型
 Update/insert/delete …….--------这里是触发事件类型
 On
 table_name ……..----------这里是触对象,可以是表名,ddl对象名等

declare
  varvarchar2;  ------------定义变量
begin
 --------------------------------处理主体部分
end;

JOB

begin
 sys.dbms_job.submit(job => :job,
    what =>'update_pw_oms_emergency_car;',---这里是要调用的过程名
    next_date =>to_date('13-03-2011 22:00:00', 'dd-mm-yyyy hh24:mi:ss'),
    interval =>'trunc(sysdate+1,''DD'')+22/24');
 commit;
end;

   1:每分钟执行
  Interval =>TRUNC(sysdate,'mi') + 1/ (24*60)
  或
  Interval =>sysdate+1/1440

  2:每天定时执行
  例如:每天的凌晨1点执行
  Interval =>TRUNC(sysdate) + 1 +1/ (24)

  3:每周定时执行
  例如:每周一凌晨1点执行
  Interval =>TRUNC(next_day(sysdate,'星期一'))+1/24

  4:每月定时执行
  例如:每月1日凌晨1点执行
  Interval=>TRUNC(LAST_DAY(SYSDATE))+1+1/24

  5:每季度定时执行
  例如每季度的第一天凌晨1点执行
  Interval =>TRUNC(ADD_MONTHS(SYSDATE,3),'Q') + 1/24

  6:每半年定时执行
  例如:每年7月1日和1月1日凌晨1点
  Interval =>ADD_MONTHS(trunc(sysdate,'yyyy'),6)+1/24

  7:每年定时执行
    例如:每年1月1日凌晨1点执行
    Interval =>ADD_MONTHS(trunc(sysdate,'yyyy'),12)+1/24

固化视图

CREATE MATERIALIZED VIEW PW_EIP_TODOTASK
REFRESH COMPLETE ON DEMAND
AS
select ..... from tab_name
where  .......;

JAVA存储过程

高级部分

表空间

创建表空间

CREATE TABLESPACE tablespace_name  datafile 'E:\ora_data\tablespaces\KKX_GD.ora'
SIZE 5M autoextend on next 64m maxsize unlimited extent  management local uniformsize 256K ;

增加表空间文件

Alter database add datafile 'E:\ora_data\tablespaces\KKX_GD1.ora'
SIZE 5M autoextend on next 64m maxsize unlimited extent  management local uniformsize 256K ;

修改表空间大小

Alter database datafile 'E:\ora_data\tablespaces\KKX_GD1.ora'resize 100m;

常用用户授权

1.数据库管理员系统权限(数据库实体管理部分)

ADUIT ANY

CREATE ANY CLUSTER

ALTER ANY CLUSTER

DROP ANY CLUSTER

CREATE ANY INDEX

ALTER ANY INDEX

DROP ANY INDEX

GRANT ANY PRIVILEGE

CREATE ANY PROCEDURE

ALTER ANY PROCEDURE

DROP ANY PROCEDURE

EXECUTE ANY PROCEDURE

ALTER ANY ROLE

DROP ANY ROLE

GRANT ANY ROLE

CREATE ANY SEQUENCE

ALTER ANY SEQUENCE

DROP ANY SEQUENCE

SELECT ANY SEQUENCE

CREATE ANY SNAPSHOT

ALTER ANY SNAPSHOT

DROP ANY SNAPSHOT

CREATE ANY SYSNONYM

DROP ANY SYSNONYM

CREATE ANY TABLE

ALTER ANY TABLE

DROP ANY TABLE

LOCK ANY TABLE

COMMENT ANY TABLE

SELECT ANY TABLE

INSERT ANY TABLE

UPDATE ANY TABLE

DELETE ANY TABLE

CREATE ANY TRIGGER

ALTER ANY TRIGGER

DROP ANY TRIGGER

CREATE ANY VIEW

DROP ANY VIEW

CREATE ANY TYPE

DROP ANY TYPE

CREATE ANY LIBRARY

DROP ANY LIBRARY

2.数据库管理系统权限(数据库维护部分)

ALTER DATABASE

CREATE PROFILE

ALTER PROFILE

DROP PROFILE

ALTER RESOURCE COST

CREATE PUBLIC DATABASE LINK

DROP PUBLIC DATABASE LINK

CREATE ROLE

CREATE ROLLBACK SEGMENT

ALTER ROLLBACK SEGMENT

DROP ROLLBACK SEGMENT

ALTER SYSTEM

CREATE TABLESPACE

ALTER TABLESPACE

MANAGE TABLESPACE

ALTER USER

DROP USER

CREATE SESSION

CREATE PUBLIC SYNONYM

DROP PUBLIC SYNONYM

UNLIMITED TABLESPACE

CREATE ROLE

DROP ROLE

3.数据库开发用户系统权限表

grant CREATE CLUSTER

grant DROP CLUSTER

grant CREATE PROCEDURE

grant DROP PROCEDURE

grant CREATE DATABASE LINK

grant CREATE SYSNONYM

grant DROP SYNONYM

grant CREATE SEQUENCE

grant CREATE SNAPSHOTP

grant CREATE TABLE

grant CREATE VIEW

grant CREATE TYPE

grant CREATE LIBRARY

SQL性能优化

表空间、内存、CPU的使用率

#检查表空间使用情况

select f.tablespace_name,

      a.total,

      f.free,

      (a.total - f.free) / 1024 "used SIZE(G)",

      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

 WHEREa.tablespace_name = f.tablespace_name(+)

 order by "% Free"

#查询临时segment使用情况

SELECT username,

      segtype,

      extents  "ExtentsAllocated",

      blocks   "BlocksAllocated"

 FROM v$tempseg_usage;

#查看数据文件信息

SELECT fs.phyrds   "Reads",

      fs.phywrts  "Writes",

      fs.avgiotim "Average I/O Time",

       df.name    "Datafile"

 FROM v$datafile df, v$filestat fs

 WHERE df.file# = fs.file#;

#查看所有数据文件i/o情况

SELECT ts.name      AS ts,

      fs.phyrds    "Reads",

      fs.phywrts   "Writes",

      fs.phyblkrd  AS br,

      fs.phyblkwrt AS bw,

      fs.readtim   "RTime",

      fs.writetim  "WTime"

 FROM v$tablespace ts, v$datafile df, v$filestat fs

 WHERE ts.ts# = df.ts#

  AND df.file# = fs.file#

UNION

SELECT ts.name      AS ts,

      ts.phyrds    "Reads",

      ts.phywrts   "Writes",

      ts.phyblkrd  AS br,

      ts.phyblkwrt AS bw,

      ts.readtim   "RTime",

      ts.writetim  "WTime"

 FROM v$tablespace ts, v$tempfile tf, v$tempstat ts

 WHERE ts.ts# = tf.ts#

  AND tf.file# = ts.file#

 ORDER BY 1;

#获取top 10 热segment

select *

 from (select ob.owner, ob.object_name, sum(b.TS#) Touchs

         from v$bh b, dba_objects ob

        where b.OBJD = ob.data_object_id

          and b.ts# > 0

        group by ob.owner, ob.object_name

        order by sum(b.ts#) desc)

 where rownum <= 10

#判断物理读最多的object

select *

 from (select owner, object_name, value

         from v$segment_statistics

        where statistic_name = 'physical reads'

        order by value desc)

 where rownum <= 10

#查看热点数据文件(从单块读取时间判断)

SELECT t.file_name,

      t.tablespace_name,

      round(s.singleblkrdtim / s.singleblkrds, 2) AS CS,

      s.READTIM,

      s.WRITETIM

 FROM v$filestat s, dba_data_files t

 WHERE s.file# = t.file_id

  and rownum <= 10

 order by cs desc;



******************************查看redo

#检查日志切换频率

select sequence#,

      to_char(first_time, 'yyyymmdd_hh24:mi:ss') firsttime,

      round((first_time - lag(first_time) over(order by first_time)) * 24 *60,

            2) minutes

 from v$log_history

 where first_time > sysdate - 1

 orderby first_time, minutes;

#检查lgwr i/o性能(time_waited/total_waits:表示平均lgwr写入完成时间若>1表示写入过慢)

select total_waits,

      time_waited,

      average_wait,

      time_waited / total_waits as avg

 from v$system_event

 where event = 'log file parallel write';

#检查与redo相关性能指标

select name,value from v$sysstat where namelike '%redo%';

#查看redo allocation latch

select name, gets, misses, misses / gets

 from v$latch_children

 where name = 'redo allocation';

#查看与redo相关等待事件

select event, total_waits, total_timeouts,average_wait

 from v$system_event

 where upper(event) like '%REDO%';

#查看session redo event

selectevent,total_waits,total_timeouts,average_wait from v$session_event whereupper(event) like'%REDO%';

#查看系统运行时间

select (sysdate - startup_time)*24*60*60 asseconds from v$instance

#计算出每个事务平均处理多少个redo block

select value from v$sysstat where name ='redo blocks written';

#查看buffer cache 命中率

select 1 - (sum(decode(name, 'physicalreads', value, 0)) /

      (sum(decode(name, 'db block gets', value, 0)) +

      (sum(decode(name, 'consistent gets', value, 0))))) "Buffer HitRatio"

 from v$sysstat;

#查看buffer cache建议

1.
select size_for_estimate,estd_physical_read_factor,
to_char(estd_physical_reads, 99999999999999999999999)as"estd_physical_reads"
from v$db_cache_advice
where name = 'DEFAULT';

2.
SELECT (SELECT ROUND(value / 1024 / 1024,0)
FROM v$parameter
WHERE name = 'db_cache_size') "Current Cache(Mb)",name "Pool",
size_for_estimate "ProjectedCache(Mb)",
ROUND(100 - estd_physical_read_factor, 0) "Cache Hit Ratio%"
FROM v$db_cache_advice
WHERE block_size =
(SELECT value FROM v$parameter WHERE name = 'db_block_size')
ORDER BY 3;

#查看buffer cache中defalut pool 命中率

select name, 1 - (physical_reads) /(consistent_gets + db_block_gets) from v$buffer_pool_statistics;

#检查shared pool中library cache

select namespace,pinhitratio fromv$librarycache;

#检查整体命中率(library cache)

select sum(pins) "hits",

sum(reloads) "misses",

sum(pins)/(sum(pins)+sum(reloads))"Hits Ratio"

from v$librarycache;

#检查shered pool free space

SELECT * FROM V$SGASTAT WHERE NAME = 'free memory' AND POOL = 'shared pool';

1. 监控事例的等待

select event,sum(decode(wait_Time,0,0,1))"Prev", sum(decode(wait_Time,0,1,0))"Curr",count(*) "Tot" from v$session_Wait group by event order by 4;

2. 回滚段的争用情况

select name, waits, gets, waits/gets"Ratio"

from v$rollstat a, v$rollname b

where a.usn = b.usn;

3. 监控表空间的 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;

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$datafile a, v$filestat b

 where a.file# = b.file#;

6. 监控 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$sysstat a, v$sysstat b, v$sysstat c

 where a.statistic# = 38

  and b.statistic# = 39

   and c.statistic# = 40;

7. 监控 SGA 中字典缓冲区的命中率

select parameter,

      gets,

      Getmisses,

      getmisses / (gets + getmisses) * 100 "miss ratio",

      (1 - (sum(getmisses) / (sum(gets) + sum(getmisses)))) * 100 "Hitratio"

 from v$rowcache

 wheregets + getmisses <> 0

 group by parameter, gets, getmisses;

8. 监控 SGA 中共享缓存区的命中率,应该小于1%

1.select sum(pins) "Total Pins",

select sum(pins) "Total Pins",

sum(reloads) "Total Reloads",

sum(reloads) / sum(pins) * 100 libcache

 from v$librarycache;

2.select sum(pinhits-reloads)/sum(pins)"hit radio",sum(reloads)/sum(pins) "reload percent"

from v$librarycache;

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

11. 监控内存和硬盘的排序比率,最好使它小于 .10,增加 sort_area_size

SELECT name, value

 FROM v$sysstat

 WHERE name IN ('sorts (memory)', 'sorts(disk)');

13. 监控字典缓冲区

SELECT (SUM(PINS - RELOADS)) / SUM(PINS)"LIB CACHE" ,FROM V$LIBRARYCACHE;

SELECT (SUM(GETS - GETMISSES - USAGE - FIXED))/ SUM(GETS) "ROW CACHE" FROM V$ROWCACHE;

SELECT SUM(PINS) "EXECUTIONS",SUM(RELOADS) "CACHE MISSES WHILE EXECUTING", FROM V$LIBRARYCACHE;

后者除以前者,此比率小于1%,接近0%为好。

SELECT SUM(GETS) "DICTIONARYGETS",SUM(GETMISSES) "DICTIONARY CACHE GET MISSES"

FROM V$ROWCACHE

14. 找ORACLE字符集

select * from sys.props$ wherename='NLS_CHARACTERSET';

16. 碎片程度

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

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

17. 表、索引的存储情况检查

select segment_name, sum(bytes) space,count(*) ext_quan

 from dba_extents

 where segment_type = 'TABLE'

 group by tablespace_name, segment_name;

死锁

1、查看锁情况

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

2、查询锁定状态的session

SELECT s.username,

      l.OBJECT_ID,

      l.SESSION_ID,

      s.SERIAL#,

      l.ORACLE_USERNAME,

      l.OS_USER_NAME,

      l.PROCESS

 FROM V$LOCKED_OBJECT l, V$SESSION S

 WHERE l.SESSION_ID = S.SID

3、查询指定的某个session,通过status字段判断是否处于锁定状态

 select t.STATUS  from V$SESSION t where sid = 1029

4、杀掉进程  kill session

alter system kill session 'sid,serial_num';

 

你可能感兴趣的:(J2SE,Oracle)