第1章 配置恢复管理器Configuring Recovery Manager

组成:GUI或者命令行、可选的恢复目录、RMAN命令和脚本,以及磁带媒介连接

考虑事项:RMAN是一种物理备份方法。其他的备份恢复方法:用户管理和Oracle EXPORT工具(逻辑备份,一般不做为独立得备份方法,而是对RMAN或者用户管理的备份提供附加的备份护,exp,expdp)

可以使用控制文件或者恢复目录作为资料档案库。Oracle建议,中等规模的企业环境,使用恢复目录,这样可以充分发挥RMAN工具的全部功能。如果使用控制文件作为资料档案库,设置参数:CONTROL_FILE_RECORD_KEEP_TIME.

恢复目录必须存储在自己的数据库服务器中,而不是目标数据库所在的服务器中。为安全恢复数据库也备份。为了使目录能够工作,必须建立具有connect,resource和RECOVERY_CATALOG_OWNER权限的账户。新数据库参数如下:

1)SYSTEM 90M;UNDO 5M;TEMP 5M

2)三个日志文件组每组两个成员 1M

3)RECOVERY CATALOG表空间 CATTBS 15M

DBCA建立恢复目录数据库以及,然后实践第3步,创建恢复目录

书中数据库环境:目标数据库ORA101T,恢复目录数据库ORA101RC,恢复目录表空间DATA

(本机测试环境:目标数据库为prod,恢复目录数据库prodrman,恢复目录为CATTBS.

rman target /@prod catalog rman/rman@prodrman )

以下command>表示windows环境命令行。

command> SET ORACLE_SID = ora101rc

command>sqlplus /nolog

sql>connect / as sysdba

sql>create user rman_user identified by rman_user default tablespace data temporary tablespace temp;

sql>grant connect,resource,recovery_catalog_owner to rman_user;

command>rman

rman>connect catalog rman/rman

rman>create catalog tablespace data;

注册数据库

command> SET ORACLE_SID = ora101t

command>rman target /

rman>connect catalog "rman_user/rman_user@ora101rc";

rman>register database;

for example:备份整个数据库

command>set ORACLE_SID = ora101t

command>sqlplus /nolog

sql>connect / as sysdba

sql>startup mount

command>rman

rman>connect target

rman>connect catalog rman_user/rman_user@ora101rc;

rman>run

{

allocate channel c1 type disk;

backup database format 'G:\RMAN_BAKCUP3\db_%u_%d_%s';

backup format 'G:\RMAN_BAKCUP3\log_t%t_s%s_p%p' (archivelog all);

}

备份完成以后,就可以恢复数据库。数据库必须已安装,但没有打开。选择多个磁盘通道以利用并行恢复进程,这不是必须的,但可以改进重建和恢复时间。

RMAN>run

{

allocate channel c1 type disk;

allocate channel c2 type disk;

allocate channel c3 type disk;

restore database;

recover database;

alter database open;

}

启动和连接到RMAN

从命令行连接:

command>set ORACLE_SID=ora101rc

command>rman target / catalog rman_user/rman_user@ora101rc

从rman工具连接到目标数据库。

command>set ORCLE_SID=ora101t;

command>rman

rman>connect target

rman>connect catalog rman_user/rman_user@ora101rc;

媒介管理层(MML)界面使应用编程界面(API),它是RMAN与不同的硬件硬件供应商的磁带设备接口。这些磁带设备,是自动化磁带库(ATL),所有希望与ORACLE RMAN 一起工作的硬件供应商都做自己的MNL,因为大部分磁带硬件设备是有专利的,要求不同的程序调用。

通道分配

自动分配:

_________________________________________________________

CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO [COPY |[ COMPRESSED ]BACKUPSET] |clear|parallelism n

CONFIGURE DEFAULT DEVICE TYPE to deviceSpecifier|clear

CONFIGURE CHANNEL DEVICE TYPE disk|equal??

CONFIGURE CHANNEL n DEVICE TYPE disk|equal

-----------------------线内有些奇怪,略,看 example----------------------------

RMAN的参数和永久设置

RMAN>configure default device type to disk;

rman>configure default device type to sbt;

rman>configure device type disk backup type to copy;

rman>configure device type disk backup type to backupset;

rman>configure device type disk backup type to compressed backupset;

rman>configure device type sbt backup type to compressed backupset;

rman>configure channel device type disk format 'c:\backup\ora101rc\ora_dev_t%t_s%s_p%p;

rman>configure channel device type sbt PARMS='ENV=mnl_env_settings';

rman>configure device type sbt parallelism 3;

使用ENTERPRISE MANAGER 配置 RMAN 设置值

HTTP://hostname.domain:5500/em---->login-->Maintenance-->Backup/Recovery

保留策略

rman>configure retention policy to recovery window of 30 days;

run

{

allocate channel c1 type disk;

backup database format 'db_%u_%d_%s' tag monthly_backup;

backup format 'log_t%t_s%s_p%p' (archivelog all);

}

rman>change backupset tag monthly_backup nokeep;

rman>change backupset tag monthly_backup keep until time '01-DEC-04' logs;

rman>configure controlfile autobackup on;

rman>configure controlfile autobackup format for device type disk to 'c:\oracle\ora101rc\cf%F';

第2章 Using Recovery Manager

run

{

allocate channel c1 type disk;

backup database format 'db_%u_%d_%s' tag monthly_backup;

backup format 'log_t%t_s%s_p%p'

(archivelog all);

}

command>rman

rman>connect target

rman>run{

allocate channel c1 type disk;

backup database format 'db_%u_%d_%s';

backup format 'log_t%t_s%s_p%p'

(archivelog all);

}

rman>run

{

allocate channel ch1 tyep disk;

copy

datafile 1 to 'c:\oracle\staging\ora101t\system01.dbf',

current controlfile to 'c:\oracle\staging\ora101t\control01.ctl';

}

RMAN> delete datafilecopy 28;

command>rman

rman>connect target

rman>backup as copy tag "062504_backup" database;

rman>backup as compressed backupset database;

rman>configure device type disk backup type to compressed backupset;

dir *.bkp

Full and Incremental Backups

Full backups do not mean the complete database was backed up. In other words, a full backup can back up only part of the database and not all datafiles, control files, and logs.

a differential incremental and a cumulative incremental backup.

Performing a Differential Incremental Backup

rman>backup incremental level 0 database;

rman> backup incremental level 1 database;

Performing a Cumulative Incremental Backup

rman>backup incremental level 1 cumulative database;

备份集得并行化

command>set ORACLE_SID=ora101rc

command>rman

rman>run

{

allocate channel c1 type disk;

allocate channel c2 type disk;

backup

(datafile 1,2,3 channel c1)

(archivelog all channel c2);

}

rman>show all;

rman>configure device type disk parallelism 3;

rman>backup

(datafile 1,2)

(datafile 3,4)

(archivelog all);

rman>backup tablespace users format ='user_bs_%d%p%s';

rman>backup as copy tablespace users format='c:\oracle\backups\ora101rc\users_%d%p%s';

rman>backup database tag weekly_backup;

rman>configure channel device type disk rate 5m;

rman>configure channel device type disk maxsetsize=10g;

rman>backup database maxsetsize=10g;

rman>configure channel device type disk maxpiecesize=2G;

启动和关闭块变化跟踪

command>sqlplus /nolog

sql>connect / as sysdba

sql>select * from v$block_change_tracking;

sql>alter database enable block change tracking using file 'c:\oracle\block_track\ora101rc_block_track.log' reuse;

sql>alter database enable block change tracking using file '/backup/block_track.log';

sql>select filename,status,bytes from v$block_change_tracking;

sql>alter database disable block change tracking;

用EM管理备份

监视RMAN备份

sql>connect system/manager@ora101t

sql>select dbid from v$database;

sql>connect rman_user/rman_user@ora101rc

sql>select db_key from rc_database where dbid=1736563848;

sql>select bs_key,backup_type,completion_time

from rc_database_incarnation a,rc_backup_set b

where a.db_key = b.db_key

and a.current_incarnation = 'YES';

使用list命令。

rman>list backupset by backup summary;

rman>list backupset by file;

 

 

使用report命令

rman>REPORT OBSOLETE;

rman>REPORT SCHEMA;

使用RMAN作业示例

启用ARCHIVELOG模式

sql>alter system set log_archive_start=true scope=spfile;

sql>connect / as sysdba

sql>startup mount

sql>alter database archivelog;

sql>alter database open;

使用RMAN备份归档重执行日志

RUN

{

allocate channel c1 type disk;

allocate channel c2 type disk;

backup database;

backup (archivelog all);

}

制定备份工作计划表

第3章 Recovering From Non-Critical Losses

sql>create temporary tablespace temp2 tempfile 'c:\xxxxxxxx\xx.dbf' size 100m extent management local uniform size 128k;

sql>create temporary tablespace temp2 tempfile '/u02/oradata/orcl/temp02.dbf' size 100m extent management local uniform size 128k;

启动丢失临时文件得数据库

COMMAND>SQLPLUS /NOLOG

sql>connect / as sysdba

sql>startup mount

sql>drop tablespace temp including contents;

sql>create temporary tablespace temp2 tempfile 'c:\xxxxxxxx\xx.dbf' size 100m extent management local uniform size 128k;

改变数据库得默认临时表空间

sql>alter database default temporary tablespace temp2;

重建重执行日志文件

sql>alter database drop logfile member 'c:\oracle\oradata\ora101t\redo01.log';

sql>alter database add logfile member 'c:\oracle\oradata\ora101t\redo01.log' to group 1;

恢复索引表空间

SQLPLUS /NOLOG

sql>connect / as sysdba

sql>startup

sql>drop tablespace indexes including contents;

sql>create tablespace indexes datafile 'c:\oracle\oradata\ora1010t\index01.dbf' size 20m;

重建索引

CREATE UNIQUE INDEX example_index_pk

ON EXAMPLE_table

(column_one,

column_two,

column_three,

column_four)

PCTFREE 10

INITRANS 2

MAXTRANX 255

TABLESPACE indexes

STORAGE(

initial 1m

next 1m

PCTINCREASE 0

MINEXTENTS 1

MAXEXTENTS 8192

)

NOLOGGING

PARALLEL (degree 4)

/

sql>@create_example_index_pk

恢复只读表空军

SQL>ALTER tablespace users read only;

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>shutdown immediate

sql>host

command> cd c:\oracle\oradata\backup\ora101t

command>copy c:\oracle\oradata\ora101t\*

command cd ..\..\ora101t

command>delete users01.dbf

sql>startup

sql>shutdown immediate

sql>host

command>cd c:\oracle\oradata\ora101t

command>copy c:\oracle\oradata\backup\ora101t\users01.dbf users01.dbf

command>exit

sql>startup

重建密码文件(远程登陆用) an example of rebuilding a password file:

1. First, shut down the database:

SQL> shutdown immediate

SQL> startup

2. Run the ORAPWD utility to build the password file in the $ORACLE_HOME/dbs directory

in name convention orapw$ORACLE_SID. The entries option determines how many users

can be stored in the password file:

orapwd file=orapworcl password=syspass entries=20

To see what users are utilizing the password file, keep a copy of the following query:

SQL>SELECT * FROM V$PWFILE_USERS;

我的RHEL: $ORACLE_HOME/dbs orapworcl

第4章 数据库恢复 Database Recovery

Restore 和 Recovery

sql>connect / as sysdba

sql>startup mount

rman>run

{

allocate channel c1 type disk;

restore database;

recover database;

alter database open;

}

用户管理恢复

SQL>CONNECT / AS SYSDBA

SQL>STARTUP

command>copy ..\backup\ora101t\users01.dbf

sql>startup mount

sql>recover database;

sql>alter database open;

恢复控制文件

1. First, you must configure RMAN to perform a control file autobackup:

rman>connect target

SQL> select dbid from v$database; 1125643918

rman>configure controlfile autobackup on;

rman>show all;

2. Next, perform a backup with the control file autobackup enabled:

rman>run

{

backup database;

backup (archivelog all);

}

3. Next, you simulate the missing control files by deleting all the control files.

(The database will need to be shut down to perform this simulated failure.)

command>delete *.ctl

4. Next, start the database in NOMOUNT mode,

command>sqlplus /nolog

sql>connect / as sysdba

sql>startup nomount

5. Next, connect to RMAN and the target database. You will also need to specify the DBID to identify the database you are connecting to, because the control file contains this information and failure causes the control file to be unavailable. The DBID was obtained in step 1 from connecting to the target database before the failure was introduced:

rman>connect target /

rman>set dbid 1125643918; (没有设置dbid,也搞定,不过是在本地运行dbid,如果恢复数据库有多个数据库的备份,可能需要设置dbid,控制文件里存储了dbid信息)

6. Next, restore the control file from backup:

rman>restore controlfile from autobackup;

7. Next, mount the database and begin to recover the database:

rman>alter database mount;

rman>recover database;

8. Finally, open the database with RESETLOGS option for normal operations:

rman>alter database open resetlogs;

重建控制文件 Re-creating a Control File

SQL>sqlplus /nolog

sql>connec / as sysdba

sql>alter database backup controlfile to trace;

command>edit ora101t_ora_3428.trc ---->存储为 backup_controlfile_noreset.txt

command>delete *.ctl

command>sqlplus /nolog

sql>connect / as sysdba

@backup_controlfile_noreset.txt

command>dir *.ctl

进行不完全恢复 Performing an Incomplete Recovery

RMAN Incomplete Recovery

SQL>STARTUP MOUNT

command:set NLS_DATE_FORMAT=DD-MON-YYYY HH24:MI:SS

rman>

run

{

set until time '06-SEP-2004 11:25:00';

restore database;

recover database;

}

rman>alter database open resetlogs;

sql>select * from v$log_history;

sql>startup mount

rman>

run

{

set until sequence 3 thread 1;

restore database;

recover database;

}

rman>alter database open resetlogs;

完成用户管理得不完全恢复

command>set NLS_DATE_FORMAT=DD-MON-YYYY HH24:MI:SS

command>delete USERS01.DBF

command>copy c:\oracle\backup\ora101t\users01.dbf

sql>startup mount

sql>recover database until time '06-SEP-2004 15:15:00';

SQL>ALTER database open resetlogs;

1 . c:\oradata\oracle\ora101t\>copy c:\oracle\backup\ora101t\*.dbf

2 . 查看 控制文件创建脚本

3 . SQL>CONNECT / AS SYSDBA;

SQL>backup_control_reset.txt

4 .sql>recover database until cancel using backup controlfile;

sql>alter database open resetlogs;

使用EM得数据恢复

在RESETLOGS操作之后完成恢复

Performing a Recovery after a RESETLOGS Operation

1. 1. Perform a backup if you do not have a good whole database backup:

RMAN>CONNECT target

rman>run

{

allocate channel c1 type disk;

backup database;

backup (archivelog all);

}

2. Force all the redo log information to archive logs by executing ALTER SYSTEM SWITCH LOGFILE:

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

3. Verify the redo log sequence and thread number in the V$LOG_HISTORY table so that you

can perform incomplete recovery to a redo log sequence:

SQL> select * from v$log_history;

4. Simulate a failure by shutting down the database and deleting the USERS01.DBF:

command>sqlplus /nolog

sql>connect / as sysdba

sql>shutdown immediate

sql>host

command>del users01.dbf

5. Begin the recovery process by starting the database in MOUNT mode:

sql>startup mount

6. Perform an incomplete recovery using the SET UNTIL SEQUENCE clause:

rman>connect target

rman>

run

{

set until sequence 5 thread 1; (恢复到sequence 4)

restore database;

recover database;

}

RMAN> alter database open resetlogs;

7. Simulate database activity by creating a table T1 and forcing this activity to the archived redo logs:

sql>connect test/test

sql>create table t1(c1 char(20));

sql>connect / as sysdba

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

sql>alter system switch logfile;

8. Shut down the database and simulate a database failure by deleting the USERS01.DBF file:

sql>shutdown immediate

C:\oracle\oradata\ora101t\> del USERS01.DBF

9. Start the database in MOUNT mode and then perform a complete recovery in RMAN:

sql>startup mount

command>rman

rman>connect target

rman>

run

{

restore database;

recover database;

}

10. Validate that you have recovered through the last RESETLOGS by verifying that the current V$LOG_HISTORY table shows the log sequence 6 and thread 1 followed by new redo logs files:

sql>select * from v$log_history;

第5章 闪回数据库Understanding the Flashback Database

配置闪回恢复区

sql>alter system set db_recovery_file_dest_size = 6g scope=both;

sql>alter system set db_recovery_file_dest='c:\oracle\flash_recovery_area\ora101t';

sql>alter system set db_recovery_file_dest_size=2000m;

aql>alter system set db_recovery_file_dest='';

使用闪回恢复区Using the Flash Recovery Area

Let's walk through performing an automated disk-based backup and recovery:

1.First, connect to the target database:

command>set ORACLE_SID=ora101rc

command>rman

rman>connect target

2.Next, perform a backup of the target database:

rman>backup as copy database;

3. Finally, query the V$RECOVERY_FILE_DEST to determine if the SPACE_USED column value has increased.

sql>select * from v$recovery_file_dest;

备份闪回恢复区

rman>backup recovery area;

rman>backup recovery files;

配置闪回恢复区

1. Start the database in MOUNT mode:

sql>connect / as sysdba

sql>startup mount

2. Set the DB_FLASHBACK_RETENTION_TARGET parameter to the desired value. This value can be set as an initialization parameter if you're not using the SPFILE. This value is in minutes, which equates to three days:

SQL> alter system set db_flashback_retention_target=4320;

3. Enable the flashback capability:

sql>alter database flashback on;

4. Now the database can be opened for normal use:

sql>alter database open;

在RMAN中使用闪回数据库

(example演示了闪回某个时刻(能闪回的最旧scn),但我在这中间曾经resetlogs也几次,也更改了控制文件,能成吗,以后测试,估计要先恢复控制文件)

1. First, query the V$FLASHBACK_DATABASE_LOG view to retrieve the OLDEST_FLASHBACK_SCN:

command>sqlplus /nolog

sql>connect / as sysdba

sql>select oldest_flashback_scn,oldest_flashback_time from v$flashback_database_log;

2. Next, shut down and start the database in MOUNT mode:

sql>shutdown

sql>startup mount

3. Next, issue the Flashback Database recovery from RMAN:

command>rman

rman>connect target

rman>flashback database to scn=689316;

4. Finally, open the database with the RESETLOGS option,

sql>alter database open resetlogs;

监视闪回数据库

sql>select flashback_on from v$database;

sql>select oldest_flashback_scn,oldest_flashback_time,retention_target,estimated_flashback_size from v$flashback_database_log;

sql>select * from v$flashback_database_stat;

EM使用闪回数据库(略)

第6章 从用户错误恢复Recovering from User Errors

使用闪回丢弃

sql>flashback table t1 to before drop;

了解回收站

sql>select * from t1;

sql>drop table t1;

sql>show recyclebin;

sql>select object_name as recycle_name ,original_name,object_name from recyclebin;

BIN$HbesBq6flungQAB/AQBm7A==$0 TB01

sql>select * from "BIN$0ZVR8xxxxxxxxxxxxxxx"

sql>flashback table "BIN$0Zxxxxxxxxxxxxxxx" to before drop rename to t2;

sql>select * from t2;

sql>show recyclebin;

回收站和空间利用

sql>purge table "BIN$0ZVR8eDEQbK4sxxxxxxxxxxx==$0"

sql>purge tablespace users user test;

The PURGE RECYCLEBIN command is used to purge your own Recycle Bin.

The PURGE DBA_RECYCLEBIN command removes all objects from all users' Recycle Bins.

sql>purge recyclebin;

sql>connect / as sysdba;

sql>purge dba_recyclebin;

闪回丢弃和回收站的局限性(略)

通过EM实现闪回丢弃表

使用闪回版本查询Using Flashback Versions Query

1.

sql>update t1 set salary=18000 where employee='JONES';

sql>commit;

sql>update t1 set salary=21000 where employee='JONES';

sql>commit;

sql>update t1 set salary=25000 where employee='JONES';

sql>commit;

2.显示不同时刻的value

sql>select salary from t1 versions between scn minvalue and maxvalue where employee = 'JONES';

sql>select salary from t1

versions between timestamp

to_timestamp('2004-10-26 11:37:01','YYYY-MM-DD HH:MI:SS') and

to_timestamp('2004-10-26 11:43:01','YYYY-MM-DD HH:MI:SS')

where employee = 'JONES';

sql>select current_scn,scn_to_timestamp(current_scn) from v$database;

There are several new pseudocolumns that help you work with the Flashback Versions

Query:

VERSIONS_STARTTIME

VERSIONS_STARTSCN

VERSIONS_ENDTIME

VERSIONS_ENDSCN

VERSIONS_XID

VERSIONS_OPERATION

SQL>select to_char(versions_starttime,'DD-MON HH:MI') "START DATE",

to_char (versions_endtime, 'DD-MON HH:MI') "END DATE",

versions_xid,

versions_operation,

employee,

salary

from test.t1

versions between scn

minvalue and maxvalue

where employee = 'JONES'

select to_char(versions_starttime,'DD-MON HH:MI:SS') "START DATE",

to_char (versions_endtime, 'DD-MON HH:MI:SS') "END DATE",

versions_xid,

versions_operation,

salary

from t1

versions between scn

minvalue and maxvalue

where employee_id =197;

使用闪回事务查询 Using Flashback Transaction Query

The Flashback Transaction Query is designed to be a diagnostic tool to help identify changes made to the database at the transaction level.

The Flashback Transaction Query is based on undo data 。

Using the FLASHBACK_TRANSACTION_QUERY view can help identify the table and operation that is performed against the table. This view can be large, so it is helpful to use a filter like the transaction identifier, which is in the column XID. The XID value was identified in the previous

The privilege required to use the Flashback Transaction Query is the system privilege FLASHBACK ANY TABLE. (用sysdba管理吧?)

Flashback Versions Query example.

SQL>SELECT table_name,operation,undo_sql from flashback_transaction_query

where xid='020018001F030000';

sql>select table_name,operation,undo_sql from flashback_transaction_query

where start_timestamp >= to_timestamp('2004-10-26 06:45:00','YYYY-MM-DD HH:MI:SS')

and table_owner='TEST';

使用闪回表Using Flashback Table

Flashback Table is a Flashback Technology that allows you to recover a table or set tables to a specific point-in-time without performing an incomplete recovery.

There are two main clauses that are used with the Flashback Table:

The TO SCN clause can recover the Flashback Table to a certain SCN.

The TO TIMESTAMP clause can recover the Flashback Table to a certain point-in-time.

Let's walk through performing a Flashback Table with SCN:

1.Enable ROW MOVEMENT on table T1:

sql>alter table t1 enable row movement;

2.Retrieve the current SCN before you modify the table:

sql>select current_scn from v$database; 771511

3.

sql>update t1 set salary=50000 where employee = 'JONES';

sql>commit;

4.

sql>flashback table t1 to scn 771511;

5.

sql>select * from t1 where employee='JONES';

OK已恢复

Let's walk through performing a Flashback Table with SCN: 测试时间点闪回表

FLASHBACK TABLE employee TO TIMESTAMP TO_TIMESTAMP('2003-04-04 09:30:00', `YYYY-MM-DD HH24:MI:SS');

Triggers are disabled by default during the Flashback Table process.

sql>flashback table table_name to scn 771551 enable triggers;

第7章 处理块损坏Handling BlockCorruption

The detection of block corruption involves using multiple diagnostic logs to identify that corruption has occurred.These methods include monitoring and reading the log files from theoperating system, application, and database level. If audit functions are enabled at the operating system level, these audit logs can be reviewed as well.

In a Windows environment, the Event Viewer shows the contents of the system log.

In a Unix environment, the SYSLOG file contains the system log events. This is a file located in /var/adm/syslog

in many Unix environments.

Application logs can vary for each application that is installed.

Database logs and trace file references are located in the ALERT.LOG file and the associated trace files in the UDUMP

or BDUMP directories.

The following is an example of a trace file created in the UDUMP directory:

Dump file c:\oracle\admin\ora101\udump\ora101_ora_2236.trc

...........

data_block_dump

===============

tsiz: 0x6b8

hsiz: 0x18

pbl: 0x38088044

bdba: 0x01800008

flag=-----------

ntab=1

nrow=5

哪个块怀了 ?5

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

Using Various Methods to Detect and Resolve Corruption

There are four methods for detecting corruption:

The ANALYZE TABLE table_name VALIDATE STRUCTURE command

The Oracle DBVERIFY utility used against the offline data files

The init.ora parameter DB_BLOCK_CHECKING, which checks data and index blocks each time they are created or modified

The DBMS_REPAIR package used against a table, index, or partition

使用ANALYZE命令Using the ANALYZE Utility

The ANALYZE TABLE table_name VALIDATE STRUCTURE command validates the integrity of the structure of the object being analyzed.

sql>analyze table test.t3 validate structure;

ERROR at line 1:

ORA-01498: block check failure - see trace file

This is a good starting point for identifying a database object that is corrupt.

使用DBVERIFY命令

DBVERIFY is an Oracle utility that is used to see whether corruption exists in a particular datafile. This utility is most often used on a backup of the database or when the database is not running

参数:FILE START END BLOCKSIZE LOGFILE FEEDBACK PARAFILE USERID SEGMENT_ID

C:\oracle\product\10.1.0\db_1\database>dbv help=y

command>dbv blocksize=8192 file=users01.dbf

command>dbv blocksize=8192 file=users01.dbf logfile=c:\temp\users01.log

使用DB_BLOCK_CHECKING Using DB_BLOCK_CHECKING

The default is set to FALSE for all non-system tablespaces. The SYSTEM tablespace is enabled by default.

This parameter forces checks for corrupt blocks each time blocks are modified at the tablespace level.

sql>show parameter db_block_checking

使用DBMS_REPAIR程序包

用bbed模拟一个坏块

sql>create table cxy.t3 as select * from tb01;

sql>select segment_name,file_id,block_id,blocks from dba_extents where segment_name = 'T3'; 表T3占用的块

bbed>modify 1000 file 4 block 1941; 书中是5

The general process for resolving physical corruption is to verify that you have corrupt data blocks and to determine their extent. Next, you need to put the list of corrupt data blocks in a holding table so the corrupt blocks can be identified. These blocks are then marked as corrupt

so that they can be skipped over in a query or during normal usage of the table. We will also demonstrate how to fix an index and freelists that could be impacted by physical corruption in a table.

Let's walk through an example of how to detect and mark corrupt blocks:

1. Generate a trace file of the corrupt block, which is automatically created by the ANALYZE command.

sql>connect / as sysdba

sql>analyze table test.t3 validate structure;

ERROR at line 1:

ORA-01498: block check failure - see trace file

2.View the trace file to determine bad block information.

In this example, the bad block is 5. This is indicated by the output line nrow=5, highlighted at the end of this code listing.

_________________________________________________________________________________

Dump file c:\oracle\admin\ora101\udump\ora101_ora_2236.trc

……

flag=-----------

ntab=1

nrow=5

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

3.Create the repair tables to store and retrieve information from running the DBMS_REPAIR package

sql>host repair_tab.sql

-- Create DBMS Repair Table

declare

begin

dbms_repair.admin_tables

(table_name => 'REPAIR_TABLE',

table_type => dbms_repair.repair_table,

action => dbms_repair.create_action,

tablespace => 'USERS');

end;

SQL>

SQL> @repair_tab

PL/SQL procedure successfully completed.

SQL> select owner, object_name, object_type from dba_objects

where object_name like '%REPAIR_TABLE';

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

SYS DBA_REPAIR_TABLE VIEW

SYS REPAIR_TABLE TABLE

4.Check the object, or table T3, to determine whether there is a corrupt block in the table. Even though you know this from the ANALYZE TABLE table_name VALIDATE STRUCTURE command

sql>host edit check_obj.sql

--determine what block is corrupt in a table

set serveroutput on size 100000;

declare

rpr_count int;

begin

rpr_count := 0;

dbms_repair.check_object(

schema_name => 'CXY',

object_name => 'T3',

repair_table_name => 'REPAIR_TABLE',

corrupt_count => rpr_count);

dbms_output.put_line('repair block count: '

||to_char(rpr_count));

end;

SQL> @check_obj.sql

Server Output ON

PL/SQL procedure successfully completed.

repair block count: 1

5.Verify that REPAIR_TABLE contains information about table T3 and the bad block. This query has been broken into three queries for display purposes:

SQL> select object_name, block_id, corrupt_type, marked_corrupt,

corrupt_description, repair_description

from repair_table;

OBJECT_NAME BLOCK_ID CORRUPT_TYPE MARKED_COR

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

T3 3 1 FALSE(我的是true)

SQL> select object_name, corrupt_description

from repair_table;

OBJECT_NAME CORRUPT_DESCRIPTION

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

T3 kdbchk: row locked by non-existent transaction

table=0 slot=0

lockid=44 ktbbhitc=1

SQL> select object_name, repair_description from repair_table;

OBJECT_NAME REPAIR_DESCRIPTION

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

T3 mark block software corrupt

6. A backup of the table should be created before any attempts are made to fix the block or mark the block as corrupt. Therefore, you should attempt to salvage any good data from the corrupted block before marking it as corrupt.

sql>connect test/test

sql>create table cxy.t3_bak as select * from cxy.t3 where dbms_rowid.rowid_block_number(rowid) <> 1941 and dbms_rowid.rowid_to_absolute_fno (rowid,'CXY','T3') = 4;

读取不了,是否因为已经标记为坏块了,为什么我用 bbed修改的块,默认就标记为坏块了

sql>select c1 from t3_bak;

7.Mark block 5 as corrupt, but note that full table scans will still generate an ORA-1578 error.

sql>host edit fixblocks.sql

declare

fix_block_count int;

begin

fix_block_count := 0;

dbms_repair.fix_corrupt_blocks (

schema_name => 'CXY',

object_name => 'T3',

object_type => dbms_repair.table_object,

repair_table_name => 'REPAIR_TABLE',

fix_count => fix_block_count);

dbms_output.put_line('fix blocks count: ' ||

to_char(fix_block_count));

end;

sql>@fix_blocks

sql>select object_name,block_id,marked_corrupt from repair_table;

sql>select * from test.t3;

8.Use the DUMP_ORPHAN_KEYS procedure to dump the index entries that point to the corrupt

rows in the corrupt data blocks.

sql>host more orphan.sql

-- Create the orphan_table

declare

begin

dbms_repair.admin_tables

(table_name => 'ORPHAN_KEY_TABLE',

table_type => dbms_repair.orphan_table,

action => dbms_repair.create_action,

tablespace => 'USERS');

end;

SQL> @orphan_tab

9 Once the ORPHAN_KEY_TABLE is created, you can then dump the orphaned keys into this

table. The following example dumps the data into the ORPHAN_KEY_TABLE:

sql>host more orphan_dump.sql

sql>@orphan_dump

-- Create DBMS Dump orphan/Index entries

declare

orph_count int;

begin

orph_count:= 0;

dbms_repair.dump_orphan_keys (

schema_name => 'CXY',

object_name => 'INDEX1',

object_type => dbms_repair.index_object,

repair_table_name => 'REPAIR_TABLE',

orphan_table_name => 'ORPHAN_KEY_TABLE',

key_count => orph_count);

dbms_output.put_line('orphan-index entries: ' || to_char(orph_count));

end;

SQL>

SQL> @orphan_dump

orphan-index entries: 3

PL/SQL procedure successfully completed

sql>select index_name,count(*) from orphan_key_table group by index_name;

10.Mark the corrupt block as skip enabled.

sql>host more corrupt_block_skip.sql

-- Skips the corrupt blocks in the tables.

declare

begin

dbms_repair.skip_corrupt_blocks (

schema_name => 'CXY',

object_name => 'T3',

object_type => dbms_repair.table_object,

flags => dbms_repair.skip_flag);

end;

/

SQL> @corrupt_block_skip

PL/SQL procedure successfully completed.

11.Rebuild the freelists so that the corrupt block is never added to freelists of blocks.

sql>host more rebuild_freelists.sql

-- Removes the bad block from the freelist of blocks

declare

begin

dbms_repair.rebuild_freelists (

schema_name => 'CXY',

object_name => 'T3',

object_type => dbms_repair.table_object);

end;

/

SQL> @rebuild_freelists

PL/SQL procedure successfully completed.

我的出错:ORA-10614: Operation not allowed on this segment ,查文档,要自动段空间管理,可我已经=是自动段空间管理。

sql>@rebuild_freelists

12.

sql>drop index t3_pk;

sql>create index t3_pk on t3(c1);

块媒介恢复Block Media Recovery

command>rman

rman>connect target

rman>blockrecover datafile 5 block 6;

OK!

第8章Understanding Automatic Database Management

Composed of the Automatic Workload Repository (AWR), server-generated alerts, automated routine maintenance features, and the advisory framework, the components of the CMI simplify database administration through automation and intelligent design.

The AWR collects and processes performance statistics and metrics to be used for problem detection and self-tuning purposes. It also acts as the central storage repository for all elements of the CMI.

Using the Automatic Workload Repository (AWR)

AWR的两个组件:统计信息收集程序和工作负载储存库

The AWR consists of both the statistics collection facility and the workload repository. For simplicity, the general term AWR will be used when referring to the workload repository element.

统计信息收集程序:

The statistics collection facility of AWR resides in memory and is responsible for the collection of dynamic performance statistics.

Don't confuse AWR's statistics collection facility with Oracle's automatic statistics collection feature. AWR collects dynamic performance statistics. The automatic statistics collection feature collects optimizer statistics.

Unlike optimizer statistics, database performance statistics are not utilized by the query optimizer.Instead, they are used to measure the performance of the database over time.

数据库性能统计信息

Database performance statistics fall into one of three categories:

Cumulative values are statistics that accumulate over a period of time through continuous updating.

Metrics Metrics are statistics that represent the rate of change in a cumulative statistics category.

Sampled data Sampled data represents a sampling of the current state of all active sessions. These statistics are collected by the ASH sampler,

Oracle 10g中新的统计信息

Time model statistics, V$SYS_TIME_MODEL view:

Wait statistics, V$SERVICE_STATS view:

Operating system statistics, V$OSSTAT view:

工作负载储存库:

sql>select table_name from dba_tables

where tablespace_name='SYSAUX' and substr(table_name,1,2)='WR' and rownum<=20 order by 1;

启用AWR To enable AWR, the STATISTICS_LEVEL initialization parameter must be set to TYPICAL or ALL.

AWR空间考虑 略

活动会话历史 Active Session History

确定ASH的大小

ASH is actually a first-in, first-out (FIFO) buffer in memory that collects statistics on current session activity

ASH resides in the System Global Area (SGA) and its size is fixed for the lifetime of the instance.

Its size is calculated using the following calculation:The lesser of:

Total number of CPUs × 2MB of memory

5 percent of the Shared Pool size

ASH统计信息 略

ASH视图 V$ACTIVE_SESSION_HISTORY

ASH和AWR Oracle captures some of the ASH statistics to the workload repository for persistent storage

使用AWR

CREATE_SNAPSHOT Creates manual snapshots

DROP_SNAPSHOT_RANGE Drops a range of snapshots at once

CREATE_BASELINE Creates a single baseline

DROP_BASELINE Drops a single baseline

MODIFY_SNAPSHOT_SETTINGS Changes the RETENTION and INTERVAL settings

AWR快照

查看当前AWR设置

sql>select snap_interval,retention from dba_hist_wr_control;

创建快照

begin

DBMS_WORKLOAD_REPOSITORY.CREATE_SNAPSHOT();

end;

修改快照频率

BEGIN

DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(

RETENTION => 14400, INTERVAL => 45);

END;

丢弃快照

Exec DBMS_WORKLOAD_REPOSITORY.DROP_SNAPSHOT_RANGE(LOW_SNAP_ID =>157,HIGH_SNAP_ID =>170);

AWR基线

A baseline is the definition of a pair of snapshots that denote a significant workload period.

使用基线,只能人工进行基线丢弃,并同时删除相关的快照。

AWR baselines also make an excellent tool for application performance and scalability testing.

For example, a payroll application may be baselined with a small amount of test data to begin with. Then, as the test bed is increased, comparisons can be made to determine how well the application is scaling.

查询基线

sql>select * from dba_hist_snapshot;

建立基线

BEGIN

DBMS_WORKLOAD_REPOSITORY.CREATE_BASELINE(START_SNAP_ID =>180,

END_SNAP_ID =>181,

BASELINE_NAME =>'REPORTS1');

END;

/

丢弃基线

Exec DBMS_WORKLOAD_REPOSITORY.DROP_BASELINE('REPORTS1',FALSE);

使用AWR视图

DBA_HIST_ACTIVE_SESS_HISTORY Displays session statistics gathered from ASH.

DBA_HIST_BASELINE Displays information on baselines in the repository.

DBA_HIST_DATABASE_INSTANCE Displays database environment data.

DBA_HIST_SQL_PLAN Displays SQL execution path data.

DBA_HIST_WR_CONTROL Displays current AWR settings.

DBA_HIST_SNAPSHOT Displays information regarding snapshots stored in the AWR.

当需要为给定的时间段建立基线时,可以查询DBA_HIST_SNAPSHOT视图

sql>select snap_id,begin_interval_time,end_interval_time from dba_hist_snapshot order by 1;

使用AWR报告

The report is run through one of two SQL*Plus scripts:

awrrpt.sql, which generates a text file report

awrrpti.sql, which generates an HTML version of the report

These scripts reside in $ORACLE_HOME/rdbms/admin (on Unix systems) or %ORACLE_HOME%\rdbms\admin (on Windows systems).

The scripts will prompt for several options:

SQL> @$ORACLE_HOME/rdbms/admin/awrrpti.sql

Managing Server-Generated Alerts

Threshold alerts leverage the metrics computed by the MMON process to determine potential

performance problems. This is accomplished by comparing the current metrics to preset

threshold levels. If the threshold is exceeded, an alarm is generated.

阀值与非阀值报警

Non-threshold alerts are generated based on specific database events, rather than on threshold settings.

默认报警 oracle提供一组预定义报警

报警过程概述

The MMON process automatically computes metric values from in-memory performance statistics once every minute.

Using Enterprise Manager to Configure Thresholds

查看度量阀值 EM DATABASE CONTROL--MAMAGE METRICS 编辑度量阀值,设置多阀值

通过PL/SQL设置阀值

http://www.stanford.edu/dept/itss/docs/oracle/10g/appdev.101/b10802/d_salt.htm#1000747

TABLE 8 . 7 Comparison Operator Constants

Comparison Operator Description

OPERATOR_CONTAINS Metrics value is contained in the list of threshold values.

OPERATOR_DO_NOT_CHECK Will not apply default threshold to a specified object type.

OPERATOR_EQ Metrics value is equal to the threshold value.

OPERATOR_GE Metrics value is greater than or equal to the threshold value.

OPERATOR_GT Metrics value is greater than the threshold value.

OPERATOR_LE Metrics value is less than or equal to the threshold value.

OPERATOR_LT Metrics value is less than the threshold value.

OPERATOR_NE Metrics value is not equal to the threshold value.

exec DBMS_SERVER_ALERT.SET_THRESHOLD

(9000, --Metric Identifier, METRIC_ID in V$METRICNAME

DBMS_SERVER_ALERT.OPERATOR_GE, --Operator for Warning Threshold

'60', --Warning Threshold

DBMS_SERVER_ALERT.OPERATOR_GE, --Operator for Critical Threshold

'80', --Critical Threshold

1, --Observation Period in Minutes

1, --Occurrences

NULL, --Instance Name (NULL implies ORACLE_SID value)

DBMS_SERVER_ALERT.OBJECT_TYPE_TABLESPACE, ??Object Type

'KITCHEN' --Name of the Object);

BEGIN

DBMS_SERVER_ALERT.SET_THRESHOLD(

METRICS_ID => DBMS_SERVER_ALERT.CPU_TIME_PER_CALL,

WARNING_OPERATOR => DBMS_SERVER_ALERT.OPERATOR_GT,

WARNING_VALUE => '15000',

CRITICAL_OPERATOR => DBMS_SERVER_ALERT.OPERATOR_GT,

CRITICAL_VALUE => '30000',

OBSERVATION_PERIOD => 10,

CONSECUTIVE_OCCURRENCES => 3,

instance_name=>'ORCL',

object_type=>DBMS_SERVER_ALERT.OBJECT_TYPE_SERVICE,

object_name=>'ORCL.COM'

);

END;

catalrt.sql和dbmsslrt.sql在{ORACLE_HOME}/rdbms/admin下 安装缺少的包

查看服务器报警

TABLE 8 . 9 Server Alert Views

View Description

DBA_OUTSTANDING_ALERTS Current alerts awaiting resolution

DBA_ALERT_HISTORY Alerts that have been cleared

DBA_THRESHOLDS Threshold settings defined for the instance

V$ALERT_TYPES Alert type and group information

V$METRIC System-level metric values in memory

V$METRIC_NAME Names, identifiers, and other information about system metrics

V$METRIC_HISTORY Historical system-level metric values in memory

Using Automatic Routine Administration Tasks

使用自动例行管理程序

自动统计信息收集

Though optimizer statistics can be generated manually using the DBMS_STATS package, Oracle can do the job for you automatically through the use of its automatic statistics collection functionality. This is Oracle's recommended method for optimizer statistics collection.

The different types of optimizer statistics include the following:

Dictionary statistics,System statistics,Operating system statistics,User-defined statistics

优化器统计信息Optimizer Statistics

The availability of accurate and up-to-date optimizer statistics significantly increases the chances that the query optimizer will generate an efficient execution plan.

Let's look at a simple example of this.

sql>create table sales as select * from sh.sales where rownum <6;

sql>exec dbms_stats.gather_table_stats(null,'SALES');

sql>insert into sales select * from sh.sales where rownum <= 40000;

sql>commit;

sql>create index sales_idx on sales(cust_id) tablespace index;

sql>explain plan for select * from sales where cust_id = 123;

sql>@utlxpls 或 SQL> @$ORACLE_HOME/rdbms/admin/utlxpls.sql 是full扫描

(我的电脑上需完整路径,是path要修改吗?),

sql>exec dbms_stats.gather_table_stats(null,'SALES');

sql>delete from plan_table;

sql>commit;

sql>explain plan for select * from sales where cust_id = 123; 利用index 访问

sql>@utlxpls 或者 @$ORACLE_HOME/rdbms/admin/utlxpls.sql

字典统计信息

系统统计信息

It also needs to know something about the hardware on which it is running (in other words, CPU and I/O performance).

System statistics can be viewed using either the V$SYSSTAT or V$SESSTAT views, as shown here:

sql>select statistic#,name,value from v$sysstat where rownum <=20;

操作系统统计信息

sql>select * from V$OSSTAT ;

用户定义统计信息

收集优化器统计信息Collecting Optimizer Statistics

When a database is created in Oracle 10g, Oracle creates a job called GATHER_STATS_JOB in the scheduler. This job runs whenever the Maintenance window (defined in the

scheduler) is opened.

If the job is still running when the Maintenance window closes, it will continue to run until completion. By default, the Maintenance window is open weeknights from 10:00 P.M. until

6:00 A.M., and all day long on the weekends.

DBMS_STATS classifies statistics as “stale” when the number of rows in the object

has been modified by more than 10 percent since the last statistics were gathered.

sql>SELECT * FROM DBA_SCHEDULER_JOBS WHERE JOB_NAME='GATHER_STATS_JOB';

BEGIN

DBMS_SCHEDULER.DISABLE('GATHER_STATS_JOB');

END;

管理易变对象统计信息Managing Volatile Object Statistics

Oracle 10g offers several options for dealing with volatile objects. The first, and most obvious, is to simply gather the statistics manually using DBMS_STATS. Beyond that however, there

are two other options.

The first option is to set statistics to NULL.

sql>exec DBMS_STATS.DELETE_TABLE_STATS('BUTERTB','VALATILE_TABLE'); ------ schema ,table_name

sql>exec DBMS_STATS.LOCK_TABLE_STATS('BUTERTB','VOLATILE_TABLE');

The second option is to set statistics to values that are typical for the table and lock them.

To achieve this, gather statistics when the table is at a typical size. When complete, lock the table's statistics, as shown in the preceding example.

监视DML表变化Monitoring DML Table Changes

The DML monitoring feature keeps track of all DML activity (INSERT, UPDATE, DELETE) against a table since statistics were last gathered.

*_TAB_MODIFICATIONS

改变STATISTICS_LEVEL参数

BASIC(不建议)

TYPICAL This setting ensures collection of all major statistics that the database needs for selfmanagement.

ALL This setting results in the gathering of all of the TYPICAL statistics, as well as the operating system and plan execution statistics.

Understanding the Advisory Framework

顾问概况

The Advisory Framework offers a consistent, uniform interface across all advisors allowing them to interact with each other as needed.

自动数据库诊断监视器(ADDM)

ADDM represents the pinnacle of automatic database performance tuning. Without any human interaction, it proactively identifies performance issues and bottlenecks within the database.

段顾问The Segment Advisor

The Segment Advisor analyzes space fragmentation within segments and identifies the segments that are good candidates for the new online shrink operation.

撤销顾问The Undo Advisor

he Undo Advisor helps determine appropriate sizing for Undo tablespaces and helps determine optimal UNDO_RETENTION settings.

sql调整顾问The SQL Tuning Advisor

The SQL Tuning Advisor is used to analyze individual SQL statements and provides recommendations to increase performance.

sql访问顾问The SQL Access Advisor

The SQL Access Advisor is used to analyze a SQL workload (which can consist of one or more SQL statements) and recommend appropriate access structures to improve the performance of the workload. These access structures include, but are not limited to, materialized views and indexes

内存顾问The Memory Advisor

The Memory Advisor helps you to tune the size of the different Oracle memory structures.

SGA Advisor PGA Advisor Buffer Cache Advisor Library Cache Advisor

Oracle strongly encourages the use of ASMM over the use of the Memory Advisor.

调用顾问Invoking Advisors

DBMS_ADVISORY程序包DBMS_ADVISOR Package

To highlight the usage of the DBMS_ADVISOR package, let's look at the high-level steps that would occur during a typical tuning session:

1. CREATE_TASK:

2. SET_TASK_PARAMETER:

3. EXECUTE_TASK:

4. CREATE_TASK_REPORT:

5. MARK_RECOMMENDATION:

6. CREATE_TASK_SCRIPT:

顾问视图Advisor Views

TABLE 8 . 1 5 Advisor Views

View Description

DBA_ADVISOR_DEFINITIONS Advisor properties

DBA_ADVISOR_TASKS Global information about tasks

DBA_ADVISOR_LOG Current status tasks

DBA_ADVISOR_PARAMETERS Task parameters

DBA_ADVISOR_COMMANDS Advisor commands and associated actions

DBA_ADVISOR_OBJECTS Objects referenced by tasks

DBA_ADVISOR_FINDINGS Advisor findings

DBA_ADVISOR_RECOMMENDATIONS Advisor recommendations

DBA_ADVISOR_ACTIONS Actions associated to the recommendations

DBA_ADVISOR_RATIONALE Reasons for the recommendations

DBA_ADVISOR_USAGE Usage for each advisor

自动数据库诊断监视器Automatic Database Diagnostic Monitor (ADDM)

ADDM分析

ADDM is automatically invoked by the MMON process after each AWR snapshot is performed.

DB_TIME

The DB_TIME statistic is the most important of the time model statistics. DB_TIME captures total time spent in database calls for all components. DB_TIME represents an aggregation of CPU and non-idle wait event time.

Because DB_TIME is common across database components, the goal of tuning can be simplified to “reducing DB_TIME.”

Time model statistics at the session level can be viewed using the V$SESS_TIME_MODEL view.

For time model statistics at the system level, use the V$SYS_TIME_MODEL view.

等待事件的变化Wait Event Changes

ADDM also benefits greatly from the changes made in the Wait Event model in Oracle 10g. The first of these changes is the enhanced granularity of the statistics.

The second change to the Wait Event model is the classification of wait events into highlevel classes for ease of identification.

通过EM访问ADDM

SQL调整顾问

自动调整优化器 Automatic Tuning Optimizer (ATO)

In its normal mode, the optimizer accepts a SQL statement and generates a reasonable execution plan based on the available statistics.

When placed in tuning mode, the query optimizer is referred to as the Automatic Tuning Optimizer (ATO), and its emphasis is on generating a superior execution plan

自动SQL调整 Automatic SQL Tuning

The Automatic SQL Tuning functionality analyzes SQL using four distinct methods:

Statistics Analysis

SQL Profiling

Access Path Analysis Access Path Analysis examines whether the addition of one or more new indexes would significantly increase performance for the query.

SQL Structure Analysis SQL Structure Analysis looks at the syntax, semantics, and design of a query and identifies common problems associated with each.

使用SQL调整顾问Using the SQL Tuning Advisor

DBMS_SQLTUNE程序包 DBMS_SQLTUNE Package

Utilizing the DBMS_SQLTUNE package requires the ADVISOR privilege.

The DBMS_SQLTUNE package exposes the API to directly access the SQL Tuning Advisor.

创建任务

DECLARE

task_name varchar2(30);

sql_stmt clob;

BEGIN

sql_stmt := 'select /*+ full(a) use_hash(a) ' ||

' parallel(a,8) full(b) use_hash(b) parallel(b,8) ' ||

' */ a.type, sum(a.amt_paid) ' ||

' from large_table a, large_table2 b ' ||

' where a.key = b.key ' ||

' and state_id = :bnd';

task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK(

sql_text => sql_stmt,

bind_list => sql_binds (anydata.ConvertNumber(32));

user_name => 'BUTERTB',

scope => 'COMPREHENSIVE',

time_limit => 45,

task_name => 'large_table_task',

description => 'Tune state totals query');

dbms_output.put_line('Task ' || task_name ||

' has been created.');

END;

/

执行任务

BEGIN

DBMS_SQLTUNE.EXECUTE_TUNING_TASK( task_name => 'large_table_task');

END;

The status of the executing task can be monitored by querying the DBA_ADVISOR_LOG view or V$SESSION_LONGOPS:

select status from dba_advisor_log where task_name = 'large_table_task';

BEGIN

DBMS_SQLTUNE.INTERRUPT_TUNING_TASK( task_name => 'large_table_task');

END;

If you want to interrupt a tuning task that is currently executing, use the INTERRUPT_

TUNING_TASK procedure:

BEGIN

DBMS_SQLTUNE.INTERRUPT_TUNING_TASK( task_name => 'large_table_task');

END;

Task Results

set long 1000

set longchunksize 1000

set linesize 132

select dbms_sqltune.report_tuning_task('large_table_task') from dual;

管理SQL_Profile

Accepting a SQL Profile

DECLARE

sqlprofile_name varchar2(30);

BEGIN

sqlprofile_name := DBMS_SQLTUNE.ACCEPT_SQL_PROFILE(

task_name => 'large_table_task',

profile_name => 'large_table_profile');

END;

改变SQL PROFILE

begin

DBMS_SQLTUNE.ALTER_SQL_PROFILE(

name => 'large_table_profile',

Atribute_name =>'STATUS',

Value => 'ENABLES');

END;

丢弃SQL PROFILE

BEGIN

DBMS_SQLTUNE.DROP_SQL_PROFILE(

Name => 'large_table_profile');

END;

管理SQL调整集

创建SQL调整集

BEGIN

DBMS_SQLTUNE.CREATE_SQLSET(

Sqlset_name => 'load_proc_set',

Description => 'SQL used in load procedure');

END;

加载SQL调整集

DECLARE

sql_cursor DBMS_SQLTUNE.SQLSET_CURSOR;

begin_snap number := 1; /* beginning snapshot id

end_snap number := 5; /* end snapshot id */

BEGIN

open sql_cursor for

select value(p)

from table (DBMS_SQLTUNE.SELECT_WORKLOAD_REPOSITORY(begin_snap, end_snap) p;

DBMS_SQLTUNE.LOAD_SQLSET(

sqlset_name => 'load_proc_set',

populate_cursor => sql_cursor);

END;

/

SQL调整视图 (略)

通过EM DatabaseControl 使用SQL调整顾问(略)

第9章 理解自动存储管理

Understanding Automatic Storage Management

ASM is a cluster file system that can be used either with stand-alone Oracle instances or with Oracle Real Application Clusters (RAC) to provide a vertically integrated

subsystem encapsulating a file system,

ASM takes the ease of use of OMF and combines it with mirroring and striping features to provide a robust file system and logical volume manager that can even support multiple nodes in an Oracle RAC.

ASM体系介绍

ASM also eases the administrative burden of managing potentially thousands of database files by creating disk groups , which are comprised of disk devices and the files that reside on the disk devices managed as a logical unit.

ASM requires a special type of Oracle instance to provide the interface between a traditional Oracle instance and the file system.

Two new background processes support ASM instances:RBAL and ORBn . RBAL coordinates the disk activity for disk groups on an ASM instance, and ORBn, where n can be from 0

to 9, performs the actual extent movement between disks in the disk groups.

理解ASM实例

创建一个ASM实例

An ASM instance generally has a smaller memory footprint in the range of 60MB to 100MB and is automatically configured when ASM is specified as the database's file storage option when installing the Oracle software and an existing ASM instance does not already exist

While it does have an initialization parameter file and a password file, it has no data dictionary or control file. Therefore, all connections to an ASM instance are via SYS and SYSTEM

using operating system authentication only.

连接到一个ASM实例

Starting Up and Shutting Down an ASM Instance

the STARTUP command defaults to STARTUP MOUNT.

If an ASM instance is already started, you can use this command in an ASM instance to prevent other database instances from connecting to the ASM instance:

SQL> alter system enable restricted session;

Similarly, you can re-enable connections as in this example:

SQL> alter system disable restricted session

Performing a SHUTDOWN command on an ASM instance performs the same SHUTDOWN command on any database instances using the ASM instance;

if you use the SHUTDOWN ABORT command on the ASM instance,all dependent databases immediately perform a SHUTDOWN ABORT because there is no longer an ASM instance available to manage the database's storage.

模拟asm 见blog

If an ASM instance is already started, you can use this command in an ASM instance to prevent other database instances from connecting to the ASM instance:

SQL> alter system enable restricted session; (但我测试了还能数据库关闭了再打开还是能用)

SQL>alter system enable restricted session;

Similarly, you can re-enable connections as in this example:

sql>alter system disable restricted session;

定义ASM初始化参数,INSTANCE_TYPE,DB_UNIQUE_NAME,ASM_POWER_LIMIT,ASM_DISKSTRING,ASM_DISKGROUPS,LARGE_POOL_SIZE

>$ export ORACLE_SID=+ASM

>sqlplus / as sysdba

sql> show parameter INSTANCE_TYPE asm

sql> show parameter DB_UNIQUE_NAME +ASM

sql> show parameter ASM_POWER_LIMIT 1 (controls how fast rebalance operations occur)

SQL>show parameter asm_diskstring

SQL>show parameter ASM_DISKGROUPS

SQL> show parameter LARGE_POOL_SIZE 12m,和常规instance中的大池不同,所有内部的asm包都是从这个区域开始执行。

对ASM动态性能视图进行分类,分别在asm实例和rdbms实例中查看以下视图,其代表不同的含义,有些视图只在asm实例中启用。

V$ASM_DISK select group_number,disk_number,state,name,path from v$asm_disk;

V$ASM_DISKGROUP select group_number,name,state from V$ASM_DISKGROUP;

V$ASM_FILE

V$ASM_OPERATION

V$ASM_TEMPLATE

V$ASM_CLIENT

V$ASM_ALIAS

使用ASM文件名

sql> select file#,name,blocks from v$datafile;

ASM filenames can be one of six different formats.

we'll give an overview of the different formats and the context where they can be used:

As a reference to an existing file

During a single-file creation operation

During a multiple-file creation operation

完整路径的ASM文件名Fully Qualified Names

Fully qualified ASM filenames are used only when referencing an existing file.

+group/dbname/file type/tag.file.incarnation

where

group is the disk group name.

dbname is the database to which the file belongs.

file type is the Oracle file type.

tag is the type-specific information about the specific file type.

The file.incarnation pair ensures uniqueness.

+group/dbname/file type/tag.file.incarnation

数字化的名称Numeric Names Numeric names are used only when referencing an existing ASM file.

+DATA2.256.1

别名

You can use an alias either when referencing an existing object or when creating a single ASM file.

sql> alter diskgroup data2 add directory '+data2/redempt';

sql> alter diskgroup data2 add alias '+data2/redempt/users.dbf' for '+data2/rac0/datafile/users3.256.1';

sql> alter diskgroup data1 add alias '+data1/redempt/users.dbf' for '+DATA1/prod/datafile/users.259.602868565'; 我的电脑

使用模版的别名

You can use an alias with a template only when creating a new ASM file.

sql> create tablespace users4 datafile '+data2/uspare(datafile)';

不完全名称

You can use an incomplete filename format either for single-file or for multiple-file creation operations.

sql>create tablespace users5 datafile '+data1';

使用模板的不完全名

As with incomplete ASM filenames, you can use an incomplete filename with a template for singlefile or multiple-file creation operations.

sql> create tablespace users6 datafile '+data1(tempfile)';

理解ASM类型和模板

Understanding ASM File Types and Templates

individual template characteristics can be changed and apply only to the disk group where they reside.

管理ASM磁盘组

理解磁盘组体系结构

Files in a disk group are striped on the disks using either coarse striping or fine striping. Coarse striping spreads files in units of 1MB each across all disks. Coarse striping is appropriate

for a system with a high degree of concurrent small I/O requests such as an online transaction processing (OLTP) environment. Alternatively, fine striping spreads files in units of 128KB and is appropriate for traditional data warehouse environments or OLTP systems with low concurrency and improves response time for individual I/O requests.

有点费解,以后看看切割的具体原理和好处。。。。。。。。

理解故障组和磁盘组镜像Understanding Failure Groups and Disk Group Mirroring

A failure group is one or more disks within a disk group that share a common resource,unless you specifically assign a disk to a failure group, each disk in a disk group is assigned to its own failure group.

Once the failure groups have been defined, you can define the mirroring for the disk group;the number of failure groups available within a disk group can restrict the type of mirroring

available for the disk group. The following three types of mirroring are available:

External redundancy

Normal redundancy

High redundancy

理解磁盘组动态重平衡

Whenever the configuration of a disk group changes, whether it is adding or removing a failure group or a disk within a failure group, dynamic rebalancing occurs automatically to proportionally reallocate data from other members of the disk group to the new member of the disk group.

—————————————————————————————————————————————————————————————

我是使用裸分区的形式用DBCA设置的ASM磁盘组,和书中很有些不同,路径的表现形式这样的。

sql> select group_number,disk_number,name,failgroup,create_date,path from v$asm_disk

GROUP_NUMBER DISK_NUMBER NAME FAILGROUP CREATE_DATE PATH

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

1 0 VOL1 VOL1 03-OCT-06 ORCL:VOL1

1 1 VOL2 VOL2 03-OCT-06 ORCL:VOL2

2 0 VOL3 VOL3 03-OCT-06 ORCL:VOL3

2 1 VOL4 VOL4 03-OCT-06 ORCL:VOL4

SQL> select group_number,name,type,total_mb,free_mb from v$asm_diskgroup;

GROUP_NUMBER NAME TYPE TOTAL_MB FREE_MB

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

1 DATA1 NORMAL 12284 9878

2 DATA2 NORMAL 12284 12182

SQL> drop diskgroup data2;

SQL> select group_number,disk_number,name,failgroup,create_date,path from v$asm_disk;

GROUP_NUMBER DISK_NUMBER NAME FAILGROUP CREATE_DATE PATH

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

0 0 03-OCT-06 ORCL:VOL3

0 1 03-OCT-06 ORCL:VOL4

1 0 VOL1 VOL1 03-OCT-06 ORCL:VOL1

1 1 VOL2 VOL2 03-OCT-06 ORCL:VOL2

————————————————————————————————————————————————————————

创建和删除磁盘组

sql> select group_number,disk_number,name,failgroup,create_date,path from v$asm_disk;

sql> select group_number,name,type,total_mb,free_mb from v$asm_diskgroup;

sql> create diskgroup data2 high redundancy

failgroup fg1 disk '/dev/raw/raw3' name d2a

failgroup fg2 disk '/dev/raw/raw4' name d2b

failgroup fg3 disk '/dev/raw/raw5' name d2c

failgroup fg4 disk '/dev/raw/raw6' name d2d;

sql> create diskgroup data2 normal redundancy

failgroup fg1 disk 'ORCL:VOL3' name d2a

failgroup fg2 disk 'ORCL:VOL4' name d2b;

Looking at the dynamic performance views, you see the new disk group available in V$ASM_DISKGROUP and the failure groups in V$ASM_DISK:

SQL> select group_number, name, type, total_mb, free_mb from v$asm_diskgroup;

SQL> select group_number, disk_number, name, failgroup, create_date, path from v$asm_disk;

in the following example, the disk /dev/raw/raw4 was previously used as part of a disk group, so you must specify FORCE:

sql>create diskgroup data2 high redundancy

failgroup fg1 disk '/dev/raw/raw3' name d2a

failgroup fg2 disk '/dev/raw/raw4' name d2b force

failgroup fg3 disk '/dev/raw/raw5' name d2c

failgroup fg4 disk '/dev/raw/raw6' name d2d;

sql>drop diskgroup data2;

sql>create diskgroup data2 high redundancy

failgroup fg1 disk '/dev/raw/raw3' name d2a

failgroup fg2 disk '/dev/raw/raw4' name d2b

failgroup fg3 disk '/dev/raw/raw5' name d2c;

sql> select group_number,disk_number,name,failgroup,create_date,path from v$asm_disk;

If the disk group had any database objects other than disk group metadata, you would have to specify INCLUDING CONTENTS in the DROP DISKGROUP command.

修改磁盘组

SQL> alter diskgroup data1 add failgroup d1fg3 disk '/dev/raw/raw6' name d1c;

检查重平衡操作的状态

SQL> select group_number, operation, state, power, actual,sofar, est_work, est_rate, est_minutes from v$asm_operation;

默认power=1,该参数控制重平衡的速度,决定为重平衡操作分配更多的资源,改变power限制 power可以为1-11

SQL> alter diskgroup data1 rebalance power 8;

检查重平衡操作的状态

SQL> select group_number, operation, state, power, actual,sofar, est_work, est_rate, est_minutes from v$asm_operation;

过几分钟再检查

sql>/

SQL> select group_number, disk_number, name,failgroup, create_date, path from v$asm_disk;

sql> select group_number,name,type,total_mb,free_mb from v$asm_diskgroup;

SQL> alter diskgroup data1 add failgroup d1fg3 disk '/dev/raw/*' name d1c;(忽略已经属于磁盘组的磁盘)

使用ALTER DISKGROUP DROP DISK,

SQL> select group_number, operation, state, power, actual,sofar, est_work, est_rate, est_minutes from v$asm_operation;

sql> alter diskgroup data2 drop disk d2d;

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

我的机器执行了删除磁盘,但并没有生效,why

SQL> alter diskgroup data2 drop disk d2a;

SQL> select group_number, disk_number, name,failgroup, create_date, path from v$asm_disk;

GROUP_NUMBER DISK_NUMBER NAME FAILGROUP CREATE_DATE PATH

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

1 0 VOL1 VOL1 03-OCT-06 ORCL:VOL1

1 1 VOL2 VOL2 03-OCT-06 ORCL:VOL2

2 0 D2A FG1 05-OCT-06 ORCL:VOL3

2 1 D2B FG2 05-OCT-06 ORCL:VOL4

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

使用ALTER DISKGROUP UNDROP DISKS

The UNDROP DISKS clause cancels any pending drops of a disk from a disk group. If the drop

operation has completed, you must re-add the disk to the disk group manually and incur the

rebalancing costs associated with adding the disk back to the disk group.

sql>alter diskgroup data2 add failgroup fg4 disk '/dev/raw/raw6' name d2d;

sql>select adg.name DG_NAME,ad.name FG_NAME,path from v$asm_disk ad right outer join v$asm_diskgroup adg

on ad.group_number = adg.group_number

where adg.name = 'DATA2';

sql>alter diskgroup data2 drop disk d2d;

sql>alter diskgroup data2 undrop disks;

sql>select adg.name DG_NAME,ad.name FG_NAME,path from v$asm_disk ad right outer join v$asm_diskgroup adg on ad.group_number = adg.group_number

where adg.name = 'DATA2';

使用ALTER DISKGROUP REBALANCE POWER n 调整重平衡速度

使用ALTER DISKGROUP DROP ADD 只发生一次重平衡操作,而不会发生两次

sql>select adg.name DG_NAME, ad.name FG_NAME, path from v$asm_disk ad right outer join v$asm_diskgroup adg

on ad.group_number = adg.group_number where adg.name = 'DATA2';

SQL> alter diskgroup data2 add failgroup fg4 disk '/dev/raw/raw6' name d2d

drop disk d2c;

SQL> select adg.name DG_NAME, ad.name FG_NAME, path from v$asm_disk ad right outer join v$asm_diskgroup adg

on ad.group_number = adg.group_number where adg.name = 'DATA2';

使用ALTER DISKGROUP DISMOUNT

sql>alter diskgroup data2 dismount;

使用ALTER DISKGROUP MOUNT

SQL>ALTER DISKGROUP data2 MOUNT;

使用ALTER DISKGROUP CHECK ALL

SQL>alter diskgroup data2 check all;

将EM DATABASE CONTROL用于ASM磁盘组

使用RMAN是实现将数据库迁移到ASM,以后测试下

1. Note the filenames of the control files and the online redo log files.

2. Shut down the database using the NORMAL, IMMEDIATE, or TRANSACTIONAL keywords.

3. Back up the database.

4. Edit the SPFILE to use OMF for all file destinations.

5. Edit the SPFILE to remove the CONTROL_FILES parameter.

6. Run the following RMAN script, substituting your specific filenames as needed:

STARTUP NOMOUNT;

RESTORE CONTROLFILE FROM '';

ALTER DATABASE MOUNT;

BACKUP AS COPY DATABASE FORMAT

'+';

SWITCH DATABASE TO COPY;

SQL "ALTER DATABASE RENAME

TO '+' ";

# repeat for all log file members

ALTER DATABASE OPEN RESETLOGS;

7. Delete or archive the old database files.

第10章 Understanding Globalization Support

全球化支持概述

Globalization Support Features

Language support

Territory support

Linguistic sorting and searching

Character sets and semantics

Locale and calendar customization

全球化支持结构 略

支持多语言应用程序 略

When a database is created, two session-independent NLS parameters are specified: the database character set and the national character set

the database character set is a strict superset of the client character set.

解析客户/服务器设置

Any application that connects to the server is considered to be a client, in terms of globalization.

When a client application is run, the client NLS environment is initialized from the environment variable settings.

When the application completes a connection to the database server, the resulting session is initialized with the NLS environment settings of the server.

However, immediately after the session is established, the client implicitly issues an ALTER SESSION statement to synchronize the session NLS environment to match the client's NLS environment.

sql>select sysdate from dual;

sql>alter session set NLS_LANGUAGE=Italian;

sql>select sysdate from dual;

在多语言数据库中使用

Unicode is a universal character set that encompasses all known written languages in the world.

使用NLS参数

Ultimately, Oracle globalization support options are defined by NLS parameter settings. By assigning values to specific NLS parameters, you can control when, where, and how Oracle will

utilize globalization support functionality.

Setting NLS Parameters

NLS parameters can be classified into the following categories:

Language and territory parameters

Date and time parameters

Calendar parameters

Numeric, list, and monetary parameters

Length semantics

Using the NLS_LANG Parameter

NLS_LANG is a client-side environment variable that defines the language, territory, and character set for the client. It is functionally equivalent to setting the NLS_LANGUAGE, NLS_TERRITORY, and NLS_CHARACTERSET parameters individually.

some example:

SQL> ALTER SESSION SET NLS_DATE_FORMAT = MM/DD/YY;

SQL> alter session set NLS_DATE_FORMAT ='"Today''s date is "MM/DD/YYYY';

SQL> alter session set nls_date_language=Italian;

SQL> select to_char(sysdate,'Day:Dd Month YYYY') from dual;

SQL> alter session set nls_timestamp_format='MM/DD/YYYY HH24:MI:SS.FF';

SQL> select startup_time from sys.dba_hist_snapshot where rownum < 3;

SQL> alter session set nls_timestamp_tz_format = 'YYYY/MM/DD HH:MI TZH:TZM';

SQL> select startup_time from sys.dba_hist_snapshot where rownum < 3;

SQL> select next_run_date from sys.dba_scheduler_jobs;

SQL> alter session set NLS_CALENDAR = 'Persian';

SQL> select sysdate from dual;

SQL> alter session set NLS_NUMERIC_CHARACTERS=",.";

SQL> select cust_id, to_char(sum(amount_sold), '9G999G999D99') big_sales from sales

group by cust_id

having sum(amount_sold) > 30000;

SQL> alter session set NLS_CURRENCY = "£";

SQL> select to_char(123.45,'L9G999G999D99') amount

from dual;

SQL> alter session set NLS_CURRENCY = " USD";

SQL> select to_char(123.45,'9G999G999D99L') amount

from dual;

Prioritizing NLS Parameters

NLS parameters can be defined using any of the following methods:

Server initialization parameters

Client environment variables

Using the ALTER SESSION statement

In SQL functions

Default values

Setting Server Initialization Parameters

Environment variables on the client side will govern local client-side NLS operations (operations that don't involve the database). They will also override server-side NLS settings for sessions created from the client.

$ export NLS_LANGUAGE=French

$ sqlplus "/ as sysdba"

Using the ALTER SESSION Statement

Setting NLS parameters using the ALTER SESSION statement also overrides the server-side NLS settings for the current session, as in this example:

SQL> ALTER SESSION set NLS_SORT = FRENCH;

Setting NLS Parameters in SQL Functions

NLS parameters can also be set inside certain SQL functions. Inline NLS parameter settings have the highest priority and will override any other NLS settings.

SQL> select to_char(sysdate, 'DD/MON/YYYY','nls_date_language=Italian') from dual;

SQL> select to_char(sysdate, 'DD/MON/YYYY') from dual;

Prioritization Summary

TABLE 1 0 . 3 NLS Parameter Setting Precedence

Method Priority Scope

Set in SQL functions 1 Current SQL function

Explicit ALTER SESSION statement 2 Current session

Client environment variable (implicit ALTER SESSION statement) 3 Current session

Set by server initialization parameter 4 Instance

Default 5 Instance

Using NLS Views

NLS_SESSION_PARAMETERS

NLS_INSTANCE_PARAMETERS

NLS_DATABASE_PARAMETERS

V$NLS_VALID_VALUES

Using Datetime Datatypes

The data stored using these datatypes are often called datetimes, and you'll learn about the following:

DATE

TIMESTAMP

TIMESTAMP WITH TIME ZONE

TIMESTAMP WITH LOCAL TIME ZONE

Oracle dates consist of seven parts: century, year, month, day, hours, minutes, and seconds (elapsed since midnight). In fact, they are stored internally in the database as seven separate elements.

SQL> create table birthdates (client_id NUMBER,birthdate DATE);

SQL> insert into birthdates values(1, sysdate);

SQL> select to_char(birthdate,'YYYY-MM-DD:HH24:MI:SS') from birthdates;

SQL> select dump(birthdate) from birthdates;

DUMP(BIRTHDATE)

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

Typ=12 Len=7: 120,104,10,22,12,30,45

Oracle stores the century and the year elements using excess 100 notation, which means that it adds 100 to the number before storing it. Also, the hours, minutes, and seconds elements are stored using excess 1 notation.

把上面的结果转换成标准的10进制表示法

DUMP(BIRTHDATE)

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

Typ=12 Len=7: 20,04,10,22,11,29,44

SQL> select to_char(birthdate,'YYYY-MM-DD:HH24:MI:SS') from birthdates;

TO_CHAR(BIRTHDATE,'

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

2004-10-22:11:29:44

DATE datatypes always store both a date and a time. If no time is specified when storing a date,Oracle will use a default time of midnight. This can be problematic if you're not careful,

To resolve this problem, you can use the TRUNC function, as shown here:

SQL> select * from conv_dates where trunc(converted_date) = trunc(sysdate); 除去时间元素

When entering date information into a DATE datatype, you can specify it in several ways:

Literal

SQL> alter session set NLS_DATE_FORMAT = "MM-DD-YYYY";

SQL> insert into birthdates values(2, '12-30-1972');

ANSI date literal

It must be formatted exactly as shown here:DATE 'YYYY-MM-DD'

SQL> insert into birthdates values(3, DATE '1966-08-25');

TO_DATE function (对于转换以字符型存储的日期是很方便的)

SQL> insert into birthdates values(4,to_date('09-29-1993 13:45', 'MM-DD-YYYY HH24:MI');

TIMESTAMP Datatype

By default, the TIMESTAMP datatype stores fractional seconds to six digits of precision. This can be changed, however, by specifying a number between 0 and 9 in parentheses after the

TIMESTAMP keyword.

SQL> create table test_stamp (stamp timestamp(2));

SQL> insert into test_stamp select to_timestamp('09-SEP-2004 17:54.38.92','DD-MON-YYYY HH24:MI:SS:FF') from dual;

SQL> commit;

SQL> select * from test_stamp;

TIMESTAMP WITH TIME ZONE Datatype

SQL> create table stamp_tz (stamp_tz TIMESTAMP(4) WITH TIME ZONE);

TIMESTAMP WITH LOCAL TIME ZONE Datatype

The TIMESTAMP WITH TIME ZONE doesn't actually store time zone information at all.

转换为当地时间再存储

Using Linguistic Sorts and Searches

Binary Sorts

Binary sorts perform a numeric sort based on the encoded value (in the character set) for each character.

Linguistic Sorts

Oracle provides a rich set of linguistic sort definitions that cover most of the languages of the world. However, it also provides the ability to define new definitions or to modify existing definitions. The Oracle Locale Builder, a graphical tool that ships with Oracle 10g, can be used to view, create, and modify sort definitions and other locale definitions.

Using Linguistic Sort Parameters

NLS_SORT

The NLS_SORT parameter defines which type of sorting—binary or linguistic—should be performed for SQL sort operations.

By default, the value for NLS_SORT is the default sort method defined for the language identified in the NLS_LANGUAGE parameter.

SQL> alter session set NLS_SORT = German;

By using the NLS_SORT parameter, you can make the following changes to Oracle's default functionality:

Set the default sort method for all ORDER BY operations.

Set the default sort value for the NLSSORT function.

SQL> show parameters NLS_LANGUAGE

SQL> show parameters NLS_SORT

Remember, the NLS_SORT parameter overrides the default sorting method for ORDER BY operations and for the NLSSORT function, but has no effect on other sort operations, such as

WHERE conditions

To perform a linguistic sort, you call the NLSSORT function. Normally, the function would

be called like this:

SQL> select * from sort_test where nlssort(name, 'NLS_SORT=German_din') > nlssort('einschlie遧ich','NLS_SORT=German_din');

However, because the NLS_SORT parameter defines the default sort for the NLSSORT function,specifying the sort inside the function is unnecessary. The following method works as well:

SQL> select * from sort_test where nlssort(name) > nlssort('einschlie遧ich');

NLS_COMP

The NLS_COMP parameter works in conjunction with the NLS_SORT parameter to make linguistic

sorts easier to use. When the NLS_COMP parameter is set to a value of ANSI, all of the following SQL

operations will default to linguistic sorting (using the language specified in NLS_SORT parameter):

ORDER BY

BETWEEN

CASE WHEN

HAVING

IN/OUT

START WITH

WHERE

11 Managing Resources

Putting the Pieces Together 把最后一部分笔记放在前面了。

In this section, you will be provided step-by-step instructions for the creation of the plans shown in Figures 11.2 and 11.3. First, the pending area will be created. Next, the consumer resource groups will be created. After that, the resource plans will be created. And, finally, the resource plan directives will be created to tie them all together.

OFF_HOURS_PLAN Ratio 10:5:2:1

|

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

| | | |

SYS_GROUP 10 NIGHTLY_PROCESSING_GROUP 5 OLAP_REPORTS_GROUP 2 OTHER_GROUPS 1

word复制这个图 11.3

Creating the Pending Area

SQL> exec dbms_resource_manager.create_pending_area();

Creating the Consumer Resource Groups

SQL> begin

dbms_resource_manager.create_consumer_group(

'OLTP_GROUP','Incoming orders');

end;

SQL>/

SQL> begin

dbms_resource_manager.create_consumer_group(

'DAY_REPORTS_GROUP','DAYTIME REPORTS');

end;

SQL>/

SQL> begin

dbms_resource_manager.create_consumer_group(

'NIGHTLY_PROCESSING_GROUP','BULK LOADS, ETL, ETC.');

end;

SQL>/

SQL> begin

dbms_resource_manager.create_consumer_group(

'OLAP_REPORTS_GROUP','OFF HOURS REPORTS');

end;

SQL>/

Creating the Resource Plans

SQL> begin

dbms_resource_manager.create_plan(

PLAN => 'DAY_PLAN',

COMMENT => 'GOVERNS NORMAL WORKING HOURS ');

end;

SQL> /

SQL> begin

dbms_resource_manager.create_plan(

PLAN => 'OLTP_PLAN',

COMMENT => 'ORDER ENTRY SUB-PLAN');

end;

SQL> /

SQL> begin

dbms_resource_manager.create_plan(

PLAN => 'OFF_HOURS_PLAN',

COMMENT => 'GOVERNS NON-WORKING HOURS',

CPU_MTH => 'RATIO');

end;

SQL> /

Creating the Resource Plan Directives

Creating the OFF_HOURS_PLAN Plan Directives

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OFF_HOURS_PLAN',

GROUP_OR_SUBPLAN => 'SYS_GROUP',

COMMENT => 'CPU ALLOCATION FOR SYS_GROUP',

CPU_P1 => 10);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OFF_HOURS_PLAN',

GROUP_OR_SUBPLAN => 'NIGHTLY_PROCESSING_GROUP',

COMMENT => 'CPU ALLOCATION FOR NIGHTLY JOBS',

CPU_P1 => 5);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OFF_HOURS_PLAN',

GROUP_OR_SUBPLAN => 'OLAP_REPORTS_GROUP',

COMMENT => 'CPU ALLOCATION FOR NIGHTLY REPORTS',

CPU_P1 => 2);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OFF_HOURS_PLAN',

GROUP_OR_SUBPLAN => 'OTHER_GROUPS',

COMMENT => 'CPU ALLOCATION FOR OTHER_GROUPS',

CPU_P1 => 1);

end;

SQL>/

Creating the OLTP_PLAN Plan Directives

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OLTP_PLAN',

GROUP_OR_SUBPLAN => 'OLTP_GROUP',

COMMENT => 'CPU ALLOCATION FOR OLTP USERS',

CPU_P1 => 90);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OLTP_PLAN',

GROUP_OR_SUBPLAN => 'DAY_REPORTS_GROUP',

COMMENT => 'CPU ALLOCATION FOR DAYTIME REPORTING',

CPU_P1 => 10);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'OLTP_PLAN',

GROUP_OR_SUBPLAN => 'OTHER_GROUPS',

COMMENT => 'CPU ALLOCATION FOR OTHER_GROUPS',

CPU_P2 => 100);

end;

SQL>/

Creating the DAY_PLAN Plan Directives

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY_PLAN',

GROUP_OR_SUBPLAN => 'SYS_GROUP',

COMMENT => 'CPU ALLOCATION FOR SYS_GROUP',

CPU_P1 => 100);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY_PLAN',

GROUP_OR_SUBPLAN => 'OLTP_PLAN',

COMMENT => 'CPU ALLOCATION FOR OLTP_PLAN SUB-PLAN',

CPU_P2 => 100);

end;

SQL>/

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY_PLAN',

GROUP_OR_SUBPLAN => 'OTHER_GROUPS',

COMMENT => 'CPU ALLOCATION FOR OTHER_GROUPS',

CPU_P3 => 100);

end;

SQL>/

Validating the Pending Area

SQL> exec dbms_resource_manager.validate_pending_area; 出错,以后修正

Submitting the Pending Area

SQL> exec dbms_resource_manager.submit_pending_area;

Enabling the Resource Plans

Only one resource plan may be enabled at any given time, and the enabled plan can be switched at any time.

There are two methods in which resource plans can be enabled:

Initialization parameter (at instance startup time)

ALTER SYSTEM statement

Initialization Parameter Method

the following code can be added to the init.ora file:

RESOURCE_MANAGER_PLAN = DAY_PLAN;

ALTER SYSTEM Statement Method

ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ‘DAY_PLAN’ [SCOPE = BOTH];

Switching the Enabled Resource Plan

SQL> ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ‘FORCE:OFF_HOURS_PLAN’;

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

Oracle's Database Resource Manager (DRM) circumvents the inefficient operating system management process by giving the Oracle database server more control over resource management decisions.

An Overview of the Database Resource Manager

There are three main elements that comprise the DRM:

Resource consumer groups

Resource plans

Resource plan directives

DRM allocates resources among resource consumer groups based on a resource plan.A resource plan consists of resource plan directives that specify how resources should be distributed among the groups. Resource consumer groups are categories to which user sessions can be assigned. These groups can then be allocated resources through plan directives.

Working with the Pending Area

Before defining or updating any DRM objects, you must first establish a pending area

Creating a Pending Area

SQL> exec dbms_resource_manager.create_pending_area();

Validating Changes

SQL> exec dbms_resource_manager.validate_pending_area;

Submitting the Pending Area

SQL> exec dbms_resource_manager.submit_pending_area;

Clearing the Pending Area

SQL> exec dbms_resource_manager.clear_pending_area;

Resource Consumer Groups

In either situation, users can be assigned to one or more resource consumer groups, although each active session can be assigned to only one resource consumer group at a time.

Managing Resource Consumer Groups

Creating Resource Consumer Groups

TABLE 1 1 . 1 CREATE_CONSUMER_GROUP Parameters

Parameter Description

CONSUMER_GROUP Consumer group name.

COMMENT Any comment (usually a description of the group).

CPU_MTH Method used to schedule CPU resources between sessions in the group. Valid values are:ROUND_ROBIN (the default) ensures fair distribution by using a roundrobin

schedule. RUN_TO_COMPLETION schedules the most active sessions ahead of other sessions.

SQL> begin

dbms_resource_manager.create_consumer_group('developers',

'application developers');

end;

SQL>/

SQL> select consumer_group, cpu_method, comments from dba_rsrc_consumer_groups

where consumer_group = 'DEVELOPERS';

By default, there are four resource consumer groups predefined in the database. They are defined in Table 11.2.

TABLE 1 1 . 2 Predefined Resource Consumer Groups

Group Name Description

DEFAULT_CONSUMER_GROUP Default group for all users/sessions not assigned to an initial consumer

group.

OTHER_GROUPS Catch-all group for users assigned to groups that are not part of the currently active plan. This group cannot be explicitly assigned to users.

SYS_GROUP Used by the Oracle-provided SYSTEM_PLAN plan.

LOW_GROUP Used by the Oracle-provided SYSTEM_PLAN plan.

Updating Resource Consumer Groups

SQL> begin

dbms_resource_manager.update_consumer_group(

CONSUMER_GROUP => 'DEVELOPERS',

NEW_CPU_MTH => 'RUN-TO-COMPLETION');

end;

SQL> /

Deleting a Resource Consumer Group

SQL> begin

dbms_resource_manager.delete_consumer_group('DEVELOPERS');

end;

SQL>/

Assigning User Sessions to Consumer

You still need a method of assigning consumer groups to user sessions. DRM can be configured to automatically assign consumer groups to sessions based on specific session attributes. This process is called consumer group mapping

Creating Consumer Group Mappings

SQL> begin

dbms_resource_manager.set_consumer_group_mapping(ATTRIBUTE => dbms_resource_manager.CLIENT_OS_USER,

VALUE => 'a',CONSUMER_GROUP => 'developers');

end;

SQL>/

Establishing Mapping Priorities

SQL> begin

dbms_resource_manager.SET_CONSUMER_GROUP_MAPPING_PRI(

EXPLICIT => 1,

CLIENT_OS_USER => 2,

CLIENT_MACHINE => 3,

CLIENT_PROGRAM => 4,

ORACLE_USER => 5,

MODULE_NAME => 6,

MODULE_NAME_ACTION => 7,

SERVICE_NAME => 8,

SERVICE_MODULE => 9,

SERVICE_MODULE_ACTION => 10);

end;

SQL>/

Changing Resource Consumer Groups

When a user is granted the switch privilege, they can use the DBMS_SESSION.SWITCH_CURRENT_CONSUMER_GROUP procedure to change the consumer group for their current session.

Switching Groups using DBMS_RESOURCE_MANAGER Procedures

The first procedure, SWITCH_CONSUMER_GROUP_FOR_SESS, explicitly assigns an active session to a new consumer group.

SQL> begin

dbms_resource_manager.switch_consumer_group_for_sess (

SESSION_ID => '56',

SESSION_SERIAL=> '106',

CONSUMER_GROUP => 'LOW_GROUP');

end;

SQL>

The second method of changing the consumer group for an active session is the SWITCH_CONSUMER_GROUP_FOR_USER procedure. This procedure changes all active sessions for a given Oracle username. Here's an example:

SQL> begin

dbms_resource_manager.switch_consumer_group_for_user (

USER => 'test01',

CONSUMER_GROUP => 'LOW_GROUP');

end;

SQL>/

Switching Groups Using DBMS_SESSION

Managing the Switch Privilege

--GRANTEE_NAME,CONSUMER_GROUP,GRANT_OPTION

SQL> begin

dbms_resource_manager_privs.grant_switch_consumer_group(

'PROG_ROLE', 'developers',FALSE);

end;

SQL>/

In this example, the switch privilege is granted to the PROG_ROLE role. Any user granted that role will be able to switch to the DEVELOPERS group, but they cannot grant the privilege to any other users.

SQL>

begin

dbms_resource_manager_privs.revoke_switch_consumer_group('PROG_ROLE', 'developers');

end;

SQL>/

Resource Plans

DRM allocates resources among resource consumer groups based on a resource plan.

Resource plans prioritize resource allocation through the use of levels, with level 1 being the highest priority and level 8 being the lowest.

Resource Plan CPU Allocation Methods

EMPHASIS The allocated amount is treated as a percentage

RATIO The allocated amount is treated as a ratio of the total CPU resources

Creating Simple Resource Plans

They are distinct from complex plans in that they create a resource plan, resource plan directives, and resource consumer groups in one simple procedure

SQL> begin

DBMS_RESOURCE_MANAGER.CREATE_SIMPLE_PLAN(

SIMPLE_PLAN => 'DEPARTMENTS',

CONSUMER_GROUP1 => 'PAYROLL',

GROUP1_CPU => 50,

CONSUMER_GROUP2 => 'SALES',

GROUP2_CPU => 25,

CONSUMER_GROUP3 => 'MARKETING',

GROUP3_CPU => 25);

end;

SQL> /

Final DEPARTMENTS Plan

Level Sys_Group Payroll Sales Marketing Other_Groups

1 100%

2 50% 25% 25%

3 100%

Creating Complex Resource Plans

For complex plans, each of these elements is defined and stored separately.

Creating a plan involves defining the name of the plan, a comment or description regarding the plan, and the methods that the plan will follow when allocating specific resources. Notice

that the plan does not determine which resources it will manage. Those are predefined by Oracle

DBMS_RESOURCE_MANAGER.CREATE_PLAN procedure, whose parameters are described in Table 11.15.

PLAN COMMENT CPU_MTH ......

SQL> begin

dbms_resource_manager.create_plan(

PLAN => 'DAY',

COMMENT => 'CREATED BY TBB');

end;

SQL>/

SQL> select plan, num_plan_directives, cpu_method from dba_rsrc_plans;

Creating Resource Sub-Plans

A sub-plan is a plan. It only becomes a sub-plan if a higher level plan allocates resources to it (through a resource plan directive).

Modifying Resource Plans

exec不能换行?

SQL> exec dbms_resource_manager.update_plan(PLAN => 'DAY',NEW_COMMENT => 'Plan for scheduled work hours');

Deleting Resource Plans

SQL> exec dbms_resource_manager.delete_plan(‘DAY');

Resource Plan Directives

Resource plan directives assign consumer groups to resource plans and define the resource allocations for each. In addition to consumer groups, plan directives can

allocate resources to sub-plans.

Resource allocation methods are predefined by Oracle and, as such, are not modifiable.These represent the various methods available to DRM to allocate resources.

CPU

Active session pool with queuing

Degree of parallelism limit

Automatic consumer group switching

Canceling SQL and terminating sessions

Execution time limit

Undo pool

Idle time limit

Creating Resource Plan Directives

DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE

The following example creates a resource plan directive for the DAY plan, which limits the

parallel degree settings for the DEVELOPERS group:

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'DEVELOPERS DAY PLAN',

GROUP_OR_SUBPLAN => 'DEVELOPERS',

PARALLEL_DEGREE_LIMIT_P1 => '4');

end;

SQL> /

Creating Sub-Plan Directives

For example, to define a sub-plan under the DAY plan, you would set the GROUP_OR_SUBPLAN parameter to the name of the target plan, as follows:

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'DEPARTMENTS SUB-PLAN',

GROUP_OR_SUBPLAN => 'DEPARTMENTS',

CPU_P2=> 50);

end;

SQL> /

Creating Multi-Level Plan Directives

Multi-level plan directives are used to prioritize CPU allocation for consumer groups and subplans.

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'SYSTEM USERS',

GROUP_OR_SUBPLAN => 'SYS_GROUP',

CPU_P1=> 100);

end;

SQL> /

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'DEPARTMENTS SUB-PLAN',

GROUP_OR_SUBPLAN => 'DEPARTMENTS',

CPU_P2=> 50);

end;

SQL> /

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'DEVELOPERS GROUP CPU ALLOCATION',

GROUP_OR_SUBPLAN => 'DEVELOPERS',

CPU_P2=> 50);

end;

SQL> /

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'OTHER_GROUPS CPU ALLOCATION',

GROUP_OR_SUBPLAN => 'OTHER_GROUPS',

CPU_P3=> 100);

end;

SQL> /

Creating Automatic Consumer Group Switching Directives

SWITCH_TIME The SWITCH_TIME parameter sets the maximum execution time (in seconds) allowed for any operation.转换后不会回到原来的群

SWITCH_TIME_IN_CALL 类似SWITCH_TIME ,但违规的会话在转换群中停留的时间至操作结束为止,会话将返回他原来的群

SWITCH_ESTIMATE 预测执行时间,如果超过,就进行消费群转换

the switch group can also be set to the Oracle constants KILL_SESSION or CANCEL_SQL

To create a plan directive that automatically cancels operations that execute for more than

one hour, see the following example:

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'LIMIT DEVELOPERS EXECUTION TIME',

GROUP_OR_SUBPLAN => 'DEVELOPERS',

SWITCH_GROUP => 'CANCEL_SQL',

SWITCH_TIME => 3600);

end;

SQL> /

To create a plan directive that temporarily moves DEVELOPERS sessions to a lower priority group whenever Oracle estimates that an operation will execute for more than 15 minutes, see

this example:

SQL> begin

dbms_resource_manager.create_plan_directive(

PLAN => 'DAY',

COMMENT => 'SWITCH DEVELOPERS TEMPORARILY',

GROUP_OR_SUBPLAN => 'DEVELOPERS',

SWITCH_TIME_IN_CALL => 900,

SWITCH_GROUP => 'LOW_GROUP',

SWITCH_ESTIMATE => TRUE);

end;

SQL> /

Updating Resource Plan Directives

SQL> begin

dbms_resource_manager.update_plan_directive(

PLAN => ‘DAY’,

GROUP_OR_SUBPLAN => ‘DEVELOPERS’,

NEW_SWITCH_ESTIMATE => FALSE);

end;

SQL>/

加前缀NEW_到科修改的参数……

Deleting Resource Plan Directives

SQL> begin

dbms_resource_manager.delete_plan_directive(

PLAN => ‘DAY’,

GROUP_OR_SUBPLAN => ‘DEVELOPERS’);

end;

SQL>/

12 Using the Scheduler to Automate Tasks

Scheduler Overview

Jobs A job instructs the Scheduler to run a specific program at a specific time on a specific date.

Programs A program contains the code (or a reference to the code) that needs to be run to accomplish a task.

Schedules A schedule contains a start date, an optional end date, and a repeat interval.

Windows A window identifies a recurring block of time during which a specific resource plan should be enabled to govern resource allocation for the database.

Job groups A job group is a logical method of classifying jobs with similar characteristics.

Window groups A window group is a logical method of grouping windows.

Scheduler Architecture

The job table, which houses all the active jobs within the database

SQL>select owner, job_name, state,NEXT_RUN_DATE from dba_scheduler_jobs;

The job coordinator, a key Oracle process that ensures that jobs are being run on schedule

Job slaves, processes that carry out the execution of jobs under the guidance of the job coordinator

The architecture in Real Application Cluster (RAC) environments and how it differs only slightly from a stand-alone database environment

Each instance in the cluster will have its own job coordinator.The job coordinators can communicate with one another to share formation.

. Jobs can be defined with a service affinity (they should run on a specific service) as opposed to an instance affinity (they should run on a pecific instance).

Common Administration Tools

The Oracle Scheduler is implemented through a PL/SQL package named DBMS_SCHEDULER

Using the ENABLE Procedure

With the exception of schedules, all Scheduler objects have a common attribute named ENABLED

SQL> begin

dbms_scheduler.enable('BACKUP_JOB');

end;

SQL> begin

dbms_scheduler.enable( 'BACKUP_PROGRAM, BACKUP_JOB, STATS_JOB');

end;

SQL> begin

dbms_scheduler.enable('BACKUP_JOB_GROUP, STATS_JOB, SYS.WINDOW_GROUP_1');

end;

/

When a job group is enabled, all members of that job group will be enabled.

When a window group is enabled, only the window group object is enabled. Windows that are members of the group are not enabled.

When a window or window group is referenced in the ENABLE procedure, it must always be prefixed with the SYS schema name as shown in the preceding example (SYS.WINDOW_GROUP_1).

Using the DISABLE Procedure

DBMS_SCHEDULER.DISABLE

This procedure accepts two parameters: NAME and FORCE.

The FORCE parameter is a Boolean (TRUE or FALSE) value that tells the procedure how to handle the request if dependencies exist. The default value is FALSE.

There are two situations that could be classified as dependencies:

A job object that references a program object is considered to be dependent on that object.

If an instance of an object is currently running (for example, a window is open or a job is running), there may be a dependency issue.

SQL>

begin

dbms_scheduler.disable('BACKUP_JOB');

end;

SQL> begin

dbms_scheduler.disable(

'BACKUP_PROGRAM, BACKUP_JOB, STATS_JOB',TRUE);

end;

SQL> begin

dbms_scheduler.disable(

'BACKUP_JOB_GROUP, STATS_JOB, SYS.WINDOW_GROUP_1');

end;

/

Setting Attributes

Scheduler objects are collections of attributes. To make a change to an object requires setting its attributes

SQL> begin

dbms_scheduler.set_attribute (

name => 'TEST_JOB',

attribute => 'ENABLED',

value => TRUE);

end;

/

SQL> begin

dbms_scheduler.set_attribute_null (

name => 'TEST_SCHEDULE',

attribute => 'END_DATE');

end;

Using Scheduler Jobs

A Scheduler job defines a specific program to be executed, the arguments (or parameters) to be passed to the program, and the schedule defining when the program should be executed.

Creating Jobs

a job combines a program and a schedule for execution of that program.

Jobs are created by using the DBMS_SCHEDULER.CREATE_JOB procedure. The CREATE_JOB procedure is an overloaded procedure.

调度器允许用四种不同的方法创建任务。

The following example creates a job that will run once every year to enact cost of living adjustments for all employees:

SQL> begin

dbms_scheduler.create_job (

job_name => 'cola_job',

job_type => 'PLSQL_BLOCK',

job_action => 'update employee set salary = salary*1.05;',

start_date => '10-OCT-2004 06:00:00 AM',

repeat_interval => 'FREQ=YEARLY',

comments => 'Cost of living adjustment');

end;

/

To verify that the job was created, the DBA|ALL|USER_SCHEDULER_JOBS view can be queried,as shown here:

SQL> select job_name, enabled, run_count from user_scheduler_jobs;

Copying Jobs(默认停用)

SQL> begin

dbms_scheduler.copy_job('COLA_JOB','RAISE_JOB');

end;

/

SQL> select job_name, enabled from user_scheduler_jobs;

Running Jobs

SQL> begin

dbms_scheduler.run_job('COLA_JOB',TRUE); 第2个参数 同步或异步

end;

/

Stopping Jobs

SQL> begin

dbms_scheduler.stop_job(job_name => 'COLA_JOB',

force => TRUE);

end;

/

when a job is stopped using the STOP_JOB procedure, only the most recent transaction is rolled back.

Dropping Jobs

SQL> begin

dbms_scheduler.drop_job(job_name => 'COLA_JOB',

force => TRUE);

end;

Using Job Classes

Job Class Parameters

JOB_CLASS_NAME

RESOURCE_CONSUMER_GROUP

SERVICE

LOGGING_LEVEL

LOG_HISTORY

Creating Job Classes

SQL> begin

dbms_scheduler.create_job_class(

job_class_name => 'LOW_PRIORITY_CLASS',

resource_consumer_group => 'LOW_GROUP',

logging_level => DBMS_SCHEDULER.LOGGING_FULL,

log_history => 60,

comments => 'LOW PRIORITY JOB CLASS');

end;

/

In this example, a job class named LOW_PRIORITY_CLASS was created that will assign all jobs in the group to the LOW_GROUP consumer group.

Dropping Job Classes

SQL> begin

dbms_scheduler.drop_job_class(

'LOW_PRIORITY_CLASS, HIGH_PRIORITY_CLASS');

end;

/

Using Scheduler Programs

A program defines the action that will occur when a job runs. It can be a PL/SQL block, a stored procedure, or an operating system executable.

Program Attributes

PROGRAM_NAME

PROGRAM_TYPE

PROGRAM_ACTION

NUMBER_OF_ARGUMENTS

Creating Programs

SQL> begin

dbms_scheduler.create_program(

program_name => 'STATS_PROGRAM',

program_type => 'STORED_PROCEDURE',

program_action => 'DBMS_STATS.GATHER_SCHEMA_STATS',

number_of_arguments => 1,

comments => 'Gather stats for a schema');

end;

/

参数:the name of the schema

The ARGUMENT_NAME parameter is available, but is completely optional.

SQL> begin

dbms_scheduler.define_program_argument(

program_name => 'STATS_PROGRAM',

argument_position => 1,

argument_type => 'VARCHAR2');

end;

/

Arguments can be dropped from programs as well.

SQL> begin

dbms_scheduler.drop_program_argument(

program_name => 'STATS_PROGRAM',

argument_position => 1,

end;

/

or its name:

SQL> begin

dbms_scheduler.drop_program_argument(

program_name => 'STATS_PROGRAM',

argument_name => 'SCHEMA_NAME',

end;

/

Dropping Programs

Program objects can be dropped through the use of the DBMS_SCHEDULER.DROP_PROGRAM procedure. This procedure removes the procedure entirely from the database. If existing job definitions include the program that you are attempting to drop, the drop will fail. However, if you

set the FORCE parameter to TRUE, the program will be dropped and the referencing jobs will become disabled.

The following example drops the STATS_PROGRAM program and disables any referencing jobs:

SQL> begin

dbms_scheduler.drop_program (

program_name => 'STATS_PROGRAM',

force => TRUE

end;

/

Using Schedules

Schedules define not only when a job will start, but also how often the job will be repeated.

Schedule Attributes

SCHEDULE_NAME

START_DATE

END_DATE

REPEAT_INTERVAL

COMMENTS

Creating Schedules

By default, schedules are created with access to the PUBLIC role.

To create a schedule that repeats every night at 8:00 P.M., use the following example:

SQL> begin

dbms_scheduler.create_schedule(

schedule_name => 'NIGHTLY_8_SCHEDULE',

start_date => SYSTIMESTAMP,

repeat_interval => 'FREQ=DAILY; BYHOUR=20',

comments => 'Runs nightly at 8:00 PM');

end;

/

Setting Repeat Intervals

calendaring syntax 日程语法 书404 英文书551页

TABLE 1 2 . 4 Calendaring Syntax Examples

Goal Expression

Every Monday FREQ=WEEKLY; BYDAY=MON;

Every other Monday FREQ=WEEKLY; BYDAY=MON; INTERVAL=2;

Last day of each month FREQ=MONTHLY; BYMONTHDAY=-1;

Every January 7 FREQ=YEARLY; BYMONTH=JAN; BYMONTHDAY=7;

Second Wednesday of each month FREQ=MONTHLY; BYDAY=2WED;

Every hour FREQ=HOURLY;

Every 4 hours FREQ=HOURLY; INTERVAL=4;

Hourly on the first day of each month FREQ=HOURLY; BYMONTHDAY=1;

15th day of every other month FREQ=MONTHLY; BYMONTHDAY=15; INTERVAL=2

Testing Repeat Intervals

DBMS_SCHEDULER.EVALUATE_CALENDAR_STRING

CALENDAR_STRING

START_DATE

RETURN_DATE_AFTER

NEXT_RUN_DATE

SQL> DECLARE

start_date TIMESTAMP;

return_date_after TIMESTAMP;

next_run_date TIMESTAMP;

BEGIN

start_date := to_timestamp_tz(

'10-OCT-2004 10:00:00','DD-MON-YYYY HH24:MI:SS');

DBMS_SCHEDULER.EVALUATE_CALENDAR_STRING(

'FREQ=MONTHLY; INTERVAL=2; BYMONTHDAY=15',

start_date, null, next_run_date);

DBMS_OUTPUT.PUT_LINE('next_run_date: ' ||

next_run_date);

END;

/

next_run_date: 15-OCT-04 10.00.00.000000 AM

The procedure returns only a single value for NEXT_RUN_DATE, but you may want to see more

than one. If so, you can use the SQL shown here:

SQL> DECLARE

start_date TIMESTAMP;

return_date_after TIMESTAMP;

next_run_date TIMESTAMP;

BEGIN

start_date := to_timestamp_tz('10-OCT-2004 10:00:00','DD-MON-YYYY HH24:MI:SS');

return_date_after := start_date;

FOR i IN 1..10 LOOP

DBMS_SCHEDULER.EVALUATE_CALENDAR_STRING('FREQ=MONTHLY; INTERVAL=2; BYMONTHDAY=15',start_date, return_date_after, next_run_date);

DBMS_OUTPUT.PUT_LINE('next_run_date: ' || next_run_date);

return_date_after := next_run_date;

END LOOP;

END;

Using Scheduler Windows

Unlike most of the other Scheduler objects that you've seen so far, windows are created in the SYS schema.

Creating Windows

The parameters for the CREATE_WINDOW procedure are described here:

WINDOW_NAME

RESOURCE_PLAN

START_DATE

DURATION

SCHEDULE_NAME

REPEAT_INTERVAL

END_DATE

WINDOW_PRIORITY

COMMENTS

To create a window that activates the DAY_PLAN resource plan and uses a schedule named WORK_HOURS_SCHEDULE, see the following example:

SQL> begin

dbms_scheduler.create_window (

window_name => 'WORK_HOURS_WINDOW',

resource_plan => 'DAY_PLAN',

schedule_name => 'WORK_HOURS_SCHEDULE',

duration => INTERVAL '10' HOUR,

window_priority => 'HIGH');

end;

/

PL/SQL procedure successfully completed.

Opening and Closing Windows

There are two distinct ways that a window can be opened. The first is based on the window's schedule. The second is they can be opened manually by using the DBMS_SCHEDULER.OPEN_WINDOW procedure.

When opening a window manually, you can specify a new duration for the window to remain open; otherwise it will remain open for the duration defined when the window was created.

The OPEN_WINDOW procedure opens a window independent of its schedule. The associated resource plan is enabled immediately, and currently executing jobs are subjected to the change in resource plan

SQL> begin

dbms_scheduler.open_window (

window_name => 'WORK_HOURS_WINDOW',

duration => INTERVAL '20' MINUTE,

force => TRUE);

end;

/

This example forces the WORK_HOURS_WINDOW to be opened and any current window to close.

The new window will remain open for a duration of 20 minutes

SQL> begin

dbms_scheduler.close_window (

window_name => 'WORK_HOURS_WINDOW');

end;

/

Window Logging

For example, use the following query to view window log entries:

SQL> select log_id, trunc(log_date) log_date,window_name, operation

from dba_scheduler_window_log;

For each CLOSE operation logged in the DBA_SCHEDULER_WINDOW_LOG view, there will be an associated record in the DBA_SCHEDULER_WINDOW_DETAILS view, as shown here:

SQL> select log_id, trunc(log_date) log_date,window_name, actual_duration

from dba_scheduler_window_details;

Purging Logs

Scheduler job and window logs will be automatically purged based on the setting of the LOG_HISTORY attribute of the Scheduler itself.

SQL> begin

DBMS_SCHEDULER.SET_SCHEDULER_ATTRIBUTE( 'LOG_HISTORY','60');

end;

/

By default, this procedure sets the history retention period for both Scheduler window logs and Scheduler job logs. To set only one, the WHICH_LOG parameter may be included to specify either WINDOW_LOG or JOB_LOG.

Using Scheduler Views

To see information on completed instances of a job, use the example shown here:

SQL> select job_name, status, error# from dba_scheduler_job_run_details

where job_name = 'FAIL_JOB';

To see the current state of all jobs, use the following example:

SQL> select job_name, state from dba_scheduler_jobs;

Scheduler Views Available p412页

TABLE 1 2 . 6 Scheduler Views Available

View Description

*_SCHEDULER_SCHEDULES Shows information on all defined schedules.

*_SCHEDULER_PROGRAMS Shows information on all defined programs.

*_SCHEDULER_PROGRAM_ARGUMENTS Shows all registered program arguments, and the

default values if they exist.

*_SCHEDULER_JOBS Shows all defined jobs, both enabled and disabled.

*_SCHEDULER_GLOBAL_ATTRIBUTE Shows the current values of all Scheduler attributes.

*_SCHEDULER_JOB_ARGUMENTS Shows the arguments for all defined jobs.

*_SCHEDULER_JOB_CLASSES Shows information on all defined job classes.

*_SCHEDULER_WINDOWS Shows information about all defined windows.

*_SCHEDULER_JOB_RUN_DETAILS Shows information about all completed (failed or

successful) job runs.

*_SCHEDULER_WINDOW_GROUPS Shows information about all window groups.

*_SCHEDULER_WINGROUP_MEMBERS Shows the members of all window groups.

*_SCHEDULER_RUNNING_JOBS Shows the state information on all jobs that are

currently being run.

To view windows and their next start dates, the following SQL can be used:

SQL> select window_name, next_start_date from dba_scheduler_windows;

The DBA_SCHEDULER_JOB_LOG view can be used to view log entries for previously executed

jobs, as shown here:

SQL> select log_id, trunc(log_date) log_date, owner, job_name, operation

from dba_scheduler_job_log;

……

You also learned that, in a RAC environment, each instance has its own job coordinator, and

the job coordinators have the ability to communicate with each other to keep information current.

You learned that a RAC environment will still have only one job table that is shared by all

the instances. You also learned that jobs can be assigned to a service, as opposed to an instance,

ensuring that the job can be run by a different node if an instance is down.

....

13 Monitoring and Managing Storage

Monitoring Tablespace Storage

Oracle 10g manages the disk space in two ways: reactively and proactively.

In a truly proactive manner, Oracle 10g collects statistics on space usage in the Automatic Workload Repository (AWR) at 30-minute intervals to assist you with tablespace and segment

growth trend analysis and capacity planning.

Space Usage Monitoring

The background process MMON checks for tablespace space problems every 10 minutes; alerts are triggered both when a threshold is exceeded and once again when the space usage for

a tablespace falls back below the threshold.

Dictionary-managed tablespaces do not support server-generated alerts

Editing Thresholds with Enterprise Manager Database Control

如果超过空间阀值,MMON进程将会以下列三方式之一通知DBA危急的表空间问题。

via the EM Database Control Home tab, via an e-mail message sent to the e-mail address configured when the database was created, or using the script in the Response

Action column, if one was specified,

Using DBMS_SERVER_ALERT

SET_THRESHOLD

GET_THRESHOLD

EXPAND_MESSAGE

SQL> begin

dbms_server_alert.set_threshold(

dbms_server_alert.tablespace_pct_full,

dbms_server_alert.operator_ge, 90,

dbms_server_alert.operator_ge, 99,

1, 1, null,

dbms_server_alert.object_type_tablespace,'USERS');

end;

以下出错,已发帖子,why?要看看开发知识。

variable warn_oper number

variable warn_value varchar2

variable crit_oper number

variable crit_value varchar2

variable obs_per number

variable cons_oc number

begin

dbms_server_alert.get_threshold(

dbms_server_alert.TABLESPACE_PCT_FULL,

:warn_oper, :warn_value, :crit_oper, :crit_value,:obs_per, :cons_oc, null,

dbms_server_alert.object_type_tablespace,'USERS');

end;

print warn_oper

print warn_value

print crit_oper

print crit_value

print obs_per

print cons_oc

Using Segment Management Tools

Segment Shrink

An Overview of Segment Shrink

Segment shrink compresses the data blocks in a table or index and optionally moves the HWM down, making the unused space available for other segments in the tablespace.

Before Oracle 10g, the HWM could be moved down only if the segment was moved or truncated. While online table redefinition or Create Table As Select (CTAS) operations can provide

similar results to segment shrink, those methods must temporarily provide double the amount of space occupied by the table.

Segment Shrink Restrictions and Considerations

During a segment shrink operation, the ROWID may change for a row when it moves between blocks. Therefore, segments that rely on ROWIDs being constant, such as an application that maintains ROWIDs as pointers in another table, cannot be shrunk. In any case, ROW MOVEMENT must be enabled for table segments that are candidates for shrink operations.

Performing Segment Shrink

SQL Commands and Segment Shrink

SQL> alter table hr.employees enable row movement;

SQL> alter table hr.employees shrink space;

将操作分成两个命令可能好些

SQL> alter table hr.employees shrink space compact;

……using the COMPACT clause to compress the rows without moving the HWM,

At a later time, when the database is not as busy, you can complete the rest of the operation by omitting the COMPACT clause.

SQL> alter table hr.employees shrink space;

When CASCADE is specified, all dependent objects, such as indexes, are also shrunk.

SQL> alter table hr.employees shrink space cascade;

EM Database Control and Segment Shrink

Growth Trend Report

Segment Resource Estimation

Segment Advisor within PL/SQL

Index Space Monitoring

Monitoring Index Space Usage

sql>connect hr/cxxx@orcl

SQL> analyze index emp_name_ix validate structure;

SQL> select pct_used from index_stats where name = 'EMP_NAME_IX';

Over time, if the PCT_USED value starts to decline, you can either rebuild the index, or drop and re-create the index.

Rebuilding versus Coalescing Indexes

SQL> alter index emp_name_ix coalesce;

Rebuilding versus Coalescing an Index

Rebuilding an Index Coalescing an Index

Can move index to another tablespace Cannot move index to another tablespace

Requires double the amount of disk space if Does not require additional disk space

performed online

Creates a new tree and adjusts tree height if Coalesces index leaf blocks within each

necessary branch

If you decide to rebuild the index, you can do it online, as in this example:

SQL> alter index emp_name_ix rebuild online;

The index is available nearly 100 percent of the time that the rebuild operation is in progress, other than a very short amount of time at the end of the rebuild when

the old index is swapped with the new copy of the index.

Identifying Unused Indexes

SQL> alter index hr.emp_name_ix monitoring usage;

Next, check V$OBJECT_USAGE to make sure the index is being monitored:

SQL> select index_name, table_name, monitoring,used, start_monitoring from v$object_usage where index_name = 'EMP_NAME_IX';

INDEX_NAME TABLE_NAME MON USE START_MONITORING

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

EMP_NAME_IX EMPLOYEES YES NO 06/02/2004 08:57:44

SQL> select employee_id from employees where last_name = 'King';

INDEX_NAME TABLE_NAME MON USE END_MONITORING

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

EMP_NAME_IX EMPLOYEES NO YES 06/02/2004 17:00:40

Understanding Special Table Types

Index-Organized Tables

An Overview of Index-Organized Tables

You can store index and table data together in an IOT. IOTs are suitable for tables in which the data access is mostly through its primary key, such as lookup tables.

An IOT is a b-tree index,much like a traditional stand-alone index. However, instead of storing the ROWID of the table where the row belongs, the entire row is stored as part of the index.

Creating Index-Organized Tables

create table sales_summary_by_date_division

(sales_date date,

division_id number,

total_sales number(20,2),

constraint ssum_dt_div_pk primary key

(sales_date, division_id))

organization index

tablespace users;

IOT Row Overflow

To further improve the performance benefits provided by an IOT, you can create an IOT overflow area. If an IOT row’s data exceeds the threshold of available space in a block, the row’s

data will be dynamically and automatically moved to the overflow area.

create table sales_summary_by_date_division

(sales_date date,

division_id number,

total_sales number(20,2),

constraint ssum_dt_div_pk primary key

(sales_date, division_id))

organization index

tablespace users

pctthreshold 25

overflow tablespace users;

IOT Mapping Tables

sybex书中概念严重有问题,以下来自concepts

A mapping table is required for creating bitmap indexes on an index-organized table. In both heap-organized and index-organized base tables, a bitmap index is accessed

using a search key. If the key is found, the bitmap entry is converted to a physical rowid. In the case of heap-organized tables, this physical rowid is then used to access

the base table. However, in the case of index-organized tables, the physical rowid is then used to access the mapping table. The access to the mapping table yields a logical

rowid. This logical rowid is used to access the index-organized table.

以下代码创建了IOT表,有映射

create table sales_summary_by_date_division

(sales_date date,

division_id number,

total_sales number(20,2),

constraint ssum_dt_div_pk primary key

(sales_date, division_id))

organization index

tablespace users

pctthreshold 25

overflow tablespace users

mapping table;

Data Dictionary Views for IOTs

DBA_INDEXES (iot表既是表也是索引)

SQL> select index_name, index_type, tablespace_name from dba_indexes

where table_name = 'SALES_SUMMARY_BY_DATE_DIVISION';

DBA_TABLES

提供iot自身的信息,映射表和相关的溢出段。

SQL> select table_name, iot_name, iot_type, tablespace_name

from dba_tables

where table_name = 'SALES_SUMMARY_BY_DATE_DIVISION'

or iot_name = 'SALES_SUMMARY_BY_DATE_DIVISION';

DBA_SEGMENTS

看看iot相关段的信息可以先从DBA_TABLES中得知段名

SQL> select segment_name, segment_type, tablespace_name

from dba_segments

where segment_name LIKE '%_IOT_%' or

segment_name = 'SSUM_DT_DIV_PK';

.....and owner='HR' 增加约束

Clustered Tables

A cluster consists of a group of two or more tables that share the same data blocks.

Creating a clustered table requires three steps:

1. Create the cluster definition.

2. Create the index on the cluster. (This step is skipped for hash clusters.)

3. Create tables within the cluster.

Cluster Types

Clusters can be divided into two broad categories: index clusters and hash clusters.

Index clusters use a traditional b-tree index to find rows in the cluster, and hash clusters use a hashing function to determine the physical location where a given row is stored.

Index Clusters

Consider an index cluster in these situations:

The tables in the cluster are always queried together and only infrequently on their own.

The tables have little or no insert, update, or delete activity performed on them after the initial

load of the cluster.

The child tables have roughly equal numbers of rows for each parent key in the parent

table.

The following example shows the SQL commands necessary to create a cluster called ORD_ITEM, an index on the cluster called ORD_ITEM_IDX, and tables ORD and ITEM in the cluster:

SQL> create cluster ord_item

(ord_number number) size 500

tablespace app_data;

The parameter SIZE specifies how many cluster keys you expect to have per Oracle block

SQL> create index ord_item_idx

on cluster ord_item

tablespace app_idx;

SQL> create table ord

(ord_number number,

cust_last_name varchar2(40),

cust_first_name varchar2(30),

ord_date date,

ord_total number(15,2))

cluster ord_item (ord_number);

SQL> create table item

(item_id number,

ord_number number,

catalog_number number,

item_price number(7,2))

cluster ord_item (ord_number);

Hash Clusters

Hash clusters work best for queries with equivalence operators, as in this example:

select cust_last_name from ord where ord_number = 681107;

Here are the attributes of a table that make it suitable for use in a hash cluster:

The tables in the cluster have a relatively uniform distribution of values in the indexed column.

The tables have little or no insert, update, or delete activity performed on them after the initial

load of the cluster.

The tables in the cluster have a predictable number of values in the indexed column.

The queries against the clustered table almost exclusively use an equality operator to

retrieve the desired row.

create cluster ord_item2

(ord_number number(6,0)) size 500

hash is ord_number hashkeys 100000

tablespace users;

Sorted Hash Clusters

In heap-organized tables and traditional hash clusters, the order in which rows are returned is not under user control and depends on internal algorithms and the relative

physical location of data blocks on disk. For each hash cluster key, Oracle maintains a list of rows sorted by one or more sort columns.

创建

The first step is to create a single table sorted hash cluster, as follows:

create cluster order_cluster

(customer_number number,

order_timestamp timestamp sort)

hashkeys 1000

single table hash is customer_number

size 500;

The next step is to create the order table itself:

create table orders

(cust_number number,

order_date timestamp,

order_number number,

spec_instr varchar2(1000))

cluster order_cluster(cust_number, order_date);

Next, add a few orders with the following INSERT statements.

insert into orders values(3045,timestamp'2004-05-05 15:04:14',405584,'Reorder from last month');

insert into orders values(1958,timestamp'2004-05-05 15:05:01',348857,'New customer');

insert into orders values(3045,timestamp'2004-05-04 9:26:59',938477,'GGT Promotion');

insert into orders values(3045,timestamp'2004-05-07 12:33:23',703749,'');

insert into orders values(3045,timestamp'2004-05-02 19:47:09',389233,'Needs order in time for Mothers Day');

SQL> select cust_number,

to_char(order_date,'yyyy-mm-dd hh:mi pm')

order_date,

order_number, spec_instr

from orders where cust_number = 3045;

Execution Plan

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

0 SELECT STATEMENT Optimizer=ALL_ROWS

(Cost=0 Card=4 Bytes=2164)

1 0 TABLE ACCESS (HASH) OF 'ORDERS'

(CLUSTER (HASH))

以下如果用>= 将需要order by 字句。

SQL> select cust_number,

to_char(order_date,'yyyy-mm-dd hh:mi pm')

order_date,

order_number, spec_instr

from orders where cust_number >= 3045;

其他空间管理工具略。

Leveraging Resumable Space Allocation

Using Resumable Space Allocation

ALTER SESSION ENABLE RESUMABLE [TIMEOUT timeout] [NAME name];

the user must be granted the RESUMABLE system privilege

SQL> alter session enable resumable timeout 600 name 'Short Timeout';

SQL> alter session disable resumable;

DBMS_RESUMABLE Package

The procedures within DBMS_RESUMABLE are as follows:

ABORT .

GET_SESSION_TIMEOUT

GET_TIMEOUT

SET_SESSION_TIMEOUT

SET_TIMEOUT

SPACE_ERROR_INFO

SQL> select dbms_resumable.get_timeout() from dual;

SQL> exec dbms_resumable.set_timeout(1200);

SQL> select dbms_resumable.get_timeout() from dual;

Using the AFTER SUSPEND System Event

A system event called AFTER SUSPEND, first introduced in Oracle 9i, is triggered at the database or schema level when a correctable Resumable Space Allocation error occurs.

CREATE OR REPLACE TRIGGER resumable_default_timeout

AFTER SUSPEND ON DATABASE

BEGIN

/* set timeout to 8 hours */

DBMS_RESUMABLE.SET_TIMEOUT(28800);

/* prepare e-mail to DBA on call */

. . .

UTL_MAIL.SEND (. . .);

END;

Resumable Space Allocation Data Dictionary Views

The data dictionary views DBA_RESUMABLE and USER_RESUMABLE display the set of Resumable Space Allocation statements in the system.

SQL> select user_id, session_id, name, status,

timeout, sql_text

from dba_resumable;

14 Securing the Oracle Listener, Diagnostic Sources, and Memory

Securing the Oracle Listener

An Overview of the TNS Listener

The listener is not limited to database connections, however. It can also be used to access executable programs on the database server.

Managing the Listener Remotely(安全隐患,需受到合适的保护)

Remote management can be accomplished by simply following these steps:

1.Install Oracle software (either client or server) on a remote machine. The machine needs to have Oracle Net Services connectivity, as well as the

lsnrctl executable.

2.On the remote machine, configure the listener.ora file so that it can resolve to the address of the database server.

REMOTE_LISTENER =

ADDRESS_LIST =

(ADDRESS =

(PROTOCOL = TCP)

(HOST =192.168.1.200)

(PORT = 1521)

)

)

3.Start the lsnrctl program and specify the alias defined in step 2, as shown here:

lsnrctl remote_listener

Setting the Listener Password

Setting the password for the listener can be accomplished using several different methods.

The first method is to manually edit the listener.ora file and add the following line:

PASSWORDS_LISTENER = shazam

lsnrctl>reload

second method of setting the listener password is to use the CHANGE_PASSWORD command from the lsnrctl prompt:

LSNRCTL>change_password

LSNRCTL> set password

LSNRCTL> save_config

上面的方法无论输入什么密码都可以管理,估计是操作系统验证惹得祸

The third method of setting the listener password is to use one of Oracle’s graphical tools such as Net Manager (netmgr),Network Creation Assistant (netca), or the Oracle Enterprise

Manager (EM) Database Control application.

Controlling Database Access

DMZ:?

by implementing valid node checking, only requests coming from the application servers would be accepted, and all others would be denied.

netmgr GUI下可更改,书中是更改sqlnet.ora文件,果然外部机器登陆不上。

Using Listener Logging

netmgr可启用 ,或者用下面的方法

LSNRCTL> set log_directory /oralogs

LSNRCTL> set log_file listener_lnx1.log

LSNRCTL> set log_status on

Enabling Listener Logging Using EM Database Control

Removing Unneeded External Procedure Services

The listener can do more than just listen for database requests. It can also be used to run binary executable programs on the database server and to return the output back to the caller. This functionality is referred to as external procedure support.

By default, Oracle creates a service for external procedures in the listener. For the majority of users, this service is never used. Therefore, the service should be removed from the listener.

Manually Removing External Procedure Services

listener.ora Network Configuration File:

/apps/oracle/oracle10gR1/network/admin/listener.ora

# Generated by Oracle configuration tools.

SID_LIST_LISTENER =

(SID_LIST =

(SID_DESC =

(SID_NAME = PLSExtProc)

(ORACLE_HOME = /apps/oracle/oracle10gR1)

(PROGRAM = extproc)

)

(SID_DESC =

(GLOBAL_DBNAME = lnx1)

(ORACLE_HOME = /apps/oracle/oracle10g)

(SID_NAME = lnx1)

)

)

LISTENER =

(DESCRIPTION_LIST =

(DESCRIPTION =

(ADDRESS_LIST =

(ADDRESS = (PROTOCOL = ICP)(KEY = EXTPROC))

)

(ADDRESS_LIST =

(ADDRESS = (PROTOCOL = TCP)(HOST =lnx1)

(PORT = 1521))

)

)

)

改变之后

SID_LIST_LISTENER =

(SID_LIST =

(SID_DESC =

(GLOBAL_DBNAME = lnx1)

(ORACLE_HOME = /apps/oracle/oracle10g)

(SID_NAME = lnx1)

)

)

LISTENER =

(DESCRIPTION_LIST =

(DESCRIPTION =

(ADDRESS_LIST =

(ADDRESS = (PROTOCOL = TCP)(HOST =lnx1)

(PORT = 1521))

)

)

)

Removing External Procedure Services Using EM Database Control

Creating a Separate Listener for External Procedures

可以单独设置一个严格处理外部过程请求的监听器。这个监听器由一个具有非常局限的操作系统权限的用户来执行或限制从哪个库执行过程。

Executing the Listener with a Restricted Account

执行该新监听器的帐号具有读LISTENER.ORA的权限。其他权限不需要了。

Limiting the Available Libraries

By default, the extproc agent can execute procedures from any DLL or shared object library stored in the following locations:

$ORACLE_HOME/lib directory in Unix

%ORACLE_HOME%\bin directory in Windows

但是可以限制监听器只访问LISTENER.ORA文件中明显指定的库。

1,编辑文件创建新的listener.ora略

2,用oem创建 更直观。测试之

Using the ADMIN_RESTRICTIONS Parameter

禁止图形下执行set,故只有人工编辑,fuck。不熟悉

ADMIN_RESTRICTIONS = on

Securing the Listener Directory

listenr.ora,sqlnet.ora 文件的目录只有管理级帐户可以读写。

Applying Oracle Listener Patches

Blocking SQL*NET Traffic on Firewalls

Diagnostic Sources

The alert log is an excellent source of diagnostic data and is generally considered the first place to check when an error occurs.

看alert文件 ,oem看,或者利用外部表特性查询。

Using Server-Generated Alerts

Using Oracle Trace Files

Background processes use this format: sid_process_name_process_id.trc

User processes use this format: sid_ora_process_id.trc

The TRACEFILE_IDENTIFIER parameter allows you specify a text string that will be appended to the names of user session trace files.

ALTER SESSION SET SQLTRACE = TRUE

ALTER SESSION SET TIMED_STATISTICS = TRUE

ALTER SESSION SET TRACEFILE_IDENTIFIER = ‘TIM’

Automatic Memory Management

Oracle Memory Usage

Within each of these structures, Oracle divides available memory into smaller structures known as pools, each designated to satisfy a particular class of memory allocation request.

An Overview of the SGA

Database Buffer Cache

Memory in the database buffer cache is tracked by two internal lists: the write list and the least recently used (LRU) list.

The LRU list is a FIFO

The exception to this rule is when a full table scan operation is performed. Blocks retrieved from a full table scan are added to the least recently used end of the LRU list, so they will be aged out quickly.

you can add the CACHE clause to the table (either via ALTER TABLE or in the CREATE TABLE statements) to circumvent this behavior. You can also choose to pin the table in memory.

Shared Pool

The shared pool contains the library cache and the data dictionary cache, as well as buffers for parallel execution messages and other control structures.

Library Cache

When a SQL statement is parsed, the resultant parse tree and execution plan are stored (along with the statement itself) in a shared SQL area.

Data Dictionary Cache

Redo Log Buffer

Java Pool

Large Pool

Streams Pool

Fixed SGA

An Overview of the PGA

A Program Global Area (PGA) stores data and control information for a single server process. Therefore, every session and background process has an associated PGA.

An Overview of Automatic Memory Management

ASMM divides the SGA memory pools into two groups: automatically sized components and manually sized components.

从参数中的非零值表示最小内存分配,

人工设置大小的组成部分:

These components are

Streams pool

Keep buffer cache

Recycle buffer cache

Other caches

These parameters include

DB_KEEP_CACHE_SIZE

DB_RECYCLE_CACHE_SIZE

DB_nK_CACHE_SIZE (where n = 2, 4, 8, 16, or 32)

STREAMS_POOL_SIZE

Using APMM

APMM functionality is implemented through the use of the PGA_AGGREGATE_TARGET initialization parameter.

Historically, PGA memory allocation has been done through the use of the following initialization parameters:

SORT_AREA_SIZE

HASH_AREA_SIZE

BITMAP_MERGE_AREA_SIZE

CREATE_BITMAP_AREA_SIZE

以上参数与WORKAREA_SIZE_POLICY 结合使用。

如果WORKAREA_SIZE_POLICY 为AUTO,忽略以上内存参数,

如果WORKAREA_SIZE_POLICY 为MANUAL ,使用以上内存参数。

Implementing APMM

PGA_AGGREGATE_TARGET=2G

SQL> alter system set PGA_AGGREGATE_TARGET = 2G;

Implementing APMM Through EM Database Control

%d

Specifies the name of the database.

%f

Specifies the absolute file number.

%h

Specifies the archived redo log thread number.

%I

Specifies the DBID.

%M

Specifies the month in the Gregorian calendar in format MM.

%N

Specifies the tablespace name.

%n

Specifies the name of the database, padded on the right with x characters to a total length of eight characters. For example, if the prod1 is the database name, then the padded name is prod1xxx.

%p

Specifies the piece number within the backup set. This value starts at 1 for each backup set and is incremented by 1 as each backup piece is created.

Note: If you specify PROXY, then the %p variable must be included in the FORMAT string either explicitly or implicitly within %U.

%s

Specifies the backup set number. This number is a counter in the control file that is incremented for each backup set. The counter value starts at 1 and is unique for the lifetime of the control file. If you restore a backup control file, then duplicate values can result. Also, CREATE CONTROLFILE initializes the counter back to 1.

%t

Specifies the backup set time stamp, which is a 4-byte value derived as the number of seconds elapsed since a fixed reference time. The combination of %s and %t can be used to form a unique name for the backup set.

%T

Specifies the year, month, and day in the Gregorian calendar in this format: YYYYMMDD.

%u

Specifies an 8-character name constituted by compressed representations of the backup set or image copy number and the time the backup set or image copy was created.

%r resetlogs ID that ensures unique names are constructed for the archived log files across multiple incarnations of the database

10g RMAN FORMAT 选项的格式规范

%d 规定数据库的名字

%D 规定格里高里日历表示的当前月日

%F 组合数据库标识符(DBID)、日、月、年和序列号为一个独特的、可重复生成的名字

%n 规定数据库名,右端用n个字符填补,总长度8个字符

%p 规定备份集的块号

%s 备份集号

%t 备份集时间戳

%T 规定格里高里日历表示的年、月、日

%u 规定8个字符的名字,该名字使通过备份集的压缩表示或图象副本号而生成

%U 规定系统生成的唯一文件名(默认)

疑问:

select recid,name,thread#,sequence# from v$archived_log

【oracle】配置恢复管理器Configuring Recovery Manager相关推荐

  1. oracle的恢复管理器概述与配置(600大神讲课)

    备份恢复: 备份:把有效的文件copy出来 1. 使用RMAN进行恢复 Data files------数据损失(data files数据丢失) 2 Control files 数据库的名字,数据文件 ...

  2. Oracle 11g 中恢复管理器RMAN介绍

    这是我平时摘录的笔记,从管理艺术那本书上摘录出来的,放到这里 RMAN 可在数据库服务器的帮助下从数据库内备份数据文件,可构造数据文件映像副本.控制文件和控制文件映像.对当日志 SPFILE 和RMA ...

  3. 戴尔服务器系统备份还原工具,戴尔备份和恢复管理器官方版

    dell备份和恢复管理器中国版,这款是目前来说非常好用的数据恢复软件,只针对于戴尔电脑的,能够在最安全的环境下,自动快速的进行数据的备份与恢复,从而解决更多的难题. dell备份和恢复管理器怎么用 如 ...

  4. oracle设置打印机,使用 Oracle Solaris 打印管理器设置网络连接的打印机

    使用 Oracle Solaris 打印管理器设置网络连接的打印机 使用 Oracle Solaris 打印管理器设置网络连接的打印机的方法与设置直接连接的打印机类似.但是需要设置的打印机定义有所不同 ...

  5. 宣布 Windows Azure 通过 PCI DSS 合规性验证并且 ISO 认证范围扩大,同时正式发布 Windows Azure Hyper-V 恢复管理器和其他更新功能...

    今天,我们高兴地宣布两个重大里程碑事件,客户将能借此提高基于 Windows Azure 构建安全且合规的应用程序的能力.此外,我们还宣布正式发布 Windows Azure Hyper-V 恢复管理 ...

  6. VS2015配置PCL详细教程,使用配置属性管理器的方法,一劳永逸

    此处并不讲PCL的安装,假设已经安装完成PCL,并已经配置好环境变量 工程配置方法: 0.先是建立一个工程,这里命名为pclTest 接下来开始配置PCL 注意: 配置属性管理器和资源管理器的区别:配 ...

  7. CorelDraw出现应用程序恢复管理器向导解决办法汇总

    CorelDraw(cdr)出现"应用程序恢复管理器向导",对于那些经常使用Coreldraw软件的朋友来说应该不会陌生吧?这两天自己和同事的Coreldraw也都时不时的出现&q ...

  8. Delphi Project 之工程管理器(Project Manager)

    工程(Project)可以说是Delphi的生命.不可能创建一个没有工程的程序.利用工程可以把全部工作组合到一起,从而创建出可以执行的应用程序. 一般来说,每个工程都需要管理.也许要增加一个新的单元到 ...

  9. oracle10g企业管理器打不开,2014年05月13日  Oracle 10g的企业管理器(Enterprise Manager)的常见问题...

    问题: 如何打开Oracle 10g的企业管理器(Enterprise Manager)? 装了个Oracle 10g,却发现找不到企业管理器了.原来10g又升级了管理工具,不再采用8i, 9i的那些 ...

最新文章

  1. 【Qt】Qt程序查看动态链接库(windows)
  2. ExtJS之对话框及窗口篇
  3. 通过模型进行特征选择
  4. java配置irport,一个production模式下的Ror环境搭建-airport -JavaEye技术社区
  5. java图片识别查看器模拟_[转载]windows照片查看器无法显示图片内存不足
  6. 如何计算一只鸡的表面积?
  7. Flex4之元数据标签使用
  8. 建立书签链接的html语言,书签链接
  9. kali linux暴力破解wifi密码
  10. Windows10下电脑版微信未读消息自动弹窗工具
  11. 20年广西赛题技能要求(服务器)
  12. Kotlin Symbol Processing(KSP)使用初体验
  13. 格式化格林威治时间(Wed Aug 01 00:00:00 CST 2018)
  14. WeUI:专为开发微信HTML5应用的开源Web UI组件库
  15. js时间戳转时间年月日时分秒
  16. Yanmar(洋马)发动机SPN-FMI代码在仪表显示
  17. IDEA 警告 the package is not inside non-bundled dependency
  18. 2021-08-31 CoreDNS:Kubernetes内部域名解析原理、弊端及优化方式
  19. matter网络基础之—Thread
  20. 利用Python开发智能阅卷系统, 太有趣了!

热门文章

  1. 个人贷款违约预测模型(逻辑回归)
  2. Cocos Creator:挑战全平台引擎极限
  3. 【PLC编程】简易梯形图
  4. Keil错误 error: #5: cannot open source input file XXX / XXX.h:
  5. Mac在Dock程序坞上添加分割线,分割APP图标
  6. 终极!绝无仅有,史上最强python爬虫资料分享!
  7. ubuntu20.04开通多个ssh端口
  8. Scavenger:可在不同Paste站点爬取用户泄露凭证的实用工具
  9. 【20181027T1】洛阳怀【推结论+线性筛+分解质因数+GCD性质】
  10. 51nod 1479 小Y的数论题