« August 2025 »
S M T W T F S
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
You are not logged in. Log in
Entries by Topic
All topics  «
Blog Tools
Edit your Blog
Build a Blog
RSS Feed
View Profile
Open Community
Post to this Blog
Oracle Notes
Tuesday, 6 January 2009
OCM 8: Dataguard

8. Data Guard
ocm8  Use Data Guard Manager and DGMGRL
https://shenh.tripod.com/Oracleblog/index.blog/1825057/ocm8-use-data-guard-manager-and-dgmgrl/

 

Dataguard Reference:

http://www.ahmedbaraka.com/computer/docs/oracle_10g_dg_1.0.pdf

http://www.oracle.com/technology/deploy/availability/pdf/TWP_DataGuard_10gR2.pdf

http://static7.userland.com/oracle/gems/alejandroVargas/DataGuardPhysicalStandbystep.pdf

http://blogs.oracle.com/alejandroVargas/gems/DataGuardBrokerandobserverst.pdf

http://static7.userland.com/oracle/gems/alejandroVargas/DataGuardBrokerandobserverst.pdf

http://blogs.oracle.com/AlejandroVargas/

http://blogs.oracle.com/AlejandroVargas/gems/

http://blogs.oracle.com/AlejandroVargas/newsItems/viewFullItem$251/

 

ocm8: Use Data Guard Manager and DGMGRL


dataguard db:
DGMGRL


grid control
1): Database List: Type --> Database Instance: Primary | Physical Standby

2): Instance Detail Pages
  High Availability    

3): --> maintenance --> High Availability --> Data Guard

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

. oenv sid

dgmgrl
> CONNECT /

>help
>help show
> SHOW CONFIGURATION;
> SHOW CONFIGURATION VERBOSE;


> SHOW DATABASE db_unique_name;
> SHOW DATABASE VERBOSE db_unique_name ;
-- database name from show configuration

> SHOW DATABASE sid_stdg1;
> SHOW DATABASE verbose sid_stdg1;

> SHOW DATABASE sid_stdg2;
> SHOW DATABASE verbose sid_stdg2;

> SHOW INSTANCE instance_name_from_database_name;
-- instance name from show database

> show instance sid  on database sid_stdg1;
> show instance verbose sid  on database sid_stdg1;

> show instance sid  on database sid_stdg2;
> show instance verbose sid  on database sid_stdg2;

show instance verbose sid  on database sid_prd;

> SHOW INSTANCE VERBOSE;

sqlplus:
show parameter  service_names
show parameter  db_unique_name
show parameter  db_name
show parameter  db_domain
show parameter  DG_BROKER_START
show parameter  DG_BROKER_CONFIG
show parameter  log_archive_config
show parameter  log_archive_dest
show parameter  fal_server
show parameter  fal_client
show parameter  standby_file_management
show parameter  db_file_name_convert
show parameter  log_file_name_convert
show parameter  db_create_file_dest
show parameter  remote_login_passwordfile

select host_name, status, DATABASE_STATUS, INSTANCE_ROLE from v$instance;

select name, DB_UNIQUE_NAME,
DATABASE_ROLE,
GUARD_STATUS, DATAGUARD_BROKER,
SWITCHOVER_STATUS,
OPEN_MODE, LOG_MODE,
PROTECTION_MODE, PROTECTION_LEVEL
from v$database; 

Configuration of 10g Data Guard Broker and Observer for Switchover
Alejandro Vargas
Principal Support Consultant
Oracle Advanced Support Services

Configuring Data Guard Broker for Switchover, General Review. ......2
The Enviroment...2
Implementation notes:...................................2
Step by Step Implementation of Data Guard Broker................3
Enable Data Guard Broker Start on the Primary and Standby databases ................................3
Setup the Local_Listener parameter on both the Primary and Standby databases..................3
Setup the tnsnames to enable communication with both the Primary and Standby databases3
Check and edit database properties .............8
Enabling the configuration and databases..10
Enabling Fast Start Failover and the Observer ..................12
Ensure standby redo logs are configured on all databases ......12
Ensure the LogXptMode Property is set to SYNC .........13
Specify the FastStartFailoverTarget property ................14
Upgrade the protection mode to MAXAVAILABILITY, if necessary. ...................................14
Enable Flashback Database on the Primary and Standby databases. ...............................14
Enable fast start failover..........................16
Start the observer....................................17
Verify the fast-start failover configuration18
Perform a Switchover..............................19
Reference:.........23

Configuring Data Guard Broker for Switchover, General Review.
on this document I'm adding how to configure the broker and observer, setup the database to Maximum Availability and
managing switchover from Data Guard Manager, DGMGRL.

Data Guard Broker permit to manage a Data Guard Configuration, from both the Enterprise Manager Grid Control console, or from a
terminal in command line mode. In this document I will explore command line mode.

Pre requisites include the use of 10g Oracle server, using spfile on both the primary and standby and a third server for the Observer,
and configure the listeners to include a service for the Data Guard Broker.

The Enviroment

• 2 Linux servers, Oracle Distribution 2.6.9-55 EL i686 i386 GNU/Linux, the Primary and Standby databases are located on these
servers.
• 1 Linux server, RH Linux 2.6.9-42.ELsmp x86_64 GNU/Linux, The Data Guard Broker Observer is located on this server
• Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
ssh is configured for user oracle on both nodes
• Oracle Home is on identical path on both nodes
• Primary database WHITEOWL
• Standby database BLACKOWL

Implementation notes:
Once you have your primary and standby databases up and running these are the steps to follow:

1. Enable Data Guard Broker Start on the Primary and Standby databases.
2. Setup the Local_Listener parameter if the listener port is not the standard 1521, on both the Primary and Standby databases.
3. Setup the listener and tnsnames to enable communication with both the Primary and Standby databases.
4. Setup the Broker configuration files
5. Check and edit properties
6. Enable the configuration and databases
7. Enable Fast Start Failover and the Observer

Step by Step Implementation of Data Guard Broker

Enable Data Guard Broker Start on the Primary and Standby databases
SQL> ALTER SYSTEM SET DG_BROKER_START=TRUE SCOPE=BOTH;

Setup the Local_Listener parameter on both the Primary and Standby databases
SQL> ALTER SYSTEM SET LOCAL_LISTENER='LISTENER_VMRACTEST' SCOPE=BOTH;

Setup the tnsnames to enable communication with both the Primary and Standby databases

The listener.ora should include a service named global_db_nameDGMGRL to enable the broker to start the databases on the event of
switchover. This configuration needs to be included on both servers.
Listener.ora on Node 1
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522)(IP = FIRST))
)
)
SID_LIST_LISTENER_VMRACTEST =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME = whiteowl)
(ORACLE_HOME = /oradisk/app01/oracle/product/10gDB )
(SID_NAME = whiteowl)
)
(SID_DESC =
(SID_NAME=whiteowl)
(GLOBAL_DBNAME = whiteowl_DGMGRL)
(ORACLE_HOME = /oradisk/app01/oracle/product/10gDB )
)
)
Listener.ora on Node 2
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522)(IP = FIRST))
)
)

Tnsnames.ora on Node 1, 2 and the observer node
whiteowl=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest1)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = whiteowl_DGMGRL)
)
)
blackowl=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = blackowl_DGMGRL)
)
)

Setup the Broker configuration files

The broker configuration files are automatically created when the broker is started using
ALTER SYSTEM SET DG_BROKER_START=TRUE.

The default destination can be modified using the parameters
DG_BROKER_CONFIG_FILE1 and DG_BROKER_CONFIG_FILE2 On Primary:

SQL> show parameters DG_BROKER_CONFIG
NAME TYPE VALUE
---------------- ----------- ------------------------------
dg_broker_config_file1 string /oradisk/app01/oracle/product/
10gDB/dbs/dr1whiteowl.dat
dg_broker_config_file2 string /oradisk/app01/oracle/product/
10gDB/dbs/dr2whiteowl.dat

On Standby:

SQL> show parameters DG_BROKER_CONFIG
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
dg_broker_config_file1 string /oradisk/app01/oracle/product/
10gDB/dbs/dr1blackowl.dat

dg_broker_config_file2 string /oradisk/app01/oracle/product/
10gDB/dbs/dr2blackowl.dat

Next create from within the DGMGRL the configuration
[vmractest1] > dgmgrl
DGMGRL> CONNECT sys/oracle@whiteowl

DGMGRL> CREATE CONFIGURATION WHITEOWL AS
> PRIMARY DATABASE IS whiteowl
> CONNECT IDENTIFIER IS whiteowl;

Configuration "whiteowl" created with primary database "whiteowl"
Add the standby to the configuration and check it

DGMGRL> ADD DATABASE blackowl AS
> CONNECT IDENTIFIER IS blackowl
> MAINTAINED AS PHYSICAL;

Database "blackowl" added
DGMGRL> SHOW CONFIGURATION;

Configuration
Name: whiteowl
Enabled: NO
Protection Mode: MaxPerformance
Fast-Start Failover: DISABLED
Databases:
whiteowl - Primary database
blackowl - Physical standby database
Current status for "whiteowl":
DISABLED
Check and edit database properties
In this case parameter DbFileNameConvert has an error, it lacks the leading backslash:

DGMGRL> SHOW DATABASE VERBOSE blackowl;
Database
Name: blackowl
Role: PHYSICAL STANDBY
Enabled: NO
Intended State: OFFLINE
Instance(s):
blackowl
Properties:
InitialConnectIdentifier = 'blackowl'
LogXptMode = 'ASYNC'
Dependency = ''
DelayMins = '0'
Binding = 'OPTIONAL'
MaxFailure = '0'
MaxConnections = '1'
ReopenSecs = '300'
NetTimeout = '180'
LogShipping = 'ON'
PreferredApplyInstance = ''
ApplyInstanceTimeout = '0'
ApplyParallel = 'AUTO'
StandbyFileManagement = 'auto'
ArchiveLagTarget = '0'
LogArchiveMaxProcesses = '30'
LogArchiveMinSucceedDest = '1'
DbFileNameConvert = 'vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/, /oradisk/od01/BLACKOWL/datafile/'
LogFileNameConvert = '/vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/, /oradisk/od01/BLACKOWL/onlinelog/'
FastStartFailoverTarget = ''
StatusReport = '(monitor)'
InconsistentProperties = '(monitor)'
InconsistentLogXptProps = '(monitor)'
SendQEntries = '(monitor)'
LogXptStatus = '(monitor)'
RecvQEntries = '(monitor)'
HostName = 'vmractest2.partnergsm.co.il'
SidName = 'blackowl'
LocalListenerAddress = '(ADDRESS=(PROTOCOL=TCP)(HOST=vmractest2)(PORT=1522)(IP=FIRST))'
StandbyArchiveLocation = '/oradisk/od01/BLACKOWL/archives/'
AlternateLocation = ''
LogArchiveTrace = '0'
LogArchiveFormat = '%t_%s_%r.arc'
LatestLog = '(monitor)'
TopWaitEvents = '(monitor)'
Current status for "blackowl":
DISABLED

DGMGRL> EDIT DATABASE "blackowl" SET PROPERTY 'DbFileNameConvert' =
'/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/, /oradisk/od01/BLACKOWL/datafile/';

Property "DbFileNameConvert" updated

The parameter DbFileNameConvert will be updated on the database also on the next restart.
Enabling the configuration and databases

DGMGRL> enable configuration;
DGMGRL> show configuration;

Configuration
Name: whiteowl
Enabled: YES
Protection Mode: MaxPerformance
Fast-Start Failover: DISABLED
Databases:
whiteowl - Primary database
blackowl - Physical standby database
Current status for "whiteowl":
SUCCESS

DGMGRL> enable database blackowl;
DGMGRL> SHOW DATABASE VERBOSE blackowl;

Database
Name: blackowl
Role: PHYSICAL STANDBY
Enabled: YES
Intended State: ONLINE
Instance(s):
blackowl
Properties:
InitialConnectIdentifier = 'blackowl'
LogXptMode = 'ASYNC'
Dependency = ''
DelayMins = '0'
Binding = 'OPTIONAL'
MaxFailure = '0'
MaxConnections = '1'
ReopenSecs = '300'
NetTimeout = '180'
LogShipping = 'ON'
PreferredApplyInstance = ''
ApplyInstanceTimeout = '0'
ApplyParallel = 'AUTO'
StandbyFileManagement = 'auto'
ArchiveLagTarget = '0'
LogArchiveMaxProcesses = '30'
LogArchiveMinSucceedDest = '1'
DbFileNameConvert = '/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/ , /oradisk/od01/BLACKOWL/datafile/'
LogFileNameConvert = '/vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/, /oradisk/od01/BLACKOWL/onlinelog/'
FastStartFailoverTarget = ''
StatusReport = '(monitor)'
InconsistentProperties = '(monitor)'
InconsistentLogXptProps = '(monitor)'
SendQEntries = '(monitor)'
LogXptStatus = '(monitor)'
RecvQEntries = '(monitor)'
HostName = 'vmractest2.partnergsm.co.il'
SidName = 'blackowl'
LocalListenerAddress = '(ADDRESS=(PROTOCOL=TCP)(HOST=vmractest2)(PORT=1522)(IP=FIRST))'
StandbyArchiveLocation = '/oradisk/od01/BLACKOWL/archives/'
AlternateLocation = ''
LogArchiveTrace = '0'
LogArchiveFormat = '%t_%s_%r.arc'
LatestLog = '(monitor)'
TopWaitEvents = '(monitor)'
Current status for "blackowl":
SUCCESS

Enabling Fast Start Failover and the Observer
These are the steps required to enable and check Fast Start Failover and the Observer:
1. Ensure standby redo logs are configured on all databases.
2. Ensure the LogXptMode Property is set to SYNC.
3. Specify the FastStartFailoverTarget property.
4. Upgrade the protection mode to MAXAVAILABILITY, if necessary.
5. Enable Flashback Database on the primary and standby databases, if necessary.
6. Enable fast start failover.
7. Start the observer.
8. Verify the fast-start failover configuration.
9. Performing a Switchover Operation

Ensure standby redo logs are configured on all databases

This database is using Oracle Managed files so it is not necessary to pass a member name, i.e.:

ALTER DATABASE ADD STANDBY LOGFILE GROUP 4 SIZE 50M;

SQL> set lines 120
SQL> col member for a80
SQL> select type,member from v$logfile order by type
2 /
TYPE MEMBER
------- --------------------------------------------------------------------------------
ONLINE /vmasmtest/whiteowl/recovery/WHITEOWL/onlinelog/o1_mf_2_3hkno95x_.log
ONLINE /vmasmtest/whiteowl/recovery/WHITEOWL/onlinelog/o1_mf_1_3hkno7jb_.log
ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_3hkno747_.log
ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_3_3hknoby2_.log
ONLINE /vmasmtest/whiteowl/recovery/WHITEOWL/onlinelog/o1_mf_3_3hknocmw_.log
ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_2_3hkno8rq_.log
STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_6_3gznrwd7_.log
STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_4_3gznjc9v_.log
STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_5_3gznnrh0_.log
9 rows selected.

Ensure the LogXptMode Property is set to SYNC
These commands will succeed only if database is configured with standby redo logs.

DGMGRL> connect sys/oracle@whiteowl

DGMGRL> EDIT DATABASE whiteowl SET PROPERTY 'LogXptMode'='SYNC';
Property "LogXptMode" updated

DGMGRL> EDIT DATABASE blackowl SET PROPERTY 'LogXptMode'='SYNC';
Property "LogXptMode" updated

Specify the FastStartFailoverTarget property
DGMGRL> EDIT DATABASE whiteowl SET PROPERTY FastStartFailoverTarget='blackowl';
Property "faststartfailovertarget" updated

DGMGRL> EDIT DATABASE blackowl SET PROPERTY FastStartFailoverTarget='whiteowl';
Property "faststartfailovertarget" updated

Upgrade the protection mode to MAXAVAILABILITY, if necessary.
DGMGRL> EDIT CONFIGURATION SET PROTECTION MODE AS MAXAVAILABILITY;

Operation requires shutdown of instance "whiteowl" on database "whiteowl"
Shutting down instance "whiteowl"...
Database closed.
Database dismounted.
ORACLE instance shut down.
Operation requires startup of instance "whiteowl" on database "whiteowl"
Starting instance "whiteowl"...
Unable to connect to database
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Failed.
You are no longer connected to ORACLE
Please connect again.
Unable to start instance "whiteowl"
You must start instance "whiteowl" manually

Enable Flashback Database on the Primary and Standby databases.
SQL> conn / as sysdba
Connected to an idle instance.
SQL> startup mount;

On Both databases
To enter the standby into Flashback mode you must shutdown the both databases, then while the primary is down execute the
following commands on the standby:

SQL> ALTER SYSTEM SET UNDO_RETENTION=3600 SCOPE=SPFILE;
SQL> ALTER SYSTEM SET UNDO_MANAGEMENT='AUTO' SCOPE=SPFILE;
SQL> startup mount;
SQL> ALTER DATABASE FLASHBACK ON;

Enable fast start failover

[vmractest1] > dgmgrl
DGMGRL for Linux: Version 10.2.0.1.0 - Production
Copyright (c) 2000, 2005, Oracle. All rights reserved.
Welcome to DGMGRL, type "help" for information.

DGMGRL> connect sys/oracle@whiteowl

DGMGRL> SHOW CONFIGURATION;
Configuration
Name: whiteowl
Enabled: YES
Protection Mode: MaxAvailability
Fast-Start Failover: DISABLED
Databases:
whiteowl - Primary database
blackowl - Physical standby database
Current status for "whiteowl":
SUCCESS

DGMGRL> SHOW DATABASE blackowl;
Database
Name: blackowl
Role: PHYSICAL STANDBY
Enabled: YES
Intended State: ONLINE
Instance(s):
blackowl
Current status for "blackowl":
SUCCESS

DGMGRL> ENABLE FAST_START FAILOVER;
Enabled.

DGMGRL> SHOW CONFIGURATION;
Configuration
Name: whiteowl
Enabled: YES
Protection Mode: MaxAvailability
Fast-Start Failover: ENABLED
Databases:
whiteowl - Primary database
blackowl - Physical standby database
- Fast-Start Failover target
Current status for "whiteowl":
Start the observer
Start the observer from a third server on background. You may use a script like this:

---------------- script start on next line --------------------
#!/bin/ksh
# startobserver
export ORACLE_BASE=/vmractst3/app01/oracle
export ORACLE_HOME=/vmractst3/app01/oracle/product/10.2
export
BASE_PATH=/vmractst3/app01/oracle/scripts/general:/opt/CTEact/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/bin:/etc:/usr/loc
al/maint/oracle:/usr/ccs/bin:/usr/openwin/bin:/usr/dt/bin:/usr/local/bin:.
export PATH=$ORACLE_HOME/bin:$BASE_PATH

dgmgrl << eof
connect sys/oracle@whiteowl
START OBSERVER;
eof

---------------- script end on previous line --------------------
[vmractest3] > nohup ./startobserver &
[2] 22182
<oracle> /vmractst3/app01/oracle/product/10.2/dbs > DGMGRL for Linux: Version 10.2.0.3.0 - 64bit Production
Copyright (c) 2000, 2005, Oracle. All rights reserved.
Welcome to DGMGRL, type "help" for information.

DGMGRL> Connected.

DGMGRL> Observer started
Verify the fast-start failover configuration.

DGMGRL> SHOW CONFIGURATION VERBOSE;
Configuration
Name: whiteowl
Enabled: YES
Protection Mode: MaxAvailability
Fast-Start Failover: ENABLED
Databases:
whiteowl - Primary database
blackowl - Physical standby database
- Fast-Start Failover target
Fast-Start Failover
Threshold: 30 seconds
Observer: vmractest3
Current status for "whiteowl":
SUCCESS

DGMGRL> SHOW DATABASE blackowl;
Database
Name: blackowl
Role: PHYSICAL STANDBY
Enabled: YES
Intended State: ONLINE
Instance(s):
blackowl
Current status for "blackowl":
SUCCESS

Perform a Switchover

Connect to DGMGRL on the observer server:
ORA Environement Variables:
ORACLE_BASE=/vmractst3/app01/oracle
ORACLE_HOME=/ vmractst 3/app01/oracle/product/10.2

[vmractst3] > dgmgrl
DGMGRL for Linux: Version 10.2.0.3.0 - 64bit Production
Copyright (c) 2000, 2005, Oracle. All rights reserved.
Welcome to DGMGRL, type "help" for information.

DGMGRL> connect sys/oracle@whiteowl
DGMGRL>
Check that primary and standby are healthy
This check must return 'SUCCESS' as the status for both databases,
otherwise it means there is a configuration problem.

DGMGRL> show database whiteowl;
Database
Name: whiteowl
Role: PRIMARY
Enabled: YES
Intended State: ONLINE
Instance(s):
whiteowl
Current status for "whiteowl":
SUCCESS

DGMGRL> show database blackowl;
Database
Name: blackowl
Role: PHYSICAL STANDBY
Enabled: YES
Intended State: ONLINE
Instance(s):
blackowl
Current status for "blackowl":
SUCCESS
Execute the switchover

DGMGRL> SWITCHOVER TO blackowl;
Performing switchover NOW, please wait...
Operation requires shutdown of instance "whiteowl" on database "whiteowl"
Shutting down instance "whiteowl"...
ORA-01109: database not open
Database dismounted.
ORACLE instance shut down.
Operation requires shutdown of instance "blackowl" on database "blackowl"
Shutting down instance "blackowl"...
ORA-01109: database not open
Database dismounted.
ORACLE instance shut down.
Operation requires startup of instance "whiteowl" on database "whiteowl"
Starting instance "whiteowl"...
ORACLE instance started.
Database mounted.
Operation requires startup of instance "blackowl" on database "blackowl"
Starting instance "blackowl"...
ORACLE instance started.
Database mounted.
Switchover succeeded, new primary is "blackowl"

DGMGRL> show database blackowl
Database
Name: blackowl
Role: PRIMARY
Enabled: YES
Intended State: ONLINE
Instance(s):
blackowl
Current status for "blackowl":
SUCCESS

DGMGRL> show database whiteowl
Database
Name: whiteowl
Role: PHYSICAL STANDBY
Enabled: YES
Intended State: ONLINE
Instance(s):
whiteowl
Current status for "whiteowl":
SUCCESS

Reference:
Oracle® Data Guard Concepts and Administration
10g Release 2 (10.2)
Part Number B14239-04
http://download.oracle.com/docs/cd/B19306_01/server.102/b14230/cli.htm#BGBFEAFG 

ocm8  Create and utilize a physical standby database
https://shenh.tripod.com/Oracleblog/index.blog/1825058/ocm8-create-and-utilize-a-physical-standby-database/

http://www.itpub.net/636810,1.html

alter database force logging;

alter database force nologging;

dataguard manager: primary database must use spfile;

alter database create standby controlfile as '\...\standyctf.con';

init.ora for standby db
db_file_name_covert
log_file_name_convert
log_archive_format
standby_file_management=auto vs. manual
standby_archive_dest
log_archive_start=true vs. manual
remote_archive_enable=true false send receive

on standby db:
startup mountpfile-stby_init.ora
alter database add standby logfile ( ..., ... ) size 500K;
alter database recover managed standy database disconnect;

on primary db:
alter system set log_archive_dest_2='service=standby mandatory';
alter system set log_archive_dest_stat_2=enable defer reset alternate;

archive_lag_target=1800 ( seconds ) max wait for a log switch to occur

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


Alejandro Vargas
Principal Support Consultant
Oracle Advanced Support Services

Creating a Data Guard Physical Standby environment, General Review.
The Enviroment
Implementation notes: 
Step by Step Implementation of a Physical Standby Environment
Primary Database Steps
Primary Database General View
Enable Forced Logging
Create a Password File
Configure a Standby Redo Log
Enable Archiving
Set Primary Database Initialization Parameters
Standby Database Steps
Create a Control File for the Standby Database
Backup the Primary Database and transfer a copy to the Standby node
Prepare an Initialization Parameter File for the Standby Database
Configure the listener and tnsnames to support the database on both nodes
Set Up the Environment to Support the Standby Database on the standby node
Start the Primary Database
Verify the Physical Standby Database Is Performing Properly
Reference:

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

Creating a Data Guard Physical Standby environment, General Review.
Manually setting up a Physical standby database is a simple task when all prerequisites and setup steps are carefully met and executed.
In this example I did use 2 hosts, that host a RAC database. All RAC preinstall requisites are then in place and no additional configuration was
necessary to implement Data Guard Physical Standby manually. Note that using Enterprise Manager Grid Control Data Guard Physical Standby
can be implemented from the Grid Control Console easily. Still, this exercise provide a degree of familiarity with Data Guard.
The Enviroment
2 Linux servers, Oracle Distribution 2.6.9-55 EL i686 i386 GNU/Linux
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
ssh is configured for user oracle on both nodes
Oracle Home is on identical path on both nodes

Implementation notes:

Once you have your primary database up and running these are the steps to follow:
1. Enable Forced Logging
2. Create a Password File
3. Configure a Standby Redo Log
4. Enable Archiving
5. Set Primary Database Initialization Parameters

Having followed these steps to implement the Physical Standby you need to follow these steps:
1. Create a Control File for the Standby Database
2. Backup the Primary Database and transfer a copy to the Standby node.
3. Prepare an Initialization Parameter File for the Standby Database
4. Configure the listener and tnsnames to support the database on both nodes
5. Set Up the Environment to Support the Standby Database on the standby node.
6. Start the Physical Standby Database
7. Verify the Physical Standby Database Is Performing Properly

Step by Step Implementation of a Physical Standby Environment
Primary Database Steps
Primary Database General View

SQL> select name from v$database;
NAME
---------
WHITEOWL

SQL> select file_name from dba_data_files;
FILE_NAME
--------------------------------------------------------------------------------
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_users_310mzml9_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_sysaux_310mzm34_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_undotbs1_310mzmk2_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_system_310mzm27_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test2_3117h15v_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test3_3117h8nv_.dbf
/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test4_3117hk7d_.dbf
7 rows selected.

SQL> select name from v$database;
NAME
---------
WHITEOWL

SQL> show parameters unique
NAME TYPE VALUE
-------- ----------- -------
db_unique_name string whiteowl

Enable Forced Logging

In order to implement Standby Database we enable 'Forced Logging'.

This option ensures that even in the event that a 'nologging' operation is done,
force logging takes precedence and all operations are logged
into the redo logs.

SQL> ALTER DATABASE FORCE LOGGING;
Database altered.

Create a Password File
A password file must be created on the Primary and copied over to the Standby site.
The sys password must be identical on both sites. T
his is a key prerequisite in order to be able to ship and
apply archived logs from Primary to Standby.

cd $ORACLE_HOME/dbs

[vmractest1] > orapwd file=orapwwhiteowl password=oracle force=y

Configure a Standby Redo Log

A Standby Redo log is added to enable Data Guard Maximum Availability and Maximum Protection modes.
It is important to configure the Standby Redo Logs (SRL) with the same size as the online redo logs.

In this example I'm using Oracle Managed Files, that's why I don't need to provide the SRL path and file name.
If you are not using OMF's, you then must pass the full qualified name.

SQL> select * from v$logfile;
GROUP# STATUS TYPE MEMBER IS_
---------- ------- ------- ---------------------------------------------- ---
3 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_3_310n22jj_.log NO
2 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_2_310n21sx_.log NO
1 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_310n215q_.log NO

SQL> select bytes from v$log;
BYTES
----------
52428800
52428800
52428800

SQL> ALTER DATABASE ADD STANDBY LOGFILE GROUP 4 SIZE 50M;
Database altered.

SQL> ALTER DATABASE ADD STANDBY LOGFILE GROUP 5 SIZE 50M;
Database altered.

SQL> ALTER DATABASE ADD STANDBY LOGFILE GROUP 6 SIZE 50M;
Database altered.

SQL> select * from v$logfile
2 /
GROUP# STATUS TYPE MEMBER IS_
---------- ------- ------- ---------------------------------------------------------------------- ---
3 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_3_310n22jj_.log NO
2 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_2_310n21sx_.log NO
1 ONLINE /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_310n215q_.log NO
4 STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_4_3gznjc9v_.log NO
5 STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_5_3gznnrh0_.log NO
6 STANDBY /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_6_3gznrwd7_.log NO
6 rows selected.

Enable Archiving
On 10g you can enable archive log mode by mounting the database and executing the archivelog command:

SQL> startup mount;
SQL> alter database archivelog;
SQL> alter database open;
SQL> archive log list

Set Primary Database Initialization Parameters

Data Guard must use spfile,

SQL> create pfile='/oradisk/app01/oracle/product/10gDB/dbs/pfilewhiteowl.ora' from spfile;

db_name='whiteowl'
db_unique_name='whiteowl'
LOG_ARCHIVE_CONFIG='DG_CONFIG=(whiteowl,blackowl)'
control_files='/vmasmtest/od01/WHITEOWL/WHITEOWL/controlfile/o1_mf_310n1xf0_.ctl'
LOG_ARCHIVE_DEST_1='LOCATION=/vmasmtest/whiteowl/archdest/VALID_FOR=(ALL_LOGFILES,ALL_ROLES)
DB_UNIQUE_NAME=whiteowl'
LOG_ARCHIVE_DEST_2='SERVICE=blackowl LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=blackowl'
LOG_ARCHIVE_DEST_STATE_1=ENABLE
LOG_ARCHIVE_DEST_STATE_2=ENABLE
REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE
LOG_ARCHIVE_FORMAT=%t_%s_%r.arc
LOG_ARCHIVE_MAX_PROCESSES=30

# Standby role parameters --------------------------------------------------------------------
*.fal_server=blackowl
*.fal_client=whiteowl
*.standby_file_management=auto
*.db_file_name_convert='BLACKOWL/BLACKOWL','WHITEOWL/WHITEOWL'
*.log_file_name_convert='/vmasmtest/od01/BLACKOWL/BLACKOWL/','/vmasmtest/od01/WHITEOWL/WHITEOWL/'

# ---------------------------------------------------------------------------------------------
audit_file_dest='/oradisk/app01/oracle/admin/whiteowl/adump'
background_dump_dest='/oradisk/app01/oracle/admin/whiteowl/bdump'
core_dump_dest='/oradisk/app01/oracle/admin/whiteowl/cdump'
user_dump_dest='/oradisk/app01/oracle/admin/whiteowl/udump'
compatible='10.2.0.1.0'
db_block_size=8192
db_create_file_dest='/vmasmtest/od01/WHITEOWL'
db_domain=''
db_file_multiblock_read_count=16
job_queue_processes=10
open_cursors=300
pga_aggregate_target=94371840
processes=150
remote_login_passwordfile='EXCLUSIVE'
sga_target=283115520
undo_management='AUTO'
undo_tablespace='UNDOTBS1'
Once the new parameter file is ready we create from it the spfile:

SQL> shutdown immediate;
SQL> startup nomount pfile='/oradisk/app01/oracle/product/10gDB/dbs/pfilewhiteowl.ora';
SQL> create spfile from pfile='/oradisk/app01/oracle/product/10gDB/dbs/pfilewhiteowl.ora';
SQL> shutdown immediate;
SQL> startup;

Standby Database Steps
Create a Control File for the Standby Database
The standby database will use a control file that is generated on the primary database

SQL> startup mount;
SQL> ALTER DATABASE CREATE STANDBY CONTROLFILE AS '/oradisk/app01/oracle/product/10gDB/dbs/blackowl.ctl';
SQL> ALTER DATABASE OPEN;

Backup the Primary Database and transfer a copy to the Standby node.

Generate a script to copy datafiles
SQL> set pages 50000 lines 120 head off veri off flush off ti off
SQL> spool cpfiles
SQL> select 'scp -p '||file_name||' $v_dest' from dba_data_files;

scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_users_310mzml9_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_sysaux_310mzm34_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_undotbs1_310mzmk2_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_system_310mzm27_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test2_3117h15v_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test3_3117h8nv_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test4_3117hk7d_.dbf $v_dest
7 rows selected.

SQL> select 'scp -p '||file_name||' $v_dest' from dba_temp_files;

scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_temp_310n2bnj_.tmp $v_dest
SQL> select 'scp -p '||member||' $v_dest' from v$logfile;
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_3_310n22jj_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_2_310n21sx_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_310n215q_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_4_3gznjc9v_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_5_3gznnrh0_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_6_3gznrwd7_.log $v_dest
6 rows selected.

SQL> spool off

Shutdown the database, edit the script to add the v_dest location, and execute it.

[vmractest1] > mv cpfiles.lst cpfiles

#!/bin/ksh
v_dest=vmractest2:/oradisk/od01/BLACKOWL/datafile/
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_users_310mzml9_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_sysaux_310mzm34_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_undotbs1_310mzmk2_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_system_310mzm27_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test2_3117h15v_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test3_3117h8nv_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_test4_3117hk7d_.dbf $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/o1_mf_temp_310n2bnj_.tmp $v_dest

v_dest= vmractest2:/oradisk/od01/BLACKOWL/onlinelog/
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_3_310n22jj_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_2_310n21sx_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_310n215q_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_4_3gznjc9v_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_5_3gznnrh0_.log $v_dest
scp -p /vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_6_3gznrwd7_.log $v_dest

On the standby node create the required directories to get the datafiles

[root@vmractest2 root]# mkdir -p /oradisk/od01/BLACKOWL/datafile/
[root@vmractest2 root]# mkdir -p /oradisk/od01/BLACKOWL/onlinelog/
[root@vmractest2 root]# chown -R oracle:dba /oradisk/od01

On the primary node execute the script to copy the database while the main database is down (or in backup mode)

[vmractest1] > chmod 700 cpfiles
[vmractest1] > ./cpfiles


Prepare an Initialization Parameter File for the Standby Database

Copy and edit the primary init.ora to set it up for the standby role
*.db_name='whiteowl'
*.db_unique_name='blackowl'
*.audit_file_dest='/oradisk/app01/oracle/admin/blackowl/adump'
*.background_dump_dest='/oradisk/app01/oracle/admin/blackowl/bdump'
*.core_dump_dest='/oradisk/app01/oracle/admin/blackowl/cdump'
*.user_dump_dest='/oradisk/app01/oracle/admin/blackowl/udump'
*.compatible='10.2.0.1.0'
*.control_files='/oradisk/od01/BLACKOWL/controlfile/blackowl_01.ctl','/oradisk/od01/BLACKOWL/controlfile/blackowl_02.ctl'
*.db_block_size=8192
*.db_create_file_dest='/oradisk/od01/BLACKOWL'
*.db_domain=''
*.db_file_multiblock_read_count=16
*.db_file_name_convert='/oradisk/od01/BLACKOWL/datafile/','/vmasmtest/od01/WHITEOWL/WHITEOWL/datafile/'
*.log_file_name_convert='/oradisk/od01/BLACKOWL/onlinelog/','/vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/'
*.fal_server='whiteowl'
*.fal_client='blackowl'
*.job_queue_processes=10
*.LOG_ARCHIVE_CONFIG='DG_CONFIG=(whiteowl,blackowl)'
*.LOG_ARCHIVE_DEST_1='LOCATION=/oradisk/od01/BLACKOWL/archives/
VALID_FOR=(ALL_LOGFILES,ALL_ROLES)
DB_UNIQUE_NAME=blackowl'
*.LOG_ARCHIVE_DEST_2='SERVICE=whiteowl LGWR ASYNC
VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE)
DB_UNIQUE_NAME=whiteowl'
*.LOG_ARCHIVE_DEST_STATE_1='ENABLE'
*.LOG_ARCHIVE_DEST_STATE_2='ENABLE'
*.LOG_ARCHIVE_FORMAT='%t_%s_%r.arc'
*.LOG_ARCHIVE_MAX_PROCESSES=30
*.open_cursors=300
*.pga_aggregate_target=94371840
*.processes=150
*.remote_login_passwordfile='EXCLUSIVE'
*.sga_target=283115520
*.standby_file_management='auto'
*.undo_management='AUTO'
*.undo_tablespace='UNDOTBS1'

Create all required directories for dump directories and archived log destination

[vmractest2] > mkdir -p /oradisk/app01/oracle/admin/blackowl/adump
{oracle} /oradisk/app01/oracle/product/10gDB/dbs [vmractest2] > mkdir -p /oradisk/app01/oracle/admin/blackowl/bdump
{oracle} /oradisk/app01/oracle/product/10gDB/dbs [vmractest2] > mkdir -p /oradisk/app01/oracle/admin/blackowl/cdump
{oracle} /oradisk/app01/oracle/product/10gDB/dbs [vmractest2] > mkdir -p /oradisk/app01/oracle/admin/blackowl/udump
{oracle} /oradisk/app01/oracle/product/10gDB/dbs [vmractest2] > mkdir -p /oradisk/od01/BLACKOWL/archives/

Copy from the primary the standby controlfile to its destination
scp -p blackowl.ctl vmractest2:/oradisk/od01/BLACKOWL/controlfile/blackowl_02.ctl
scp -p blackowl.ctl vmractest2:/oradisk/od01/BLACKOWL/controlfile/blackowl_01.ctl

Configure the listener and tnsnames to support the database on both nodes
Configure listener.ora on both servers to hold entries for both databases

# ON VMRACTEST1
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest1)(PORT = 1522)(IP = FIRST))
)
)
SID_LIST_LISTENER_VMRACTEST =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME = whiteowl)
(ORACLE_HOME = /oradisk/app01/oracle/product/10gDB )
(SID_NAME = whiteowl)
)
)

# ON VMRACTEST2
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522)(IP = FIRST))
)
)
SID_LIST_LISTENER_VMRACTEST =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME = blackowl)
(ORACLE_HOME = /oradisk/app01/oracle/product/10gDB )
(SID_NAME = blackowl)
)
)

Configure tnsnames.ora on both servers to hold entries for both databases

# ON VMRACTEST1
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest1)(PORT = 1522)(IP = FIRST))
)
)

WHITHEOWL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest1)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = whiteowl)
)
)

BLACKOWL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = blackowl)
)
)

# ON VMRACTEST2
LISTENER_VMRACTEST =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522)(IP = FIRST))
)
)

BLACKOWL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest2)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = blackowl)
)
)

WHITHEOWL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = vmractest1)(PORT = 1522))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = whiteowl)
)
)

Start the listener and check tnsping on both nodes to both services

[vmractest1.partnergsm.co.il] > tnsping whiteowl

{oracle} /oradisk/app01/oracle/product/10gDB/network/admin

[vmractest1.partnergsm.co.il] > tnsping blackowl


Set Up the Environment to Support the Standby Database on the standby node.
Copy the password file from Primary to Standby, sys password must be identical

[vmractest1]> scp orapwwhiteowl vmractest2:/oradisk/app01/oracle/product/10gDB/dbs/orapwblackowl

Setup the environment variables to point to the Satndby database
ORACLE_HOME=/oradisk/app01/oracle/product/10gDB
ORACLE_SID=blackowl
Startup nomount the Standby database and generate an spfile

{oracle} /oradisk/app01/oracle/product/10gDB/dbs [vmractest2] > sqlplus / as sysdba
SQL> startup nomount pfile='/oradisk/app01/oracle/product/10gDB/dbs/initblackowl.ora'
SQL> create spfile from pfile='/oradisk/app01/oracle/product/10gDB/dbs/initblackowl.ora';
SQL> shutdown immediate;
SQL> startup mount
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;


The alert log of the standby will show the operations taking place


ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION
Wed Sep 19 16:46:26 2007
Attempt to start background Managed Standby Recovery process (blackowl)
MRP0 started with pid=47, OS id=12498
Wed Sep 19 16:46:26 2007
MRP0: Background Managed Standby Recovery process started (blackowl)
Managed Standby Recovery not using Real Time Apply
Clearing online redo logfile 1 /oradisk/od01/BLACKOWL/onlinelog/o1_mf_1_310n215q_.log
Clearing online log 1 of thread 1 sequence number 95
Deleted Oracle managed file /oradisk/od01/BLACKOWL/onlinelog/o1_mf_1_310n215q_.log
Wed Sep 19 16:46:32 2007
Completed: ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION
Wed Sep 19 16:46:33 2007
Clearing online redo logfile 1 complete
Clearing online redo logfile 2 /oradisk/od01/BLACKOWL/onlinelog/o1_mf_2_310n21sx_.log
Clearing online log 2 of thread 1 sequence number 96
Deleted Oracle managed file /oradisk/od01/BLACKOWL/onlinelog/o1_mf_2_310n21sx_.log
Clearing online redo logfile 2 complete
Clearing online redo logfile 3 /oradisk/od01/BLACKOWL/onlinelog/o1_mf_3_310n22jj_.log
Clearing online log 3 of thread 1 sequence number 94
Deleted Oracle managed file /oradisk/od01/BLACKOWL/onlinelog/o1_mf_3_310n22jj_.log
Clearing online redo logfile 3 complete
Media Recovery Waiting for thread 1 sequence 96
Start the Primary Database
The alert log of the primary will show how it recognize the standby and start shipping archived logs
******************************************************************
LGWR: Setting 'active' archival for destination LOG_ARCHIVE_DEST_2
******************************************************************
Wed Sep 19 16:01:07 2007
LNS: Standby redo logfile selected for thread 1 sequence 100 for destination
LOG_ARCHIVE_DEST_2
Wed Sep 19 16:01:07 2007
Successfully onlined Undo Tablespace 1.
Wed Sep 19 16:01:07 2007
SMON: enabling tx recovery
Wed Sep 19 16:01:09 2007
Database Characterset is AL32UTF8
replication_dependency_tracking turned off (no async multimaster replication found)
Starting background process QMNC
QMNC started with pid=21, OS id=13864
Wed Sep 19 16:01:12 2007
Completed: ALTER DATABASE OPEN
Wed Sep 19 16:01:13 2007
ARCq: Standby redo logfile selected for thread 1 sequence 99 for destination
LOG_ARCHIVE_DEST_2
Wed Sep 19 16:05:05 2007
Thread 1 advanced to log sequence 101
Current log# 1 seq# 101 mem# 0:
/vmasmtest/od01/WHITEOWL/WHITEOWL/onlinelog/o1_mf_1_310n215q_.log
Wed Sep 19 16:05:06 2007
LNS: Standby redo logfile selected for thread 1 sequence 101 for destination
LOG_ARCHIVE_DEST_2


Verify the Physical Standby Database Is Performing Properly

Check archived redo log on Standby

SQL> show parameters db_unique_name;

NAME TYPE VALUE
----- ----------- ------------
db_unique_name string blackowl
SQL> l
1* SELECT NAME FROM V$DATABASE

SQL> SELECT SEQUENCE#, FIRST_TIME, NEXT_TIME FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;
SEQUENCE# FIRST_TIM NEXT_TIME
---------- --------- ---------
96 19-SEP-07 19-SEP-07
97 19-SEP-07 19-SEP-07
98 19-SEP-07 19-SEP-07
99 19-SEP-07 19-SEP-07
100 19-SEP-07 19-SEP-07
Switch logfiles on Primary

SQL> alter system switch logfile;
SQL> archive log list
SQL> alter system switch logfile;
SQL> archive log list
SQL> SELECT SEQUENCE#, FIRST_TIME, NEXT_TIME FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;

SEQUENCE# FIRST_TIME NEXT_TIME
---------- -------------- --------------
96 19/09/07 09:35 19/09/07 09:45
97 19/09/07 09:45 19/09/07 15:20
98 19/09/07 15:20 19/09/07 15:48
99 19/09/07 15:48 19/09/07 16:00
100 19/09/07 16:00 19/09/07 16:05
101 19/09/07 16:05 19/09/07 16:08
102 19/09/07 16:08 19/09/07 16:08
7 rows selected.

Reference:
Oracle® Data Guard Concepts and Administration
10g Release 2 (10.2)
Part Number B14239-04
http://download.oracle.com/docs/cd/B19306_01/server.102/b14239/create_ps.htm#SBYDB00210 

ocm8  Create and utilize a logical standby database
https://shenh.tripod.com/Oracleblog/index.blog/1825059/ocm8-create-and-utilize-a-logical-standby-database/


1): data type
Select * from dba_logstdby_unsupported;

2):
select owner, table_name, bad_column from dba_logstdby_not_unique;
--> add primary key


3): force logging
select supplemental_log_data_pk,supplemental_log_data_ui from v$database;

ALTER  DATABASE ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY,UNIQUE INDEX) COLUMNS;

4):
JSSLDG>alter database recover managed standby database cancel;
EXECUTE DBMS_LOGSTDBY.BUILD;

shutdown immediate
startup mount;


5):
convert physical standby to logical standby
SQL> alter database recover to logical standby NEW_DBNAME;
alter database recover to logical standby jssldg;

6):  enter logical apply
SQL> alter database open resetlogs;

SQL> alter database start logical standby apply immediate;
SQL> alter database stop logical standby apply immediate;

7):  prepare to switch over

7a):
alter database prepare to switchover to logical standby;
select switchover_status from v$database;

7b):
alter database prepare to switchover to primary;

ALTER DATABASE PREPARE TO SWITCHOVER CANCEL;

8): commit to switch over
alter database commit to switchover to logical standby;
alter database commit to switchover to primary;

9): sql apply
alter database start logical standby apply;

10): failover
alter database activate logical standby database finish apply;

11):

alter session disable guard;
create database link getjssweb connect to jss identified by jss using 'jssweb';
alter session enable guard;

12); re-start sql apply
alter database start logical standby apply new primary getjssweb;

ocm8  Set up log transport services for various levels or protection
https://shenh.tripod.com/Oracleblog/index.blog/1825060/ocm8-set-up-log-transport-services-for-various-levels-or-protection/

249594.1
Dataguard Configuration: LOG_ARCHIVE_CONFIG and VALID_FOR in Oracle 10G
https://metalink.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=249594.1

http://vongates.itpub.net/post/2553/243187

arch vs. lgwr
sync vs. async ( lgwr only )
affirm vs. noaffirm

alter database set standby to maximize protection;
( must use sync, must use standby redo logs )


alter database set standby to maximize performance;

alter database set standby to maximize availibility;

 

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

 

 

*.DB_UNIQUE_NAME=10gstandby

*.LOG_ARCHIVE_CONFIG='DG_CONFIG=(10gpri,10gstandby)'

*.LOG_ARCHIVE_DEST_1='LOCATION=/archlog2/10gstandby/ VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=10gpri'

*.LOG_ARCHIVE_DEST_2='SERVICE=dbpri LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=10gpri'

*.LOG_ARCHIVE_DEST_STATE_1=ENABLE
*.LOG_ARCHIVE_DEST_STATE_2=ENABLE

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

*.FAL_SERVER=dbpri
*.FAL_CLIENT=dbstandby

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

*.DB_FILE_NAME_CONVERT=
'/data1/powererp/','/data13/powererp/',
'/data2/powererp/','/data13/powererp/',
'/data3/powererp/','/data13/powererp/',
'/data4/powererp/','/data14/powererp/',
'/data5/powererp/','/data14/powererp/',
'/data6/powererp/','/data14/powererp/',
'/data1/olddata/','/data13/olddata/data1/',
'/data2/olddata/','/data13/olddata/data2/',
'/data3/olddata/','/data13/olddata/data3/',
'/data4/olddata/','/data14/olddata/data4/',
'/data5/olddata/','/data14/olddata/data5/',
'/data6/olddata/','/data14/olddata/data6/',
'/data1/oradata/ora8/','/data13/oradata/ora8/',
'/data2/oradata/ora8/','/data13/oradata/ora8/',
'/data3/oradata/ora8/','/data14/oradata/ora8/',
'/data1/timms/','/data13/timms/',
'/data6/statspack/','/data14/statspack/'

*.LOG_FILE_NAME_CONVERT=
'/archlog/10gpri/','/archlog2/10gstandby/'

*.STANDBY_FILE_MANAGEMENT=AUTO

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

ocm8  Configure the network environment to allow communication between the standby database and the primary database
https://shenh.tripod.com/Oracleblog/index.blog/1825061/ocm8-configure-the-network-environment-to-allow-communication-between-the-standby-database-and-the-primary-database/

global_db_name_dgrmgrl.domain 

configure static double service names: 

 

 

ocm8  Open the physical standby database in a "ready-only" state
https://shenh.tripod.com/Oracleblog/index.blog/1825062/ocm8-open-the-physical-standby-database-in-a-readyonly-state/


http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10823/manage_ps.htm#1017113

http://www.databasejournal.com/features/oracle/article.php/3682421

1):
SQL> startup nomount pfile=/export/home/oracle/admin/SEAN/pfile/initSEAN.standby
SQL> atler database mount standby database;

2):
SQL> recover standby database;
AUTO

SQL> alter database open read only;

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

put it back in normal standby mount state

SQL> shutdown immediate;
SQL> startup nomount pfile=/export/home/oracle/admin/SEAN/pfile/initSEAN.standby
SQL> atler database mount standby database;

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


SQL> alter system set db_recovery_file_dest_size=2g scope=both;
SQL> alter system set db_recovery_file_dest='/u01/app/oracle/flashback' scope=both;

SQL> shutdown immediate;
SQL> startup mount;
SQL> alter database flashback on;

Stop redo apply to the standby
SQL> alter database recover managed standby database cancel;

Create a restore point on the standby
SQL> create restore point Before_App_Test guarantee flashback database;

SQL> alter system archive log current;

Stop logfile transfer
SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=DEFER;

Activate the physical standby database.
SQL> ALTER DATABASE ACTIVATE STANDBY DATABASE;

Startup mount force the standby
SQL> STARTUP MOUNT FORCE;

Set the standby protection mode to maximum performance
SQL> alter database set standby database to maximize performance;

SQL> ALTER DATABASE OPEN;


SQL> connect avargas/oracle
Connected.
SQL> create table myusers as select * from dba_users;
Table created.
SQL> insert into myusers select * from myusers;
22 rows created.
SQL> /
44 rows created.
SQL> /
88 rows created.
SQL> /
176 rows created.

-- ------------------------------
SQL> startup mount force;
SQL> flashback database to restore point before_app_test;
SQL> alter database convert to physical standby;

SQL> STARTUP MOUNT FORCE;

Put the standby database on recover mode.
SQL> alter database recover managed standby database disconnect;

Enable archive log shipping to the standby
SQL> alter system set log_archive_dest_state_2=enable;

ocm8 Perform a switchover operation and a failover operation
https://shenh.tripod.com/Oracleblog/index.blog/1825063/ocm8-perform-a-switchover-operation-and-a-failover-operation/


1): switchover
sql>alter database commit to switchover to physical standby;
sql>alter database commit to switchover to logical standby;

primary to standby:
a): ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY WITH SESSION SHUTDOWN WAIT;

b): ALTER DATABASE COMMIT TO SWITCHOVER TO LOGICAL STANDBY;

SQL> SHUTDOWN IMMEDIATE;
SQL> STARTUP NOMOUNT;
SQL> ALTER DATABASE MOUNT STANDBY DATABASE;
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT;

standby to primary:
SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN WAIT;
SQL> SHUTDOWN;
SQL> STARTUP;


2): failover

SQL> ALTER DATABASE ACTIVATE PHYSICAL STANDBY
DATABASE;

SQL> ALTER DATABASE ACTIVATE LOGICAL STANDBY
DATABASE;

Failover for Physical Standby Databases Using SQL
To perform failover for physical standby databases using SQL:

1. Initiate the failover operation on the standby database. If a failure occurs at the
primary database, a failover allows you to salvage incomplete standby redo logs
using the following statement:
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE
FINISH;

2. Convert the physical standby database to the primary role. You must now change the
standby database into the new primary database by issuing the following statement:
SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

3. Register the missing redo logs. Once the archived standby redo logs have been
received and recovered on all destinations, the other standby databases are ready to
receive redo logs from the new primary database. To register the copied archived
redo logs, issue the following statement on each standby database:
ALTER DATABASE REGISTER
LOGFILE ’/standby/arch_dest/arch_1_101.arc’;

ocm8  Implement Data Guard
https://shenh.tripod.com/Oracleblog/index.blog/1825064/ocm8-implement-data-guard/

 


Posted by shenh at 11:33 PM EST
Updated: Wednesday, 7 January 2009 12:34 AM EST
OCM 7: RAC and ASM

7. Real Application Clusters
ocm7  Install Oracle Clusterware
https://shenh.tripod.com/Oracleblog/index.blog/1825049/ocm7-install-cluster-ready-services/ 

./runclufy.sh stage -pre crsinst -n node1,node2 -orainv dba

installing crs:
cd /u01/stage/10gR2/clusterware

./runInstaller

...............................

RAC patch for 10.2.4:

run the following script:
  CRS_home/install/root102.sh 

...............................

sh orainstRoot.sh
sh root.sh

...............................

./runcluvfy.sh stage -post crsinst -n node1,node2

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

 10gr1:

/etc/init.d/init.crs start #start

/etc/init.d/init.crs stop #stop

/etc/init.d/init.crs enable #enable

/etc/init.d/init.crs disable #disable

10gR2:

crsctl stop crs

crsctl start crs

crsctl enable crs

crsctl disable crs

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

 

crsctl check crs
crsctl check install -wait 600

crs_stat -h
crs_stat -t

olsnodes [-n] [-l] [-v] [-g]

oifcfg getif

oifcfg delif -global


vipca

gsdctl start
gsdctl stat

clscfg:

cemutlo -n: display cluster name
cemutlo -w: display cluster version number

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

ocrcheck

ocrdump

ocrconfig

ocrconfig -showbackup
ocrconfig -backuploc <dirname>

ocrdump>
ocrconfig -restore <filename>

ocrconfig -import <filename>
ocrconfig -export <filename>


change ocr location:
ocrconfig -replace ocrmirror '/ocfs2/ocr2.dbf'
ocrconfig -replace ocr       '/ocfs1/ocr_new.dbf'

voting disk:
crsctl query  css votedisk
crsctl delete css votedisk <filename>
crsctl add    css votedisk <filename>

backup of voting disk:
dd if=voting_disk_name of=backup_file_name

recover:
dd if=backup_file_name of=voting_disk_name

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

 ocrconfig

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


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

/etc/sysconfig/rawdevices file:
/dev/raw/raw1 /dev/sdb1

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

/etc/init.d/rawdevices restart

raw -qa

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

hangcheck-timer:

/sbin/insmod hangcheck-timer hangcheck_tick=30 hangcheck_margin=180

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

stage list
./runcluvfy stage -list

./runcluvfy.sh stage -post hwos -n node1,node2,node2 -verbose

component list:
./runcluvfy comp -list
./runcluvfy.sh stage -pre crsinst -n node1,node2,node3 -orainv dba

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

files:
lock file:
/etc/oracle/scls_scr/<hostname>/root/cssnorun

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

ocm7  Install the Oracle Database 10g software
https://shenh.tripod.com/Oracleblog/index.blog/1825050/ocm7-install-the-oracle-database-10g-software/ 

installing db software:
./runcluvfy.sh stage -pre dbinst -n node1,node2 -osdba dba

cd /u01/stage/10gR2/
./runInstaller

.. ..............................

root.sh

-- ------------------------------
create db:
./runcluvfy.sh stage -pre dbcfg -n node1,node2 -d /u01/app/oracle/product/10g
./dbca &

ocm7  Implement ASM failure groups
https://shenh.tripod.com/Oracleblog/index.blog/1825051/ocm7-implement-asm-failure-groups/

external: 1 disk

normal: 2 disks

high: 3 disks

http://www.globusz.com/ebooks/Oracle/00000020.htm

ocm7  Create and manage as ASM instance
https://shenh.tripod.com/Oracleblog/index.blog/1825052/ocm7-create-and-manage-as-asm-instance/ 

1): using dbca to create an asm instance 

AU: Allocation Unit ( 1M default, uniform for whole ASM DB in 10g, can vary in 11g )


INSTANCE_TYPE=ASM
ASM_POWER_LIMIT=1 ( default 1 )  ( 0 ~ 1 ) used for rebalance )
ASM_DISKSTRING ='/dev/rdsk/*s1', '/dev/rdsk/c1*
ASM_DISKGROUPS=

Oracle10g New Features: ASM
http://www.itpub.net/156928.html
http://developer.ccidnet.com/art/322/20030627/52257_1.html

ocm7  Create and manage ASM disk groups
https://shenh.tripod.com/Oracleblog/index.blog/1825053/ocm7-create-and-manage-asm-disk-groups/


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

diskground:
CREATE DISKGROUP DG1 NORMAL REDUNDANCY
FAILGROUP FLGRP1 DISK
'/dev/raw/raw3',
'/dev/raw/raw4',
FAILGROUP FLGRP2 DISK
'/dev/raw/raw5',
'/dev/raw/raw6',

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

SQL> STARTUP NOMOUNT

SQL> CREATE DISKGROUP dgroup1 NORMAL REDUNDANCY

FAILGROUP controller1 DISK
'/devices/diska1' name testdisk size 100G,
'/devices/diska2',
'/devices/diska3'
FAILGROUP controller2 DISK
'/devices/diskb1',
'/devices/diskb2',
'/devices/diskb3'

ALTER DISKGROUP dgroup1 ADD DISK
'/devices/diska5' NAME diska5,
'/devices/diska6' NAME diska6;

ALTER DISKGROUP dgroup1 ADD DISK
'/devices/diska*';

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

 

ALTER DISKGROUP DG1 ADD DISK 'dev/raw/raw7' NAME disk5;

ALTER DISKGROUP DG1 DROP DISK 'dev/raw/raw7';

ALTER DISKGROUP DG1 RESIZE DISK 'dev'raw'raw6' SIZE 500M;

ALTER DISKGROUP DG1 REBALANCE POWER 5 WAIT;


select path, reads, writes, read_time, write_time,
read_time/decode(reads,0,1,reads) "AVGRDTIME",
write_time/decode(writes,0,1,writes) "AVGWRTIME",
from v$asm_disk_stat;

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

asm tools:

asmcmd
asmcmd>cd|du|exit|help|ls|find|mkalias|lsct|lsdg|mkdir|rm|rmalias


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

asm ftp:

ftp
ftp> eopm node1 7777

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

/etc/init.d/oracleasm configure


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


V$ASM_OPERATION

ocm7  Configure ASM for the shared disks, and create a clustered database
https://shenh.tripod.com/Oracleblog/index.blog/1825054/ocm7-configure-asm-for-the-shared-disks-and-create-a-clustered-database/

 

step 1):  ./runcluvfy.sh stage -pre dbcfg -n node1,node2 -d /u01/app/oracle/product/10g

step 2): dbca &  then follow gui.

 

ocm7  Configure archiving
https://shenh.tripod.com/Oracleblog/index.blog/1825056/ocm7configure-archiving/

 

http://www.idevelopment.info/data/Oracle/DBA_tips/Oracle11gRAC/CLUSTER_30.shtml

Login to one of the nodes (i.e. linux1) and disable the cluster instance parameter by setting cluster_database to FALSE from the current instance:
$ sqlplus "/ as sysdba"
SQL> alter system set cluster_database=false scope=spfile sid='orcl1';

Shutdown all instances accessing the clustered database:
$ srvctl stop database -d orcl

Using the local instance, MOUNT the database:
$ sqlplus "/ as sysdba"
SQL> startup mount

Enable archiving:
SQL> alter database archivelog;

Re-enable support for clustering by modifying the instance parameter cluster_database to TRUE from the current instance:
SQL> alter system set cluster_database=true scope=spfile sid='orcl1';

Shutdown the local instance:
SQL> shutdown immediate

Bring all instance back up using srvctl:
$ srvctl start database -d orcl

(Optional) Bring any services (i.e. TAF) back up using srvctl:
$ srvctl start service -d orcl

Login to the local instance and verify Archive Log Mode is enabled:
$ sqlplus "/ as sysdba"
SQL> archive log list
Database log mode              Archive Mode
Automatic archival             Enabled
Archive destination            USE_DB_RECOVERY_FILE_DEST
Oldest online log sequence     83
Next log sequence to archive   84
Current log sequence           84
After enabling Archive Log Mode, each instance in the RAC configuration can automatically archive redologs!

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

http://archive.netbsd.se/?ml=oracle-l&a=2006-04&t=1960607

Steps:
0. ALTER SYSTEM SET CLUSTER_DATABASE=FALSE SCOPE=SPFILE;
1. Shutdown all instances cleanly (normal, immediate, transactional)
2. "Startup mount" one instance
3. ALTER DATABASE ARCHIVELOG;
4. ALTER DATABASE OPEN;
5. ALTER SYSTEM SET CLUSTER_DATABASE=TRUE;
6. SHUTDOWN IMMEDIATE
7. Startup all the instances. Do not forget to set log_archive_dest_n
for all instances. Otherwise you'll find archived logs in $ORACLE_HOME/dbs

NOTE: do not forget to specify %t or %T in log_archive_format. That
would help to distinguish logs from different instances.

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

ALTER SYSTEM SET cluster_database=FALSE SCOPE=spfile;


STARTUP MOUNT;
ALTER DATABASE ARCHIVELOG;
ALTER SYSTEM SET cluster_database=TRUE SCOPE=spfile;
SHUTDOWN IMMEDIATE;

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

Starting with 10.2 you no longer need to modify the CLUSTER_DATABASE parameter setting to
change the archiving mode in RAC. You can change archivelog mode as long as
the database is mounted in the local instance and not open in any instances.

http://el-caro.blogspot.com/2007/01/rac-archivelog-mode-and-clusterdatabase.html

elephant-> srvctl stop database -d F8902PRD

elephant-> srvctl start instance -d F8902PRD -i F8902PRD1 -o mount
elephant-> srvctl status database -d F8902PRD
Instance F8902PRD1 is running on node elephant
Instance F8902PRD2 is not running on node rhino
Instance F8902PRD3 is not running on node hippo

SQL> show parameter cluster_database

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
cluster_database boolean TRUE
cluster_database_instances integer 3
SQL> alter database noarchivelog;

elephant-> srvctl stop instance -d F8902PRD -i F8902PRD1
Now lets try to change back to archivelog mode by mounting the database from more
than one instance.

elephant-> srvctl start instance -d F8902PRD -i F8902PRD1 -o mount
elephant-> srvctl start instance -d F8902PRD -i F8902PRD2 -o mount
elephant-> srvctl status database -d F8902PRD
Instance F8902PRD1 is running on node elephant
Instance F8902PRD2 is running on node rhino
Instance F8902PRD3 is not running on node hippo

SQL> show parameter cluster_database

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
cluster_database boolean TRUE
cluster_database_instances integer 3
SQL> alter database archivelog;

Database altered.

SQL> archive log list
Database log mode Archive Mode
Automatic archival Enabled
Archive destination /u03/backup/F8902PRD/arch/
Oldest online log sequence 1103
Next log sequence to archive 1104
Current log sequence 1104


elephant-> srvctl stop database -d F8902PRD
elephant-> srvctl start instance -d F8902PRD -i F8902PRD1 -o mount
elephant-> srvctl start instance -d F8902PRD -i F8902PRD2 -o mount
elephant-> srvctl start instance -d F8902PRD -i F8902PRD2 -o open ==> I made a typo here. It should have been F8902PRD3
instead of F8902PRD2 but notice srvctl does not generate any errors. So u don't know if instance 2 has actually opened the database.
elephant-> srvctl start instance -d F8902PRD -i F8902PRD3 -o open

SQL> select inst_id,open_mode from gv$database;

INST_ID OPEN_MODE
---------- ----------
1 MOUNTED
2 MOUNTED
3 READ WRITE

So instance 3 has the db open while instances 1 and 2 have just mounted the database.

SQL> alter database noarchivelog;
alter database noarchivelog
*
ERROR at line 1:
ORA-01126: database must be mounted in this instance and not open in any
instance


*****************************************************************************************
However if you need to recreate the controlfile you need to set cluster_database to false

elephant-> srvctl stop database -d F8902PRD
elephant-> srvctl start instance -d F8902PRD -i F8902PRD1 -o nomount
elephant-> srvctl status database -d F8902PRD
Instance F8902PRD1 is running on node elephant
Instance F8902PRD2 is not running on node rhino
Instance F8902PRD3 is not running on node hippo

SQL> select inst_id,DATABASE_STATUS from gv$instance;

INST_ID DATABASE_STATUS
---------- -----------------
1 ACTIVE

SQL> @controlfile.sql
CREATE CONTROLFILE REUSE DATABASE "F8902PRD" NORESETLOGS ARCHIVELOG
*
ERROR at line 1:
ORA-01503: CREATE CONTROLFILE failed
ORA-12720: operation requires database is in EXCLUSIVE mode

 

 

 

ocm7  Configure Services with a primary instance and an available instance
https://shenh.tripod.com/Oracleblog/index.blog/1825055/ocm7-configure-services-with-a-primary-instance-and-an-available-instance/

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


crsctl -t

 

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

srvctl -h

srvctl config database

srvctl status databse -d

srvctl status nodeapps -n node1

srvctl start database -d prod
srvctl stop  database -d prod

srvctl stop  database -d prod -o immediate
srvctl start database -d prod -o force

srvctl stop database -d prod -i instance prod3

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

 

 

select name, network_name, creation_date, goal, dtp, aq_ha_notification, clb_goal from v$services;

srvctl config service -d prod -s sales.mydomain.com

sales.mydomain.com PREF: prod1 AVAIL: prod2

four ways to manage services:
1): DBCA

2): EM web tool

3): DBMS_SERVICES.*

4): server control ( srvctl )

example:
srvctl add service -d database_name -s service_name -r preferred_instance -a available_instance -P taf_policy
 
srvctl add service -d prod -s test -r prod,prod2 -a prod3
srvctl start service -d prod -s test

execute dbms_service.create_service ( service_name =>'sales.mydomain.com' -
,aq_ha_notifications => true -
,failover_method     => dbms_service.failover_method_basic -
,failover_type       => dbms_service.failover_type_select -
,failover_retries    => 180 -
,failover_delay      => 5 -
, clb_goal           => dbms_service.clb_goal_long );

execute dbms_service.start_service ( 'sales.mydomain.com' );

startup and shutdown sequence:


srvctl stop service -d db_name [-s service_name_list [-i inst_name]]

srvctl stop instance -d db_name -i inst_name

srvctl stop database -d db_name

srvctl stop asm -n node

srvctl stop listener -n node [-l listenername]

srvctl stop nodeapps -n node

CRS_home/bin/crsctl stop crs


Posted by shenh at 11:32 PM EST
Updated: Wednesday, 7 January 2009 12:45 AM EST
OCM 6: Performance Management

6. Performance Management
ocm6  Install Statspack
https://shenh.tripod.com/Oracleblog/index.blog/1825027/ocm6-install-statspack/

http://ist.uwaterloo.ca/~baumbach/ORACLEnotes/ST_statspack.html

sqlplus perfstat/perfstat
exec statspack.snap; -- Take a performance snapshots
exec statspack.snap;

-- Get a list of snapshots
select SNAP_ID, SNAP_TIME from STATS$SNAPSHOT;

@spreport.sql -- Enter two snapshot id's for difference report

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


spauto.sql - Schedule a dbms_job to automate the collection of Statspack statistics.
spcreate.sql - Installs the Statspack user, tables and package on a database (Run as SYS).
spdrop.sql - Deinstall Statspack from database (Run as SYS).
sppurge.sql - Deletes snapshots which fall between the begin and end range of Snapshot Id's specified.
spuexp.par - Export parameter file i.e. exp userid=perfstat/perfstat parfile=spuexp.par.
spreport.sql - Report on differences between values recorded in two snapshots.
sptrunc.sql - Removes ALL data from Statspack tables.


execute statspack.snap (i_snap_level=>5, i_modify_parameter=>'true');

execute statspack.modify_statspack_parameter -
(i_snap_level=>5, i_buffer_gets_th=>10000, i_disk_reads_th=>1000);

execute statspack.snap(i_session_id=>3);



sqlplus sys
--
-- Install Statspack
-- Enter tablespace names when prompted
--
@?/rdbms/admin/spcreate.sql
--
-- Drop Statspack
-- Reverse of spcreate.sql
--
-- @?/rdbms/admin/spdrop.sql
--

sqlplus perfstat
--
-- Take a performance snapshot
--
execute statspack.snap;
--
-- Get a list of snapshots
--
column snap_time format a21
select snap_id,to_char(snap_time,'MON dd, yyyy hh24:mm:ss') snap_time
from sp$snapshot;
--

sqlplus perfstat
--
-- Statspack Report
--
-- You will be prompted for:
-- a) The beginning snapshot Id
-- b) The ending snapshot Id
-- c) The name of the report text file to be created
--
-- The report will then calculate and print ratios,
-- increases etc. for all statistics between the two snapshot periods.
--
--
-- Get a list of snapshots to report on:
--
column snap_time format a21
select snap_id,to_char(snap_time,'MON dd, yyyy hh24:mm:ss') snap_time
from sp$snapshot;
--
-- Run the Statspack report:
--
@?/rdbms/admin/spreport.sql
--

ocm6  Adjust the default interval for statistics collection
https://shenh.tripod.com/Oracleblog/index.blog/1825028/ocm6-adjust-the-default-interval-for-statistics-collection/

1. maybe for statspack

sql> execute statspack.modify_statspack_parameter -

( i_snap_level=>5,i_buffer_gets_th=>100000, i_modify_parameter=>'true');

sql> execute statspack.snap;

sql> @ORACLE_HOME/rdbms/admin/spreport ; ( sprepsql)

 

2. for awr
execute dbms_workload_repository.create_snapshot;

select snap_interval, retention
from dba_hist_wr_control;

-- retention: 2 days
-- interval: 20 minutes
begin
dbms_workload_repository.modify_snapshot_settings (
interval => 20,
retention => 2*24*60
);
end;

rem -- change ADDM sensitiveness back to normal
exec dbms_advisor.set_default_task_parameter ( 'ADDM', 'DB_ACTIVITY_MIN', 300);

more sensitive:
exec dbms_advisor.set_default_task_parameter ( 'ADDM', 'DB_ACTIVITY_MIN', 30);

ocm6  Customize the events that are monitored
https://shenh.tripod.com/Oracleblog/index.blog/1825030/ocm6-customize-the-events-that-are-monitored/


best:
http://www.globusz.com/ebooks/Oracle/00000013.htm

SELECT ADVISOR_NAME, PARAMETER_VALUE
FROM DBA_ADVISOR_DEF_PARAMETERS

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

Oracle assumes the value of the parameter (not intialization parameter) DBIO_EXPECTED is 10 milliseconds.

SELECT PARAMETER_VALUE
FROM DBA_ADVISOR_DEF_PARAMETERS
WHERE ADVISOR_NAME='ADDM'
AND PARAMETER_NAME='DBIO_EXPECTED'

If your hardware is significantly different, you can set the parameter value one time for all subsequent ADDM executions:

DBMS_ADVISOR.SET_DEFAULT_TASK_PARAMETER('ADDM','DBIO_EXPECTED', 8000); 
 

 

ocm6  Use ADDM to analyze statistics and to identify performance bottlenecks and fix them
https://shenh.tripod.com/Oracleblog/index.blog/1825031/ocm6-use-addm-to-analyze-statistics-and-to-identify-performance-bottlenecks-and-fix-them/


http://download-west.oracle.com/docs/cd/B13789_01/appdev.101/b10802/d_advis.htm


BEGIN
-- Create an ADDM task.
DBMS_ADVISOR.create_task (
advisor_name => 'ADDM',
task_name => '970_1032_AWR_SNAPSHOT',
task_desc => 'Advisor for snapshots 970 to 1032.');

-- Set the start and end snapshots.
DBMS_ADVISOR.set_task_parameter (
task_name => '970_1032_AWR_SNAPSHOT',
parameter => 'START_SNAPSHOT',
value => 970);

DBMS_ADVISOR.set_task_parameter (
task_name => '970_1032_AWR_SNAPSHOT',
parameter => 'END_SNAPSHOT',
value => 1032);

-- Execute the task.
DBMS_ADVISOR.execute_task(task_name => '970_1032_AWR_SNAPSHOT');
END;
/

-- Display the report.
SET LONG 100000
SET PAGESIZE 50000
SELECT DBMS_ADVISOR.get_task_report('970_1032_AWR_SNAPSHOT') AS report
FROM dual;
SET PAGESIZE 24

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

The relevant AWR snapshots can be identified using the DBA_HIST_SNAPSHOT view.

Related Views
The following views can be used to display the ADDM output without using Enterprise Manager or the GET_TASK_REPORT function:

DBA_ADVISOR_TASKS - Basic information about existing tasks.
DBA_ADVISOR_LOG - Status information about existing tasks.
DBA_ADVISOR_FINDINGS - Findings identified for an existing task.
DBA_ADVISOR_RECOMMENDATIONS - Recommendations for the problems identified by an existing task.

-- -----------------------------------------------------------
@my_addmrpt.sql
@addmrpt.sql

ocm6  Implement automatic shared memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825032/ocm6-implement-automatic-shared-memory-management/

good:
http://www.oracleadvice.com/10g/10g_autosharedmemory.htm


show parameter sga

show parameter pga

sga_target=4096M

To enable automatic shared memory management, set sga_target to a non-zero value up to the value of sga_max_size. The default value is 0, meaning automatic shared memory management is disabled.

Oracle will automatically tune the following SGA components:
• Db_cache_size # default 0 when sga_target > 0
• Shared_pool_size # default 0 when sga_target > 0
• Large_pool_size # default 0 when sga_target > 0
• Java_pool_size # default 0 when sga_target > 0

You must manually tune
• Log_buffer
• Keep & recycle buffer caches
• Non-standard block size buffer caches
• The new streams pool
• The new ASM storage management buffer cache

It is important to understand the rules that Oracle uses to allocate memory from sga_target.

1. If sga_target is set higher than sga_max_size, then sga_max_size will be adjusted upwards to match sga_target.
2. Deduct an overhead for fixed-size SGA structures (Eg. the new ASH - Active Session History buffer)
3. Deduct the size of the manually-configured SGA areas (log_buffer, keep & recycle pools etc.)
4. The remaining shared memory is then divided between db_cache_size, shared_pool_size, large_pool_size and java_pool_size
5. If the auto-tune parameters have been assigned values, then these are used as a minimum size. Use the default of 0 to allow Oracle to determine an appropriate size.
6. When Oracle must determine a size for the auto-tune parameters it starts off low, using a function based on cpu_count, and gradually increases the size to an optimum value. Each time it does this, it will save the new value in the SPFILE to use as a minimum the next time the instance is started. If an init.ora parameter file is used instead of an SPFILE, then performance could suffer slightly more than usual shortly after the instance is restarted.

The current values of auto-tune parameters can be viewed in V$SGA_DYNAMIC_CONTENTS

ocm6  Tune memory using manual memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825034/ocm6-tune-memory-using-manual-memory-management/

5. If the auto-tune parameters have been assigned values, then these are used as a minimum size. Use the default of 0 to allow Oracle to determine an appropriate size.

ocm6  Monitor and tune SGA areas that are not automatically tuned
https://shenh.tripod.com/Oracleblog/index.blog/1825034/ocm6-tune-memory-using-manual-memory-management/


• Log_buffer
• Keep & recycle buffer caches
• Non-standard block size buffer caches
• The new streams pool
• The new ASM storage management buffer cache

ocm6  Implement automatic SQL execution memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825036/ocm6-implement-automatic-sql-execution-memory-management/sql

memory:  shared_pool_size and large_pool_size for shared_server

shared_pool_size
shared_pool_reserved_size
open_cursors
session_cached_cursors
cursor_space_for_time
cursor_sharing

-- ------------------------------------------------------------------------
select namespace, gethitratio from v$librarycache;

select * frin v$sys_time_model  where stat_name like '%parse%;
select * frin v$sess_time_model where stat_name like '%parse%;

select * from v$sqlstats;

select v$db_object_cache;

-- ------------------------------------------------------------------------
ora-04031: unable to allocate string bytes of shared memory
Cause:    More shared memory is needed than was allocated in the shared pool.
Action:    If the shared pool is out of memory,
        either use the dbms_shared_pool package to pin large packages,
        reduce your use of shared memory, or increase the amount of
        available shared memory by increasing the value of the INIT.ORA
        parameters "shared_pool_reserved_size" and "shared_pool_size".

        If the large pool is out of memory,
        increase the INIT.ORA parameter "large_pool_size".

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

dbms_shared_pool.keep ( 'package_name' );

@dbmspool.sql
@prvtpool.plb


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

init.ora
cursor_sharing=exact|similar|force

avoid hard parse
avoid soft parse

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

 

sga_max

sga_target

• Db_cache_size # default 0 when sga_target > 0
• Shared_pool_size # default 0 when sga_target > 0
• Large_pool_size # default 0 when sga_target > 0
• Java_pool_size # default 0 when sga_target > 0

ocm6  Tune the PGA using work area size parameters
https://shenh.tripod.com/Oracleblog/index.blog/1825037/ocm6-tune-the-pga-using-work-area-size-parameters/ 

pga_aggregate_size=700m

workarea_size_policy =AUTO|manual

--> sort_area_size 

ocm6  Use the PGA Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825038/ocm6-use-the-pga-advisor/ 

best picture for DB control OEM:
http://www.dba-oracle.com/oracle10g_tuning/t_memory_advisor.htm


http://download.oracle.com/docs/cd/B19306_01/server.102/b14196/montune003.htm

From the Home Page, under related links, click Advisor Central, then Click Memory Advisor.

ocm6  Create a Database Resource Manager plan with directives (active session count, max execution time)
https://shenh.tripod.com/Oracleblog/index.blog/1825039/ocm6-create-a-database-resource-manager-plan-with-directives/ 

Resource Manager ( active session pool )
http://www.oracle-base.com/articles/10g/ResourceManagerEnhancements10g.php
http://www.oracle-base.com/articles/9i/ResourceManagerEnhancements9i.php
http://www.oracle-base.com/articles/8i/ResourceManager8i.php

DBMS_RESOURCE_MANAGER package.
Dbms_Resource_Manager.Create_Plan_Directive
Dbms_Resource_Manager.Set_Initial_Consumer_Group('web_user', 'web_cg');

Dbms_Resource_Manager_Privs
Dbms_Resource_Manager_Privs.Grant_Switch_Consumer_Group

Dbms_Session.Switch_Current_Consumer_Group

DBA_RSRC_PLANS
DBA_RESRC_PLAN_DIRECTIVES

V$RSRC_CONSUMER_GROUP


ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = hybrid_plan;

SQL> SELECT VALUE FROM V$PARAMETER
SQL> WHERE name = 'resource_manager_plan';
VALUE
---------
PEAKTIME


-- Set users' initial resource groups
DBMS_RESOURCE_MANAGER.SET_INITIAL_CONSUMER_GROUP(
user => 'HR'
,consumer_group => 'OLTP'
);
DBMS_RESOURCE_MANAGER.SET_INITIAL_CONSUMER_GROUP(
user => 'SLSMGR'
,consumer_group => 'DSS'
);


BEGIN
-- Switch the consumer group for a specific session
-- of the HR user (found by querying V$SESSION)
DBMS_RESOURCE_MANAGER.SWITCH_CONSUMER_GROUP_FOR_SESS(
session_id => '17'
,session_serial => '11'
,consumer_group => 'DSS'
);

-- Switch the consumer group for all sessions belonging to
-- the specified users
DBMS_RESOURCE_MANAGER.SWITCH_CONSUMER_GROUP_FOR_USER(
USER => 'SLSMGR'
,consumer_group => 'DSS'
);
DBMS_RESOURCE_MANAGER.SWITCH_CONSUMER_GROUP_FOR_USER(
USER => 'HR'
,consumer_group => 'OLTP'
);
END;
/


http://www.dbasupport.com/oracle/ora9i/DRM.shtml
http://www.dbasupport.com/oracle/ora9i/DRM02.shtml
http://www.dbasupport.com/oracle/ora9i/DRM03_1.shtml
http://www.dbasupport.com/oracle/ora9i/DRM03_2.shtml

== =======================================
http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/dbrm.htm#i1007878

http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/dbrm.htm#sthref3411

http://www.psoug.org/reference/dbms_res_mgr.html

http://www.globusz.com/ebooks/Oracle/00000017.htm

ocm6  Create consumer groups
https://shenh.tripod.com/Oracleblog/index.blog/1825040/ocm6-create-consumer-groups/ 

dbms_resource_manager.create_consumer_group(
consumer_group IN VARCHAR2,
comment IN VARCHAR2,
cpu_mth IN VARCHAR2 DEFAULT 'ROUND-ROBIN');

-- alternate cpu_mth is RUN-TO-COMPLETION


https://twiki.cern.ch/twiki/bin/view/LHCb/Rsrc_alloc

http://www.oraclesource.net/10g/Oracle_10g_System_res_mgr.pdf

http://www.psoug.org/reference/dbms_res_mgr.html

http://www.nocoug.org/download/2002-11/db_consolidation.ppt

http://cdacosta.free.fr/Slides/Visio-upg9i_06_RESS-MAN.pdf

http://www.ss64.com/orap/DBMS_RESOURCE_MANAGER.html

http://www.adp-gmbh.ch/ora/plsql/dbms_resource_manager.html

init.ora
RESOURCE_MANAGER_PLAN='SIEBEL_PLAN';

alter system set resource_manager_plan='SIEBEL_PLAN';
alter system set resource_manager_plan='';

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

plan, consumer group, plan_directive:

dbms_resource_manager.* package:
plan:create,update,delete,cascade
consumer_group:create,update,delete
plan_directive:create,update,delete
pending_area:create, validate, clear, submit
switch: set_initial, switch groups

1. pending area
dbms_resource_manager.create_pending_area
dbms_resource_manager.validate_pending_area
dbms_resource_manager.clear_pending_area
dbms_resource_manager.submit_pending_area

-- tie plan and consumer group
exec dbms_resource_manager.creative_plan_directive -
 ( plan => 'new_plan', -
   group_or_subplan => 'sales', -
   conmment => 'sales groups', -
   cpu_p1 => 60 -
   parallel_degree_limit_p1 => 4, -
   max_idle_time => 600, -
   max_idle_blocker_time => 300 );
-- ----------------------------------------------------

-- tie user and consumer groups:

select username, initial_rsrc_consumer_group
from dba_users;

SQL> exec dbms_resource_manager.set_inital_consumer_group ( -
     user => 'NOEL',
     consumer_group => 'OLTP' );

-- manually switching sessions and users
SQL> exec dbms_resource_manager.switch_consumer_group_for_sess ( -
 SESSION_ID => 'session_id',
 SESSION_SERIAL => 'session serial number ',
 CONSUMER_GROUP => 'group_name' );

SQL> exec dbms_resource_manager.switch_consumer_group_for_user ( -
 USER => 'user name',
 CONSUMER_GROUP => 'group_name' );


-- tie session and consumer groups:
SQL> exec dbms_resource_manager.set_consumer_group_mapping ( -
 dbms_resource_manager.oracle_user, 'scott', 'dev_group' );


SQL> exec dbms_resource_manager.set_consumer_group_mapping ( -
 dbms_resource_manager.client_os_user, 'SAM', 'dev_group' );

-- tie session and consumer groups:
SQL> dbms_resource_manager.set_consumer_group_mapping_pri ( -
  explicit => 1, -
  client_machine => 2, -
  module_name => 3, -
  oracle_iser => 4, -
  service_name => 5, -
  client_os_user => 6, -
  client_program => 7, -
  module_name_action => 8, -
  service_moduile => 9, -
  service_module_action => 10 );

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


10g: switch back after call end

DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE
(
plan => 'Day_Plan' ,
Group_or_subplan => 'DSS_GROUP',
Comment => 'Switch back example',
Switch_group => 'LONGRUN_GROUP',
Switch_time => 600,
Cpu_p1 => 100,
Cpu_p2 => 0,
Switch_back_at_call_end => true
);

DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE
(
Plan => 'Day_Plan',
Group_or_subplan => 'LONGRUN_GROUP',
Comment => 'Switch Back Example',
Cpu_p1 => 0,
Cpu_p2 => 100,
Switch_back_at_call_end => true
);

-- any user session that is idle for more than 400 seconds
   will be forcibly killed by the PMON background process.

DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE
(
Plan => 'DAY_PLAN',
Group_or_subplan =>'DSS_GROUP',
Comment => 'Limit idle time',
Max_idle_time => 400,
Max_idle_blocker_time => 100

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

);

ocm6  Configure consumer group mappings
https://shenh.tripod.com/Oracleblog/index.blog/1825041/ocm6-configure-consumer-group-mappings/ 

-- tie session and consumer groups:
SQL> exec dbms_resource_manager.set_consumer_group_mapping ( -
 dbms_resource_manager.oracle_user, 'scott', 'dev_group' );


SQL> exec dbms_resource_manager.set_consumer_group_mapping ( -
 dbms_resource_manager.client_os_user, 'SAM', 'dev_group' );

-- tie session and consumer groups:
SQL> dbms_resource_manager.set_consumer_group_mapping_pri ( -
  explicit => 1, -
  client_machine => 2, -
  module_name => 3, -
  oracle_iser => 4, -
  service_name => 5, -
  client_os_user => 6, -
  client_program => 7, -
  module_name_action => 8, -
  service_moduile => 9, -
  service_module_action => 10 );


http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/dbrm.htm#i1009380

http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_resmg2.htm#1001822

http://www.dba-oracle.com/concepts/create_pending_area.htm
http://www.praetoriate.com/t_grid_rac_pending_area_syntax.htm



abstract:

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


BEGIN
DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA();

DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'bugdb_plan',
COMMENT => 'Resource plan/method for bug users sessions');

DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Online_group',
COMMENT => 'Resource consumer group/method for online bug users sessions');

DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'bugdb_plan',
GROUP_OR_SUBPLAN => 'Online_group',
COMMENT => 'online bug users sessions at level 1', CPU_P1 => 80, CPU_P2=> 0,
PARALLEL_DEGREE_LIMIT_P1 => 8);

DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA();
DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA();
END;

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

BEGIN
DBMS_RESOURCE_MANAGER.CREATE_PENDING_AREA();
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'bugdb_plan',
COMMENT => 'Resource plan/method for bug users sessions');
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'maildb_plan',
COMMENT => 'Resource plan/method for mail users sessions');
DBMS_RESOURCE_MANAGER.CREATE_PLAN(PLAN => 'mydb_plan',
COMMENT => 'Resource plan/method for bug and mail users sessions');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Online_group',
COMMENT => 'Resource consumer group/method for online bug users sessions');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Batch_group',
COMMENT => 'Resource consumer group/method for batch job bug users sessions');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Bug_Maint_group',
COMMENT => 'Resource consumer group/method for users sessions for bug db maint');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Users_group',
COMMENT => 'Resource consumer group/method for mail users sessions');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Postman_group',
COMMENT => 'Resource consumer group/method for mail postman');
DBMS_RESOURCE_MANAGER.CREATE_CONSUMER_GROUP(CONSUMER_GROUP => 'Mail_Maint_group',
COMMENT => 'Resource consumer group/method for users sessions for mail db maint');
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'bugdb_plan',
GROUP_OR_SUBPLAN => 'Online_group',
COMMENT => 'online bug users sessions at level 1', CPU_P1 => 80, CPU_P2=> 0,
PARALLEL_DEGREE_LIMIT_P1 => 8);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'bugdb_plan',
GROUP_OR_SUBPLAN => 'Batch_group',
COMMENT => 'batch bug users sessions at level 1', CPU_P1 => 20, CPU_P2 => 0,
PARALLEL_DEGREE_LIMIT_P1 => 2);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'bugdb_plan',
GROUP_OR_SUBPLAN => 'Bug_Maint_group',
COMMENT => 'bug maintenance users sessions at level 2', CPU_P1 => 0, CPU_P2 => 100,
PARALLEL_DEGREE_LIMIT_P1 => 3);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'bugdb_plan',
GROUP_OR_SUBPLAN => 'OTHER_GROUPS',
COMMENT => 'all other users sessions at level 3', CPU_P1 => 0, CPU_P2 => 0,
CPU_P3 => 100);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'maildb_plan',
GROUP_OR_SUBPLAN => 'Postman_group',
COMMENT => 'mail postman at level 1', CPU_P1 => 40, CPU_P2 => 0,
PARALLEL_DEGREE_LIMIT_P1 => 4);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'maildb_plan',
GROUP_OR_SUBPLAN => 'Users_group',
COMMENT => 'mail users sessions at level 2', CPU_P1 => 0, CPU_P2 => 80,
PARALLEL_DEGREE_LIMIT_P1 => 4);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'maildb_plan',
GROUP_OR_SUBPLAN => 'Mail_Maint_group',
COMMENT => 'mail maintenance users sessions at level 2', CPU_P1 => 0, CPU_P2 => 20,
PARALLEL_DEGREE_LIMIT_P1 => 2);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'maildb_plan',
GROUP_OR_SUBPLAN => 'OTHER_GROUPS',
COMMENT => 'all other users sessions at level 3', CPU_P1 => 0, CPU_P2 => 0,
CPU_P3 => 100);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'mydb_plan',
GROUP_OR_SUBPLAN => 'maildb_plan',
COMMENT=> 'all mail users sessions at level 1', CPU_P1 => 30);
DBMS_RESOURCE_MANAGER.CREATE_PLAN_DIRECTIVE(PLAN => 'mydb_plan',
GROUP_OR_SUBPLAN => 'bugdb_plan',
COMMENT => 'all bug users sessions at level 1', CPU_P1 => 70);
DBMS_RESOURCE_MANAGER.VALIDATE_PENDING_AREA();
DBMS_RESOURCE_MANAGER.SUBMIT_PENDING_AREA();
END;

ocm6  Manage Services
https://shenh.tripod.com/Oracleblog/index.blog/1825042/ocm6-manage-services-oracle-database-10g-release-2/ 

show parameter service_names

or RAC

ocm6  Create and manage objects to accommodate different data access methods (schema tuning)
https://shenh.tripod.com/Oracleblog/index.blog/1825043/ocm6-create-and-manage-objects-to-accommodate-different-data-access-methods-schema-tuning/

 

ocm6  Use the SQL Tuning Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825044/ocm6-use-the-sql-tuning-advisor/ 

DECLARE
l_sql_tune_task_id VARCHAR2(100);
BEGIN
l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task (
sql_id => '2uvvchaax0wzx',
scope => DBMS_SQLTUNE.scope_comprehensive,
time_limit => 600,
task_name => 'tuning_task_1',
description => 'Tuning task for statement 2uvvchaax0wzx');
DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id);
END;
/

EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => 'tuning_task_1');

-- EXEC DBMS_SQLTUNE.reset_tuning_task (task_name => 'tuning_task_1');

SELECT task_name, status FROM dba_advisor_log WHERE owner = 'LINK';

SET LONG 10000;
SET PAGESIZE 1000
SET LINESIZE 200
SELECT DBMS_SQLTUNE.report_tuning_task('tuning_task_1') AS recommendations FROM dual;
SET PAGESIZE 24

execute dbms_sqltune.accept_sql_profile(task_name => 'tuning_task_1', replace => TRUE);


--> SQL profile "SYS_SQLPROF_0144aaae2c088000" used for this statement

-- ----------------------------------------------------------
SELECT decode(r.type,
'STATISTICS', 1,
'SQL PROFILE', 2,
'INDEX', 3, 4) as type,
count(*)
FROM dba_advisor_findings f,
dba_advisor_recommendations r
WHERE f.task_id = r.task_id AND r.task_id = :tid AND
f.finding_id = r.finding_id AND
f.object_id = :oid
GROUP BY r.type
ORDER BY type
/

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

begin
dbms_sqltune.accept_sql_profile (
task_name => 'FOLIO_COUNT',
name => 'FOLIO_COUNT_PROFILE'
description => 'Folio Count Profile',
category => 'FOLIO_COUNT');
end;



DBMS_SQLTUNE.drop_tuning_task (task_name => 'tuning_task_1');

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


10G New Features Series 2: Introduction to SQL Tuning Advisor
http://www.itpub.net/331977.html

#
# Cleanup ADDM snapshot settings
#
sqlplus -s /NOLOG <<EOF>> /tmp/cleanup_dina.log 2>&1

connect / as sysdba

rem -- change INTERVAL setting to 30 minute
execute dbms_workload_repository.modify_snapshot_settings(interval => 60);

rem -- change ADDM sensitiveness back to normal
exec dbms_advisor.set_default_task_parameter('ADDM','DB_ACTIVITY_MIN',300);

connect sh/sh

drop index sales_time_idx;

create bitmap index sales_time_bix
on sales(time_id)
tablespace example
local nologging compute statistics;


EOF

#
# Cleanup sql profile
#
sqlplus -s /NOLOG <<EOF> /tmp/cleanup_dina.log 2>&1

connect / as sysdba

set head off
set timing off
set feedback off;
set pagesize 0

spool /tmp/drop_dyn.sql;

select q'#connect / as sysdba;#' from dual;

select q'#execute dbms_sqltune.drop_sql_profile('#' || name || q'#') ;#'
from dba_sql_profiles ;

select q'#execute dbms_advisor.delete_task('#' || task_name || q'#') ;#'
from user_advisor_tasks
where CREATED > SYSDATE-(1/24);

select q'#connect system/oracle;#' from dual;

select q'#execute dbms_advisor.delete_task('#' || task_name || q'#') ;#'
from user_advisor_tasks
where CREATED > SYSDATE-(1/24);

spool off

@/tmp/drop_dyn.sql

EOF

ocm6  Use the SQL Access Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825045/ocm6-use-the-sql-access-advisor/

http://www.oracle.com/technology/oramag/oracle/04-jul/o44tech_talking.html


http://www.oracle-base.com/articles/10g/SQLAccessAdvisor10g.php

http://youngcow.net/doc/oracle10g/server.102/b14211/advisor.htm

Grid Control: Advisor Central --> SQL Access Advisor -->

SQL Access Advisor:
Mostly recommend for index and Materialized Views
 

ocm6  Gather Optimizer statistics
https://shenh.tripod.com/Oracleblog/index.blog/1825046/ocm6-gather-optimizer-statistics/

http://www.akadia.com/services/ora_gather_statistics.html

http://www.psoug.org/reference/dbms_stats.html

http://www.mcs.csueastbay.edu/support/oracle/doc/10.2/server.102/b14211/stats.htm

http://decipherinfosys.wordpress.com/2008/02/19/exportimport-of-optimizer-statistics-in-oracle/

1):

exec dbms_stats.gather_table_stats ( -
     ownname          => 'SCOTT', -
     tabname          => 'EMP', -
     estimate_percent => dbms_stats.auto_sample_size, -
     method_opt       => 'for all columns size auto', -
     cascade          => true, -
     degree           => 5 -
)
/

exec dbms_stats.gather_schema_stats ( -
     ownname          => 'SCOTT', -
     options          => 'GATHER', -
     estimate_percent => dbms_stats.auto_sample_size, -
     method_opt       => 'for all columns size auto', -
     cascade          => true, -
     degree           => 5 -
)
/


BEGIN
  DBMS_STATS.GATHER_table_STATS (OWNNAME => 'OE', TABNAME => 'INVENTORIES',
  METHOD_OPT => 'FOR COLUMNS SIZE 10 quantity_on_hand');
END;
/

DBMS_STATS.GATHER_TABLE_STATS(ownname => USER, tabname => 'CASE_HDR',
method_opt => 'for all indexed columns',
cascade => true,
stattab => 'CASE_HDR_STAT_TAB',
statid => 1);


BEGIN
  DBMS_STATS.GATHER_table_STATS (OWNNAME => 'OE', TABNAME => 'INVENTORIES',
  METHOD_OPT => 'FOR COLUMNS SIZE 20 warehouse_id');
END;
/

 


2): auto stats
SELECT * FROM DBA_SCHEDULER_JOBS WHERE JOB_NAME = 'GATHER_STATS_JOB';

BEGIN
  DBMS_SCHEDULER.DISABLE('GATHER_STATS_JOB');
END;
/

init.ora
STATISTICS_LEVEL=TYPICAL|ALL

3):
EXECUTE DBMS_STATS.GATHER_SCHEMA_STATS('OE',DBMS_STATS.AUTO_SAMPLE_SIZE);

BEGIN
  DBMS_STATS.DELETE_TABLE_STATS('OE','ORDERS');
  DBMS_STATS.LOCK_TABLE_STATS('OE','ORDERS');
END;
/


4):
DBMS_STATS.GATHER_DICTIONARY_STATS
DBMS_STATS.GATHER_SYSTEM_STATS

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


stats export and import:
DBMS_STATS.CREATE_STATS_TABLE (ownname => USER, stattab => 'MY_STAT_TABLE', tblspace => 'USERS');
exec dbms_stats.export_database_stats('MY_STAT_TABLE','my_good_stats_001','SYSTEM');
execute dbms_stats.delete_table_stats('SCOTT','EMP')
execute dbms_stats.delete_table_stats('SCOTT','DEPT')
exec dbms_stats.import_schema_stats('SCOTT','MY_STAT_TABLE','my_good_stats_001','system');
exec dbms_stats.export_database_stats('MY_STAT_TABLE','my_good_stats_002','SYSTEM');

DBMS_STATS.EXPORT_TABLE_STATS(ownname => USER, tabname => 'CASE_HDR',
                                 stattab => 'CASE_HDR_STAT_TAB', statid => 1, cascade => true);

DBMS_STATS.IMPORT_TABLE_STATS(ownname => USER, tabname => 'CASE_HDR',
         stattab => 'CASE_HDR_STAT_TAB', statid => 1, cascade => true, no_invalidate => true);


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

ocm6  Interpret execution plan
https://shenh.tripod.com/Oracleblog/index.blog/1825047/ocm6-interpret-execution-plan/ 

 

http://www.psoug.org/reference/dbms_xplan.html

1): create plan table


2):
explain plan for ... ...

3):
set autotrace on

set autotrace on traceonly

4): dbms_xplan

dbms_xplan.display(
table_name VARCHAR2 DEFAULT 'PLAN_TABLE',
statement_id VARCHAR2 DEFAULT NULL,
format VARCHAR2 DEFAULT 'TYPICAL',
filter_preds VARCHAR2 DEFAULT NULL)
RETURN dbms_xplan_type_table PIPELINED;

http://www.psoug.org/reference/dbms_xplan.html

SELECT * FROM TABLE(dbms_xplan.display_cursor('cpm9ss48qd32f', 0));

 

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

also in sqlplus, set autotrace on trace only;

dbms_monitor.*

tkprof

trcsess

10046 event:

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

 

ocm6  Use SQL tuning tools and features
https://shenh.tripod.com/Oracleblog/index.blog/1825048/ocm6-use-sql-tuning-tools-and-features/

 


Posted by shenh at 11:31 PM EST
Updated: Tuesday, 20 January 2009 11:50 AM EST
OCM 5: Data Warehouse

ocm5  Create external tables (Data Loader and Data Pump drivers)
https://shenh.tripod.com/Oracleblog/index.blog/1825019/ocm5-create-external-tables/

external table:
http://www.globusz.com/ebooks/Oracle/00000012.htm#4


http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/part_et.htm

ocm5  Implement Data Pump export and import jobs for data transfer
https://shenh.tripod.com/Oracleblog/index.blog/1825020/ocm5-implement-data-pump-export-and-import-jobs-for-data-transfer/


data pump:
http://www.globusz.com/ebooks/Oracle/00000012.htm

http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_overview.htm#i1009203

http://www.databasejournal.com/features/oracle/article.php/3489491

 

ocm5  Implement Data Pump to and from remote databases
https://shenh.tripod.com/Oracleblog/index.blog/1825021/ocm5-implement-data-pump-to-and-from-remote-databases/

1): dblinks and network 

Network Considerations

You can use SQL*Net connection strings or connection descriptors when you invoke the Import utility. To do so, the listener must be running (lsnrctl start). The following example shows how to invoke Import using a SQL*Net connection:

> impdp hr/hr@inst1 DIRECTORY=dpump_dir DUMPFILE=hr.dmp TABLES=employees  

The hr/hr@inst1 results in a SQL*Net connection. The inst1 refers to a service name specified in the tnsnames.ora file. This means that the import client is being run remotely from the server to import data from a dump file.

Do not confuse invoking the Import utility using a SQL*Net connection string with performing an import operation using the Import NETWORK_LINK parameter.

The NETWORK_LINK parameter initiates a network import. This means that the impdp client initiates the import request, typically to the local database. That server contacts the remote source database referenced by the database link in the NETWORK_LINK parameter, retrieves the data, and writes it directly back to the target database. There are no dump files involved.

 

In the following example, the source_database_link would be replaced with the name of a valid database link that must already exist.

> impdp hr/hr TABLES=employees DIRECTORY=dpump_dir1 NETWORK_LINK=source_database_link EXCLUDE=CONSTRAINT  

This example results in an import of the employees table (excluding constraints) from the source database. The log file is written to dpump_dir1, specified on the DIRECTORY parameter.

2): transportable tablespace
Transporting Tablespaces :
http://www.globusz.com/ebooks/Oracle/00000012.htm#5

http://www.globusz.com/ebooks/Oracle/00000018.htm#5
dbms_tts.*

ocm5  Implement Replication/Streams
https://shenh.tripod.com/Oracleblog/index.blog/1825022/ocm5-implement-replicationstreams/

Could you please let me know the procedure to set up multi-master replication in Oracle 10g?You can use Oracle Advanced Replication to do this.

However, this is being replaced by newer technology called Streams and this is what you should be using. Have a look at the following links for more details.

http://www.oracle.com/technology/products/dataint/htdocs/streams_fo.html

http://download-west.oracle.com/docs/cd/B14099_19/idmanage.1012/b14082/rep_process.htm

-- --------------------------------------------
D17333GC10: Implement Streams

Configure an Oracle Streams environment
Monitor the capture, propagation, and apply of events
Alter the Streams environment to add new sites or objects
Configure conflict handling for data replication
Transform the data being replicated between two sites
Enqueue and dequeue messages using Oracle Streams
Perform basic troubleshooting of a Streams environment

Introduction and Overview
Database Configuration
Streams Basic Objects
Rules
System-Created Rules
Capture Process Concepts
Configuring Capture
Instantiation
Propagation Concepts and Configuration
Apply: Concepts and Configuration
Apply Handlers
Administering a Streams Environment
Extending the Streams Environment
Data Conflicts
Conflict Resolution
Transformations
User-Enqueued Events
Operational Issues
Troubleshooting Oracle Streams
Integrating with Oracle Streams

ocm5  Configure and manage master replication
https://shenh.tripod.com/Oracleblog/index.blog/1825023/ocm5-configure-and-manage-master-replication/

good:
http://www.dbazine.com/oracle/or-articles/burleson15


http://www.dbasupport.com/oracle/ora9i/ors.shtml

http://www.adventnet.com/products/webnms/help/administrator_guide/dbase/db_replication.html

http://download.oracle.com/docs/cd/A91202_01/901_doc/server.901/a87499/repoverv.htm


http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14227/rarmanmaster.htm

http://www.dbasupport.com/oracle/ora9i/ors.shtml

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

http://orafaq.com/faqrepl.htm

http://www.oracle.com/technology/books/pdfs/book_rep_chap6_ce2.pdf

http://www.wisdomforce.com/dweb/resources/docs/advanced_replication.pdf


http://www.oracle.com/technology/products/dataint/pdf/twp_streams_replication_10gr2.pdf

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

http://download.oracle.com/docs/cd/B19306_01/server.102/b14227/rarrepsite.htm

http://www.adp-gmbh.ch/ora/admin/replication/multi_master_replication.html

http://www.colestock.com/blogs/2008/03/oracle-multi-master-replication-example.html

http://download.oracle.com/docs/cd/B19306_01/server.102/b14227/toc.htm

http://download.oracle.com/docs/cd/B19306_01/server.102/b14226/toc.htm

 

http://www.oracle.com/technology/books/pdfs/book_rep_chap6_ce2.pdf

http://www.cisco.com/univercd/cc/td/doc/product/access/acs_soft/rpms/rpms_1-0/rpmsconf/app_db2.pdf

http://www.dba-oracle.com/art_dbazine_mm_repl.htm
http://www.oraclenotes.com/Articles/Advance%20Replication.ppt
http://www.orafaq.com/wiki/Scripts#Oracle_Advanced_Replication_Scripts

1): The number of replicated tables is modest and manageable
    ( < 100K not 10,000 or more )

2): DBA has full conrol over the designof the tables.
   Every replicated table must have primary key,
   and additional column and triggers need added for conflict resolution.

-- --------------------------------------------------------
repadmin  multi-master
oemapp console &
Master Groups
-- --------------------------------------------------------

Adding and Removing Oracle replication Objects

Adding and removing objects is easy, provided they are not large. 
Simply stop replication activity. 
Add the object to the master group at the master definition site and restart replication. 
The new object will be propagated to all master sites in the replication environment.

connect repadmin/repadmin@navdb

BEGIN
      DBMS_REPCAT.SUSPEND_MASTER_ACTIVITY(
      gname => '"GROUP1"');
END;
/

begin
  dbms_repcat.create_master_repobject(
    'RENE', 'OBJ_1', 'TABLE', gname=>'rep_objects');

  dbms_repcat.create_master_repobject(
    'RENE', 'OBJ_2', 'TABLE', gname=>'rep_objects');
end;
/

REM Add master desination sites
execute dbms_repcat.add_master_database('MYREPGRP', 'TD2.world');

or
begin
  dbms_repcat.add_master_database (
     gname                => 'rep_objects',
     master               => 'otherdb.foo.invalid',
     use_existing_objects => true,
     copy_rows            => false,
     propagation_mode     => 'ASYNCHRONOUS');
end;
/

REM Generate replication support for objects within the group
execute dbms_repcat.generate_replication_support('SCOTT', 'EMP', 'table');

or
begin
  dbms_repcat.generate_replication_support('RENE','OBJ_1','TABLE');
  dbms_repcat.generate_replication_support('RENE','OBJ_2','TABLE');
end;
/

select count(*) from dba_repcatalog; ==> make sure no outstanding requests

BEGIN
      DBMS_REPCAT.RESUME_MASTER_ACTIVITY(
      gname => '"GROUP1"');

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


dbms_defer_sys.execute_error:
re-execute procedure calls in the error log
after fixing the problem that caused the error.

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

dbms_reputil.replication_off
do manual update or other DML
dbms_reputil.replication_on

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

if dbms_reputil.remote_site = false then
...
end if;

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


1): adding a column
BEGIN
   DBMS_REPCAT.ALTER_MASTER_REPOBJECT (
      sname => 'hr',
      oname => 'countries',
      type => 'TABLE',
      ddl_text => 'ALTER TABLE hr.countries ADD (timestamp DATE)');
END;
/

BEGIN
    DBMS_REPCAT.GENERATE_REPLICATION_SUPPORT (
      sname => 'hr',
      oname => 'countries',
      type => 'TABLE',
      min_communication => TRUE);
END;
/

BEGIN
   DBMS_REPCAT.ALTER_MASTER_REPOBJECT (
      sname => 'hr',
      oname => 'regions',
      type => 'TABLE',
      ddl_text => 'ALTER TABLE hr.regions ADD (site VARCHAR2(20))');
END;
/

BEGIN
    DBMS_REPCAT.GENERATE_REPLICATION_SUPPORT (
      sname => 'hr',
      oname => 'regions',
      type => 'TABLE',
      min_communication => TRUE);
END;
/

2): adding a trigger
BEGIN
   DBMS_REPCAT.CREATE_MASTER_REPOBJECT (
      gname => 'hr_repg',
      type => 'TRIGGER',
      oname => 'insert_time',
      sname => 'hr',
      ddl_text => 'CREATE TRIGGER hr.insert_time
                      BEFORE
                         INSERT OR UPDATE ON hr.countries FOR EACH ROW
                      BEGIN
                         IF DBMS_REPUTIL.FROM_REMOTE = FALSE THEN
                            :NEW.TIMESTAMP := SYSDATE;
                         END IF;
                      END;');
END;
/

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


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

Conflict Resolution:

In this code, we execute dbms_repcat.add_update_resolution to direct
Oracle to use the “latest timestamp” method for conflict resolution
for updates to the EMP table.

execute dbms_repcat.add_update_resolution( -
        sname => 'SCOTT',               -
        oname => 'EMP',                 -
        column_group => 'EMP_COLGRP',   -
        sequence_no => 1,               -
        method => 'LATEST TIMESTAMP',   -
        parameter_column_name => 'EMPNO');

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

DBA_REPCATLOG view

DBMS_REPCAT.DO_DEFERRED_REPCAT_ADMIN

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

http://www.dba-oracle.com/art_dbazine_mm_repl.htm

Conflict Resolution Mechanisms
Here are the most common mechanisms at your disposal for resolving conflicts:

* Latest Timestamp Value.
  With this simple technique, you apply updates as they are received. Based on timestamp value, the most recent updates overlays prior updates. This approach can result in situations where one user’s update gets overlaid by a more recent update.

* Earliest Timestamp Value.
 This mechanism is the opposite of the latest timestamp value, in that the first update overlays subsequent updates. As you’d expect, not many shops use this method, but it is an option.

* Minimum and Maximum Value.
 This mechanism may be used when the advanced replication facility detects a conflict with a column group. The advanced replication facility calls the minimum value conflict resolution method and then compares the new value from the originating site with the current value from the destination site for a designated column in the column group. You must designate that column when you select the minimum value conflict resolution method.

* Additive and Average Value.
 When you’re dealing with replicated numeric values, this additive method adds a new value to the existing value using the following formula: (current value = current value + (new value - old value)). The average method averages the conflicting values into the existing value using the formula (current value = (current value + new value)/2).

* Groups priority Value.
 Using this method, some groups have priority (a higher rank) over other groups. Therefore, the update associated with the highest-ranked group gets the update.

* Site Priority Value.
  In this method, all master sites are NOT created equal. Some remote sites will have priority over other sites.

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

deftran, deferror, defcall

dbms_repcat.create_master_repgroup
do_deferred_repcat_admin
dbms_repcat.create_master_repobject

dbms_repcat.make_column_group(optional)
dbms_repcat.add_master_database( gname, master=>dblink)

dba_repsites: master sites will be in dba_repsites


rem -----------------------------------------------------------------------
rem Filename:   repprep.sql
rem Purpose:    Setup users, DB Links and schedules for Oracle Advanced
rem             replication. Run this script on all replication sites.
rem             In this example replication is between sites TD1 and TD2
rem Date:       03-Oct-2000
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

set pages 50000
spool repprep

connect sys

-- @?/rdbms/admin/catrep.sql

init.ora
      shared_pool_size=10M
      global_names=true
      job_queue_processes=4

REM Check if INIT.ORA parameters are OK for replication
select name, value from sys.v_$parameter
where  name in ('job_queue_processes', 'job_queue_interval',
                'global_name')

REM Assign global name to the current DB
alter database rename global_name to TD1.world;    -- Change to your DB name + domain

REM Create public db link to the other master databses
create public database link TD2.world using 'TD2';

REM Create replication administrator / propagator / receiver
create user repadmin identified by repadmin
        default   tablespace USER_DATA
        temporary tablespace TEMP
        quota unlimited on USER_DATA;

REM Grant privs to the propagator, to propagate changes to remote sites
execute dbms_defer_sys.register_propagator(username=>'REPADMIN');

REM Grant privs to the receiver to apply deferred transactions
grant execute any procedure to repadmin;

REM Authorise the administrator to administer replication groups
execute dbms_repcat_admin.grant_admin_any_repgroup('REPADMIN');

REM Authorise the administrator to lock and comment tables
grant lock any table to repadmin;
grant comment any table to repadmin;

connect repadmin/repadmin

REM Create private db links for repadmin
create database link TD2.world
        connect to repadmin identified by repadmin;

REM Schedule job to push transactions to master sites
execute dbms_defer_sys.schedule_push(        -
        destination   => 'TD2.world',        -
        interval      => 'sysdate+1/24/60',  -
        next_date     => sysdate+1/24/60,    -
        stop_on_error => FALSE,              -
        delay_seconds => 0,                  -
        parallelism   => 1);

REM Schedule job to delete successfully replciated transactions
execute dbms_defer_sys.schedule_purge(       -
        next_date     => sysdate+1/24,       -
        interval      => 'sysdate+1/24');

REM Test database link
select global_name from global_name@TD2.world;

spool off

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

rem -----------------------------------------------------------------------
rem Filename:   repdef.sql
rem Purpose:    Define replication groups with replication objects
rem             Run on Master Definition site only. Run repprep.sql
rem  on all your databases before running this script.
rem Date:       03-Oct-2000
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

set pages 50000
spool repdef

connect repadmin/repadmin

REM Create replication group for MASTERDEF site
execute dbms_repcat.create_master_repgroup('MYREPGRP');

REM Register objects within the group
execute dbms_repcat.create_master_repobject('SCOTT', -
        'EMP', 'TABLE', gname=>'MYREPGRP');

execute dbms_repcat.create_master_repobject('SCOTT', -
        'DEPT', 'TABLE', gname=>'MYREPGRP');

REM Add master desination sites
execute dbms_repcat.add_master_database('MYREPGRP', 'TD2.world');

REM Generate replication support for objects within the group
execute dbms_repcat.generate_replication_support('SCOTT', 'EMP', 'table');

exec dbms_repcat.resume_master_activity(gname=>'MYREPGRP');

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

rem -----------------------------------------------------------------------
rem Filename:   repdef.sql
rem Purpose:    Slightly more advanced setup
rem Date:       03-Oct-2000
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

set pages 50000
spool repdef

connect repadmin/repadmin

REM Create replication group for MASTERDEF site
execute dbms_repcat.create_master_repgroup('MYREPGRP');

REM Register objects within the group
execute dbms_repcat.create_master_repobject('SCOTT', -
        'EMP', 'TABLE', gname=>'MYREPGRP');

execute dbms_repcat.make_column_group(  -
        sname => 'SCOTT',               -
        oname => 'EMP',                 -
        column_group => 'EMP_COLGRP',   -
        list_of_column_names => 'EMPNO');

execute dbms_repcat.add_update_resolution( -
        sname => 'SCOTT',               -
        oname => 'EMP',                 -
        column_group => 'EMP_COLGRP',   -
        sequence_no => 1,               -
        method => 'LATEST TIMESTAMP',   -
        parameter_column_name => 'EMPNO');

REM Add master desination sites
execute dbms_repcat.add_master_database('MYREPGRP', 'TD2.world');

REM Generate replication support for objects within the group
execute dbms_repcat.generate_replication_support('SCOTT', 'EMP', 'table');

exec dbms_repcat.resume_master_activity(gname=>'MYREPGRP');

-- -------------------------------------------------------------
rem -----------------------------------------------------------------------
rem Filename:   repmon.sql
rem Purpose:    Monitor replication status, sites and groups
rem Date:       03-Oct-2000
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

connect repadmin/repadmin

set pages 50000

col sname     format a20 head "SchemaName"
col masterdef format a10 head "MasterDef?"
col oname     format a20 head "ObjectName"
col gname     format a20 head "GroupName"
col object    format a35 trunc
col dblink    format a35 head "DBLink"
col message   format a25
col broken    format a6  head "Broken?"

prompt Replication schemas/ sites
select sname, masterdef, dblink
from   sys.dba_repschema;

prompt RepCat Log (after a while you should see no entries):
select request, status, message, errnum
from   sys.dba_repcatlog;

prompt Entries in the job queue
select job, last_date, last_sec, next_date, next_sec, broken, failures,
       what
from   sys.dba_jobs
where  schema_user = 'REPADMIN';

prompt Replication Status:
select sname, master, status
from   sys.dba_repcat;

-- Returns all conflict resolution methods
-- select * from all_repconflict;

-- Returns all resolution methods in use
-- select * from all_represolution;

prompt Objects registered for replication
select gname, type||' '||sname||'.'||oname object, status
from   sys.dba_repobject;

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

rem -----------------------------------------------------------------------
rem Filename:   reperrs.sql
rem Purpose:    Try to apply transaction in error and delete the remaining
rem             transactions that is still in error.
rem Date:       06-Feb-2006
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

connect repadmin/repadmin

spool apply_errors.sql
select 'exec dbms_defer_sys.execute_error(''' || deferred_tran_id ||''','''||
       destination || ''')'
from   deferror;
spool off
@apply_errors
commit;

spool delete_errors.sql
select 'exec dbms_defer_sys.delete_error(''' || deferred_tran_id ||''','''||
       destination || ''')'
from   deferror;
spool off
@delete_errors
commit;

-- Deletes all errors in one go...
-- execute dbms_defer_sys.delete_error(NULL,NULL);

-- Clear entries from the local RepCatLog (DBA_REPCATLOG)
-- exec dbms_repcat.purge_master_log;

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

rem -----------------------------------------------------------------------
rem Filename:   repdel.sql
rem Purpose:    Remove replication support from database
rem Date:       03-Oct-2000
rem Author:     Frank Naude, Oracle FAQ
rem -----------------------------------------------------------------------

spool repdel

connect repadmin/repadmin

REM Stop replication
execute dbms_repcat.suspend_master_activity(gname=>'MYREPGRP');

REM Delete replication groups
-- execute dbms_repcat.drop_master_repobject('SCOTT', 'EMP', 'TABLE');
execute dbms_repcat.drop_master_repgroup('MYREPGRP');
execute dbms_repcat.remove_master_databases('MYREPGRP', 'TD2.world');

REM Remove private databse links to other master databases
drop database link TD2.world;


connect sys

REM Remove the REPADMIN user
execute dbms_defer_sys.unregister_propagator(username=>'REPADMIN');
execute dbms_repcat_admin.revoke_admin_any_schema(username=>'REPADMIN');
drop user repadmin cascade;

REM Drop public database links to other master databases
drop public database link TD2.world;

spool off


ocm5  Configure and manage distributed materialized views
https://shenh.tripod.com/Oracleblog/index.blog/1825024/ocm5-configure-and-manage-distributed-materialized-views/

1): dblink

http://www.globusz.com/ebooks/Oracle/00000021.htm#4

http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_5005.htm#i2061505

CREATE PUBLIC DATABASE LINK remote
USING 'remote';

CREATE DATABASE LINK local
CONNECT TO hr IDENTIFIED BY hr
USING 'local';

CREATE DATABASE LINK remote.us.oracle.com
CONNECT TO CURRENT_USER
USING 'remote';

2): mv log
SQL> create materialized view log on table EMP;

3): actual mv
SQL> create materialized view emp
refresh fast with primary key
start with sysdate
next sysdate + 1/(24*60)
as (select * from emp@dblink);

4): refresh

dbms_mview.refresh ( 'hr.emp', 'F' );

 


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

create a mv refresh group:

http://www.hpfuchs.com/2008/02/06/materialized-view-replication/

SQL> BEGIN
dbms_refresh.make(
name => ‘mv1_refgroup’,
list => ‘MView1′,
next_date => sysdate,
interval => ’sysdate + 1′,
implicit_destroy => true,
lax => true);
END;
/

SQL> exec dbms_refresh.refresh(name => ‘mv1_refgroup’);

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

ocm5  Configure and manage Streams for replication
https://shenh.tripod.com/Oracleblog/index.blog/1825025/ocm5-configure-and-manage-streams-for-replication/


BEST:
http://www.oracle.com/technology/oramag/oracle/04-nov/o64streams.html

streams:
http://www.oracle.com/technology/obe/obe9ir2/obe-intg/streams/streams.htm
http://www.oracle.com/technology/obe/obe9ir2/obe-intg/streams/streams.htm?_template=/ocom/print

http://tech.it168.com/a2008/0724/198/000000198400.shtml


http://www.oracle.com/technology/obe/obe10gdb/integrate/streams/streams.htm

Implementing streams: D17333GC10
Oracle Database 10g: Implement Streams (Database and Grids)
http://education.oracle.com/pls/web_prod-plq-dad/show_desc.redirect?dc=D17333GC10&p_org_id=1001&lang=US&source_call=

http://education.oracle.com/pls/web_prod-plq-dad/show_desc.redirect?dc=D17333GC20&p_org_id=1001&lang=US&source_call=

http://education.oracle.com/pls/web_prod-plq-dad/show_desc.redirect?dc=D50315GC10&p_org_id=1001&lang=US&source_call=

http://education.oracle.com/pls/web_prod-plq-dad/show_desc.redirect?dc=D18681&p_org_id=1001&lang=US&source_call=

 


Oracle9i Database: Implementing Oracle Streams

9i streams:
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96571/apply.htm#55587

http://blogs.ittoolbox.com/oracle/guide/archives/oracle-streams-configuration-change-data-capture-13501

Nandeep Nagarkar: Change Data Capture Implementation in Oracle Data Warehouses

http://www.dbasupport.com/oracle/ora9i/datacapture.shtml
http://www.dbasupport.com/oracle/ora9i/datacapture2_1.shtml
http://www.dbasupport.com/oracle/ora9i/datacapture2_2.shtml
http://www.dbasupport.com/oracle/ora9i/datacapture2_3.shtml
http://www.dbasupport.com/oracle/ora9i/datacapture2_4.shtml

http://www.dbasupport.com/oracle/ora9i/datacapture3_1.shtml
http://www.dbasupport.com/oracle/ora9i/datacapture3_2.shtml


Streams Replication

a): Supplemental Logging
b): logminer


Set up ARCHIVELOG mode.
Set up the Streams administrator.
Set initialization parameters.
Create a database link.
Set up source and destination queues.
Set up supplemental logging at the source database.
Configure the capture process at the source database.
Configure the propagation process.
Create the destination table.
Grant object privileges.
Set the instantiation system change number (SCN).
Configure the apply process at the destination database.
Start the capture and apply processes

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

twp: The white paper
http://www.oracle.com/technology/products/dataint/pdf/twp_streams_replication_10gr2.pdf

DBMS_STREAMS_ADM.MAINTAIN_SCHEMAS (
schema_names => 'HR',
source_directory_object=>null,
destination_directory_oject=>null,
source_database=>null,
destination_database=>'NYC',
bi_directional=>TRUE,
instantiation=>DBMS_STREAMS_ADM.INSTANTIATION_SCHEMA_NETWORK);

dbms_streams_adm.add_subset_propagation_rules (
table_name => 'HR.CUSTOMER',
dml_condition => 'STATE=''CA''',
streams_type => 'PROPAGATION',
destination_queue_name => 'streamadmin.streams_queue@myrep.world',
source_database => 'mydb.world' );

-- -------------------------------------------------------------
http://www.jlcomp.demon.co.uk/faq/streams_01.html

Data to be replicated is not obtained by direct access to OLTP database. Data extraction process interferes with regular database operation. The source of the information is Oracle's archived log files. This is much less intrusive for online users. Streams uses Oracle’s Log Miner infrastructure to read redo logs.


(For an introduction to Streams, basic concepts, list of reference documentation, and an example of a single table one-way replication procedure, please refer to Sanjay Mishra's article, “Making Data Flow” at http://www.oracle.com/technology/oramag/oracle/04-nov/o64streams.html)


The single PL/SQL procedure - dbms_streams_adm.maintain_schemas completely sets up basic schema level replication. Certain tasks must be completed, though, before this procedure runs in step 8.


1. Configure source database to run in archivelog mode

2. Set up Streams administrator strmadmin on both databases (source and target)

3. Adjust initialization parameters on both databases for Streams replication

4. Create database link from source (ORCLA.WORLD) to target (ORCLB.WORLD) database

5. Create database link from target (ORCLB.WORLD) to source (ORCLA.WORLD) database

(This link is needed because I will use the network Data Pump export/import which is not using an export dump file; standard export/import using dump file is also possible )

6. (Recommended) Create directory on source machine (It will contain generated replication script.)

7.( Recommended) Run dbms_streams_adm.maintain_schemas with perform_actions parameter set to false on source database to generate the replication script. This is a dry run to verify the script’s correctness and avoid time-consuming replication cleanup (in case the replication setup script fails.)

8. Run dbms_streams_adm.maintain_schemas procedure on the source database with perform_actions parameter set to true. This will startt the replication setup.

9. Verify that DDL and DML changes on ORCLA.WORLD are propagated to ORCLB.WORLD




Steps in detail



For steps 1 – 4, please refer to the Mishra's article mentioned above. They are identical.



5. Create a database link on target database:

connect strmadmin/strmadmin@ORCLB.world

CREATE DATABASE LINK ORCLA.WORLD

CONNECT TO STRMADMIN

IDENTIFIED BY STRMADMIN

USING ‘ORCLA.WORLD’;



6. Create a directory on the source database where the script generated by dbms_streams_adm.maintain_schemas will be stored:

CONNECT strmadmin/strmadmin@orcla.world

CREATE OR REPLACE DIRECTORY ADMIN AS '/home/oracle/Streams';



7. Generate script schema_replication.sql in Oracle admin directory

(/home/oracle/Streams on Linux):

CONN strmadmin/strmadmin@orcla.world

BEGIN

DBMS_STREAMS_ADM.MAINTAIN_SCHEMAS(

schema_names => 'scott',

source_database => 'orcla.world',

destination_database => 'orclb.world',

capture_name => 'capture_scott',

capture_queue_table => 'rep_capture_queue_table',

capture_queue_name => 'rep_capture_queue',

capture_queue_user => null,

apply_name => 'apply_scott',

apply_queue_table => 'rep_dest_queue_table',

apply_queue_name => 'rep_dest_queue',

apply_queue_user => null,

propagation_name => 'prop_scott',

log_file => 'exp.log',

bi_directional => false,

include_ddl => true,

instantiation => dbms_streams_adm.instantiation_schema_network,

perform_actions => false,

script_name => 'schema_replication.sql',

script_directory_object => 'admin'

);

END;









The /home/oracle/Streams/schema_replication.sql script now contains commands to completely configure SCOTT schema replication. A brief description of scripts contents follows:

- Supplemental logging data is added for all tables in the SCOTT schema; it is required to log additional data to redo logs if you want Streams to work properly

- dbms_streams_adm.set_up_queue procedure is run to create capture queue and capture table

- dbms_streams_adm.add_schema_propagation_rules is run to add rules to the positive rule set for propagation; this is queue-to-queue propagation

- Propagation is temporarily disabled

- dbms_streams_adm.add_schema_rules is run to add rules to capture process

- Datapump schema mode import (network) is run from ORCLB.WORLD database ( SCOTT schema is exported from ORCLA.WORLD and imported into ORCLB.WORLD; DBMS_DATAPUMP package is used for this purpose)

- Capture process is started on ORCLA.WORLD database

- Apply queue rep_dest_queue on the target database is configured using the dbms_streams_adm.set_up_queue procedure

- Schema rules for the apply process are added (dbms_streams_adm.add_schema_rules procedure is executed )

- A tag is added to apply process and apply process is started

- Propagation is enabled



8. We will now execute maintain_schemas procedure; perform_actions parameter is changed to true.

BEGIN

DBMS_STREAMS_ADM.MAINTAIN_SCHEMAS(

schema_names => 'scott',

source_directory_object => NULL,

destination_directory_object => NULL,

source_database => 'orcla.world',

destination_database => 'orclb.world',

capture_name => 'capture_scott',

capture_queue_table => 'rep_capture_queue_table',

capture_queue_name => 'rep_capture_queue',

capture_queue_user => null,

apply_name => 'apply_scott',

apply_queue_table => 'rep_dest_queue_table',

apply_queue_name => 'rep_dest_queue',

apply_queue_user => null,

propagation_name => 'prop_scott',

log_file => 'exp.log',

bi_directional => false,

include_ddl => true,

instantiation => dbms_streams_adm.instantiation_schema_network,

perform_actions => true

);

END;

/





The execution of this procedure will take some time, depending on the schema size, number of objects, volume of data etc. When it completes all DML and DDL changes to tables in the SCOTT schema on ORCLA.WORLD, the database will be propagated to ORCLB.WORLD database.



Oracle Streams is relatively new tool primarily designed to help move real time data between databases.

The easy setup, possibility of light data transformation, and good performance make it welcome addition to a DBA's toolset.

 


Posted by shenh at 11:27 PM EST
Updated: Wednesday, 7 January 2009 12:58 AM EST
OCM 4: Data Management

4. Data Management
ocm4  Implement fine-grained auditing
https://shenh.tripod.com/Oracleblog/index.blog/1824988/ocm4-implement-finegrained-auditing/


http://www.databasejournal.com/features/oracle/article.php/3640201

http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/nanda_fga.html

DBMS_FGA.ADD_POLICY(
object_schema => 'hr',
object_name => 'emp',
policy_name => 'chk_hr_emp',
audit_condition => 'dept = ''SALES'' ',
audit_column => 'salary'
statement_types => 'insert,update,delete,select');
-- -----------------------------------
With all the relevant information available, and a trigger-like mechanism to use, the administrator can define what to record and how to process the audit event.

Consider the following commands:

/* create audit event handler */
CREATE PROCEDURE sec.log_id (schema1 varchar2, table1 varchar2, policy1 varchar2) AS
BEGIN
UTIL_ALERT_PAGER(schema1, table1, policy1); -- send an alert note to my pager
END;

/* add the policy */
DBMS_FGA.ADD_POLICY(
object_schema => 'hr',
object_name => 'emp',
policy_name => 'chk_hr_emp',
audit_condition => 'dept = ''SALES'' ',
audit_column => 'salary',
handler_schema => 'sec',
handler_module => 'log_id',
enable => TRUE);
-- -----------------------------------
package:
DBMS_FGA
DBMS_FGA.ADD_POLICY

http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14266/cfgaudit.htm#i1011302
DBA_FGA_AUDIT_TRAIL
sys.fga_log$
DBA_COMMON_AUDIT_TRAIL

http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14266/auditing.htm#i1008289

http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14266/auditing.htm#i1009205

DBMS_FGA.ADD_POLICY
(object_schema => 'scott',
object_name=>'emp',
policy_name => 'mypolicy1',
audit_condition => 'sal < 100', audit_column =>'comm, credit_card, expirn_date', handler_schema => NULL,
handler_module => NULL,
enable => TRUE,
statement_types=> 'INSERT, UPDATE',
audit_trail => DBMS_FGA.DB+DBMS_FGA.EXTENDED,
audit_column_opts => DBMS_FGA.ALL_COLUMNS);

DBMS_FGA.DISABLE_POLICY(
object_schema VARCHAR2,
object_name VARCHAR2,
policy_name VARCHAR2 );

DBMS_FGA.DROP_POLICY(
object_schema VARCHAR2,
object_name VARCHAR2,
policy_name VARCHAR2 );

DBMS_FGA.ENABLE_POLICY(
object_schema VARCHAR2,
object_name VARCHAR2,
policy_name VARCHAR2,
enable BOOLEAN);
-- -------------------------------------------


traditioonal:
grant select on employees to sue, rich
grant update (department_name, location_id) on departments to scott;

revoke [priviledge|all] on object from
user|role|public [cascade constrainsts];

role_sys_privs : system priviledges granted to roles

role_tab_privs : Table priviledges granted to roles

user_role_privs : Roles accessible by the user

user_tab_privs_made : Object priviledges granted on the user's objects

user_tab_privs_recd : Object priviledges granted to the user

user_col_privs_made : on specific columns

user_col_privs_recd : on specific columns

user_sys_privs : System priviledges granted to the user

ocm4  Create a secure application role
https://shenh.tripod.com/Oracleblog/index.blog/1824989/ocm4-create-a-secure-application-role/


http://www.oracle.com/technology/obe/obe10gdb/security/approles/approles.htm

http://www.oracle.com/technology/deploy/security/database-security/secure-application-roles/index.html

CREATE ROLE admin_role IDENTIFIED USING hr.admin;

connect system/oracle
CREATE OR REPLACE procedure sec_roles
authid current_user
as
v_user varchar2(50);
v_manager_id number :=1;
begin
v_user := (sys_context ('userenv', 'session_user'));

select manager_id into v_manager_id from hr.employees where email=v_user;

if v_manager_id = 100 then
dbms_session.set_role('ots_role');
else
null;
end if;
exception
when no_data_found then
v_manager_id:=0;
end sec_roles;
/


The role can only be enabled by modules defined inside the PL/SQL package hr.admin.

When such a role is assigned to a user, it becomes a default role for that user, which is automatically enabled at login without resorting to the package. A user with a default role does not have to be authenticated in any way to use the role. For example, the password for the role is not requested or required.

To restrict the role solely to the use specified by the IDENTIFIED USING clause, you can take either of the following actions:

Immediately after granting such a role to a user, issue an ALTER USER statement with the clause DEFAULT ROLE ALL EXCEPT role, substituting the application role for role. Then role can only be used by applications executing the authorized package.

When assigning roles, use GRANT ALL EXCEPT role.

Roles that are enabled inside an invoker's right procedure remain in effect even after the procedure exits. Therefore, you can have a dedicated procedure that deals with enabling the role for the rest of the session to use.

http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14266/authoriz.htm#sthref606

ocm4  Grant specific privileges for a Flashback Query
https://shenh.tripod.com/Oracleblog/index.blog/1824990/ocm4-grant-specific-privileges-for-a-flashback-query/

GRANT FLASHBACK ON SCOTT.BONUS_DROP TO SCOTT

grant FLASHBACK ANY TABLE to scott

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

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_flashback.htm

Grant flashback privileges to users, roles, or applications that need to use flashback features as follows:

For the DBMS_FLASHBACK package, grant the EXECUTE privilege on DBMS_FLASHBACK to provide access to the features in this package.

For Flashback Query and Flashback Version Query, grant FLASHBACK and SELECT privileges on specific objects to be accessed during queries or grant the FLASHBACK ANY TABLE privilege to allow queries on all tables.

For Flashback Transaction Query, grant the SELECT ANY TRANSACTION privilege.

For Execution of undo SQL code, grant SELECT, UPDATE, DELETE, and INSERT privileges for specific tables, as appropriate, to permit execution of undo SQL code retrieved by a Flashback Transaction Query.

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

http://orafaq.com/node/50

ocm4  Set parameters for retaining undo
https://shenh.tripod.com/Oracleblog/index.blog/1824991/ocm4-set-parameters-for-retaining-undo/

undo_retention

show parameter undo

http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14196/storage003.htm

ocm4  Implement fine-grained access control
https://shenh.tripod.com/Oracleblog/index.blog/1824994/ocm4-implement-finegrained-access-control/

Fine-Grained Access Control (FGAC)
vpd(Virtual Private Database)
DBMS_RLS
CONTEXT:

Oracle8i Fine Grained Access Control - Working Examples 67977.1
https://metalink.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=67977.1

Oracle Row Level Security: Part 1
http://www.securityfocus.com/infocus/1743

Oracle Row Level Security: Part 2
http://www.securityfocus.com/infocus/1744

http://www.oracle-base.com/articles/8i/VirtualPrivateDatabases.php
http://www.oracle-base.com/articles/10g/DatabaseSecurityEnhancements10g.php#vpd
http://www.oracle-base.com/articles/9i/OracleLabelSecurity9i.php
http://www.oracle-base.com/articles/9i/SecurityEnhancements9i.php


http://www.proligence.com/nyoug_fgac.pdf

http://www.psoug.org/reference/dbms_rls.html

begin
dbms_rls.add_policy
(
object_schema => 'HOSPITAL',
object_name => 'PATIENTS',
policy_name => 'PATIENT_VIEW_POLICY',
policy_function => 'GET_DOCTOR_ID',
function_schema => 'HOSPITAL',
statement_types => 'SELECT, INSERT, UPDATE, DELETE',
update_check => true,
enable => true
);
end;

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

create or replace function get_doctor_id
(
p_schema_name in varchar2,
p_table_name in varchar2
)
return varchar2
is
l_doctor_id number;
begin
select doctor_id
into l_doctor_id
from doctors
where doctor_name = USER;
return 'doctor_id = '||l_doctor_id;
end;

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

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

The user’s original query

SELECT * FROM PATIENTS

was rewritten to

SELECT * FROM
(SELECT * FROM PATIENTS)
WHERE DOCTOR_ID = 1 
 

 

ocm4  Create and manage contexts
https://shenh.tripod.com/Oracleblog/index.blog/1824995/ocm4-create-and-manage-contexts/

How to Determine Active Context (DBMS_SESSION.LIST_CONTEXT)
Doc ID: Note:69573.1

https://metalink.oracle.com/metalink/plsql/showdoc?db=NOT&id=69573.1&blackframe=1


http://www.databasejournal.com/features/oracle/article.php/3644956

http://www.orafusion.com/art_fgac.htm

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


DROP CONTEXT vpd_context;
CREATE CONTEXT vpd_context USING ap.app_security_context;

-- CREATE OR REPLACE PACKAGE ap.app_security_context
PROCEDURE setuserinfo;

DBMS_SESSION.SET_CONTEXT('vpd_context', 'cc_limit', cclimit);
DBMS_SESSION.SET_CONTEXT('vpd_context', 'crd_memo', crdmemo);

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

CREATE OR REPLACE TRIGGER ap.on_logon
AFTER LOGON
ON DATABASE

ocm4  Use SQL*Loader
https://shenh.tripod.com/Oracleblog/index.blog/1824996/ocm4-use-sqlloader/

Utilities
http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/ldr_concepts.htm#i1005437

SQLLDR CONTROL=sample.ctl, LOG=sample.log, BAD=baz.bad, DATA=etc.dat
USERID=scott/tiger, ERRORS=999, LOAD=2000, DISCARD=toss.dsc,
DISCARDMAX=5

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

#!/bin/sh
sqlldr scott/tiger control=ulcase1.ctl log=ulcase1.log
retcode=`echo $?`
case "$retcode" in
0) echo "SQL*Loader execution successful" ;;
1) echo "SQL*Loader execution exited with EX_FAIL, see logfile" ;;
2) echo "SQL*Loader execution exited with EX_WARN, see logfile" ;;
3) echo "SQL*Loader execution encountered a fatal error" ;;
*) echo "unknown return code";;
esac

-- -----------------------------
load data
infile 'example.dat' "fix 11"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1, col2)

example.dat:
001, cd, 0002,fghi,
00003,lmn,
1, "pqrs",
0005,uvwx,

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

Loading Data in Stream Record Format

load data
infile 'example.dat' "str '|\n'"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1 char(5),
col2 char(7))

example.dat:
hello,world,|
james,bond,|

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

1 -- This is a sample control file
2 LOAD DATA
3 INFILE 'sample.dat'
4 BADFILE 'sample.bad'
5 DISCARDFILE 'sample.dsc'
6 APPEND
7 INTO TABLE emp
8 WHEN (57) = '.'
9 TRAILING NULLCOLS
10 (hiredate SYSDATE,
deptno POSITION(1:2) INTEGER EXTERNAL(2)
NULLIF deptno=BLANKS,
job POSITION(7:14) CHAR TERMINATED BY WHITESPACE
NULLIF job=BLANKS "UPPER(:job)",
mgr POSITION(28:31) INTEGER EXTERNAL
TERMINATED BY WHITESPACE, NULLIF mgr=BLANKS,
ename POSITION(34:41) CHAR
TERMINATED BY WHITESPACE "UPPER(:ename)",
empno POSITION(45) INTEGER EXTERNAL
TERMINATED BY WHITESPACE,
sal POSITION(51) CHAR TERMINATED BY WHITESPACE
"TO_NUMBER(:sal,'$99,999.99')",
comm INTEGER EXTERNAL ENCLOSED BY '(' AND '%'
":comm * 100"
)


Utilities
http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/ldr_concepts.htm#i1005437

SQLLDR CONTROL=sample.ctl, LOG=sample.log, BAD=baz.bad, DATA=etc.dat
USERID=scott/tiger, ERRORS=999, LOAD=2000, DISCARD=toss.dsc,
DISCARDMAX=5

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

#!/bin/sh
sqlldr scott/tiger control=ulcase1.ctl log=ulcase1.log
retcode=`echo $?`
case "$retcode" in
0) echo "SQL*Loader execution successful" ;;
1) echo "SQL*Loader execution exited with EX_FAIL, see logfile" ;;
2) echo "SQL*Loader execution exited with EX_WARN, see logfile" ;;
3) echo "SQL*Loader execution encountered a fatal error" ;;
*) echo "unknown return code";;
esac

-- -----------------------------
load data
infile 'example.dat' "fix 11"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1, col2)

example.dat:
001, cd, 0002,fghi,
00003,lmn,
1, "pqrs",
0005,uvwx,

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

Loading Data in Stream Record Format

load data
infile 'example.dat' "str '|\n'"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1 char(5),
col2 char(7))

example.dat:
hello,world,|
james,bond,|

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

1 -- This is a sample control file
2 LOAD DATA
3 INFILE 'sample.dat'
4 BADFILE 'sample.bad'
5 DISCARDFILE 'sample.dsc'
6 APPEND
7 INTO TABLE emp
8 WHEN (57) = '.'
9 TRAILING NULLCOLS
10 (hiredate SYSDATE,
deptno POSITION(1:2) INTEGER EXTERNAL(2)
NULLIF deptno=BLANKS,
job POSITION(7:14) CHAR TERMINATED BY WHITESPACE
NULLIF job=BLANKS "UPPER(:job)",
mgr POSITION(28:31) INTEGER EXTERNAL
TERMINATED BY WHITESPACE, NULLIF mgr=BLANKS,
ename POSITION(34:41) CHAR
TERMINATED BY WHITESPACE "UPPER(:ename)",
empno POSITION(45) INTEGER EXTERNAL
TERMINATED BY WHITESPACE,
sal POSITION(51) CHAR TERMINATED BY WHITESPACE
"TO_NUMBER(:sal,'$99,999.99')",
comm INTEGER EXTERNAL ENCLOSED BY '(' AND '%'
":comm * 100"
)

ocm4  Implement transportable tablespaces between homogeneous and heterogeneous systems (using different methods of moving files)
https://shenh.tripod.com/Oracleblog/index.blog/1824997/ocm4-implement-transportable-tablespaces/

begin
sys.dbms_tts.transport_set_check ( ts_list => 'TS1,TS2' );
end;
/

select * from sys.transport_set_violations;

For Source DB:
step 1): read only tablespace (mandatory step)
alter tablespace ts1 read only;
alter tablespace ts2 read only;

step 2):
exp '/ as sysdba'
transport_tablespace=y
tablespaces=$tbs_list
file=tts_exp.dmp
log=tts_exp.log


step 3):
alter tablespace xxxx read write;

For destination DB:
step 1):
destination offline and drop the tablespace if exists

step 2):
Import = imp file=tt.dmp log=tt.log tablespaces=test transportable_tablespace=y datafiles=(.......,
only avail in expdb/impdb combination:
REMAP_DATAFILE Redefine datafile references in all DDL statements.
REMAP_SCHEMA Objects from one schema are loaded into another schema.
REMAP_TABLESPACE Tablespace object are remapped to another tablespace.

........)

imp \'/ as sysdba \' transport_tablespace=y tablespaces=ts1,ts2 file=tts.dmp parfile=imp.par log=tts_log

imp tts.par
datafiles=\
/u01/oradata/orcl/orcl_ts1_01.dbf,\
/u02/oradata/orcl/orcl_ts2_01.dbf

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

expdp system/manager DUMPFILE=tts.dmp DIRECTORY=trans_dir TRANSPORT_TABLESPACES=tts TRANSPORT_FULL_CHECK = TRUE


impdp system/manager parfile=c:\tts\trans.par

 -- create the following datapump parameter file: save it as trans.par
DUMPFILE=tts.dmp
DIRECTORY=trans_dir
REMAP_SCHEMA=uwclass:scott
TRANSPORT_DATAFILES='c:\temp\tts.dbf'

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

SQL> select name, platform_id,platform_name   
2 from   v$database;

NAME       PLATFORM_ID       PLATFORM_NAME
-------    -----------       -----------------------
GRID                 2       Solaris[tm] OE (64-


SELECT * FROM v$transportable_platform ORDER BY 1;

SQL> select * from v$transportable_platform order by platform_id;

PLATFORM_ID PLATFORM_NAME                       ENDIAN_FORMAT
----------- ----------------------------------- --------------
          1 Solaris[tm] OE (32-bit)             Big
          2 Solaris[tm] OE (64-bit)             Big
          3 HP-UX (64-bit)                      Big
          4 HP-UX IA (64-bit)                   Big
          5 HP Tru64 UNIX                       Little
          6 AIX-Based Systems (64-bit)          Big
          7 Microsoft Windows IA (32-bit)       Little
          8 Microsoft Windows IA (64-bit)       Little
          9 IBM zSeries Based Linux             Big
         10 Linux IA (32-bit)                   Little
         11 Linux IA (64-bit)                   Little
         12 Microsoft Windows 64-bit for AMD    Little
         13 Linux 64-bit for AMD                Little
         15 HP Open VMS                         Little
         16 Apple Mac OS                        Big

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

RMAN>CONVERT TABLESPACE lmt_xact
  TO PLATFORM='Solaris[tm] OE (32-bit)'
  FORMAT='/u03/oracle/oradata/rptrepos';

RMAN> convert tablespace users
2> to platform 'HP-UX (64-bit)'
3>  format='/home/oracle/rman_bkups/%N_%f';

RMAN> convert tablespace users, maints
2> to platform 'HP-UX (64-bit)'
3> format='/home/oracle/rman_bkups/%N_%f'
4> parallelism = 5;

RMAN> convert tablespace users
2> to platform 'HP-UX (64-bit)'
3> db_file_name_convert '/usr/oradata/dw10/dw10','/home/oracle/rman_bkups'
4> ;

RMAN> convert
2> datafile '/usr/oradata/dw10/dw10/users01.dbf'
3> format '/home/oracle/rman_bkups/%N_%f'
4> ;


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

http://www.oracle.com/technology/pub/articles/10gdba/week16_10gdba.html

http://www.databasejournal.com/features/oracle/article.php/3600931

http://www.dbazine.com/olc/olc-articles/ault5

http://www.oracle.com/technology/deploy/availability/htdocs/xtts.htm

ocm4  Choose the appropriate partition method (range, hash, list, and composite)
https://shenh.tripod.com/Oracleblog/index.blog/1824999/ocm4-choose-the-appropriate-partition-method/

How to Implement Partitioning in Oracle Versions 8 and 8i
Doc ID: Note:105317.1

Admin Guide: chapter 17
http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/partiti.htm#ADMIN017


10g Concepts: chapter 18
http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/partconc.htm#CNCPT212

1):
Range Partitioning Example
CREATE TABLE sales_range
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY RANGE(sales_date)
(
PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY')),
PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','MM/DD/YYYY')),
PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','MM/DD/YYYY')),
PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','MM/DD/YYYY'))
);

2):
List Partitioning Example
CREATE TABLE sales_list
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_state VARCHAR2(20),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY LIST(sales_state)
(
PARTITION sales_west VALUES('California', 'Hawaii'),
PARTITION sales_east VALUES ('New York', 'Virginia', 'Florida'),
PARTITION sales_central VALUES('Texas', 'Illinois'),
PARTITION sales_other VALUES(DEFAULT)
);

3):
Hash Partitioning Example
CREATE TABLE sales_hash
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
week_no NUMBER(2))
PARTITION BY HASH(salesman_id)
PARTITIONS 4
STORE IN (ts1, ts2, ts3, ts4);

4):
Composite Partitioning Range-Hash Example
CREATE TABLE sales_composite
(salesman_id NUMBER(5),
salesman_name VARCHAR2(30),
sales_amount NUMBER(10),
sales_date DATE)
PARTITION BY RANGE(sales_date)
SUBPARTITION BY HASH(salesman_id)
SUBPARTITION TEMPLATE(
SUBPARTITION sp1 TABLESPACE ts1,
SUBPARTITION sp2 TABLESPACE ts2,
SUBPARTITION sp3 TABLESPACE ts3,
SUBPARTITION sp4 TABLESPACE ts4)
(PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY'))
PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','MM/DD/YYYY'))
PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','MM/DD/YYYY'))
PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','MM/DD/YYYY'))
PARTITION sales_may2000 VALUES LESS THAN(TO_DATE('06/01/2000','MM/DD/YYYY')));

CREATE TABLE emp (deptno NUMBER, empname VARCHAR(32), grade NUMBER)
PARTITION BY RANGE(deptno) SUBPARTITION BY HASH(empname)
SUBPARTITIONS 8 STORE IN (ts1, ts3, ts5, ts7)
(PARTITION p1 VALUES LESS THAN (1000),
PARTITION p2 VALUES LESS THAN (2000)
STORE IN (ts2, ts4, ts6, ts8),
PARTITION p3 VALUES LESS THAN (MAXVALUE)
(SUBPARTITION p3_s1 TABLESPACE ts4,
SUBPARTITION p3_s2 TABLESPACE ts5));

-- range-list
CREATE TABLE sample_regional_sales
(deptno number, item_no varchar2(20),
txn_date date, txn_amount number, state varchar2(2))
PARTITION BY RANGE (txn_date)
SUBPARTITION BY LIST (state)
(PARTITION q1_1999 VALUES LESS THAN (TO_DATE('1-APR-1999','DD-MON-YYYY'))
TABLESPACE tbs_1
(SUBPARTITION q1_1999_northwest VALUES ('OR', 'WA'),
SUBPARTITION q1_1999_southwest VALUES ('AZ', 'UT', 'NM'),
SUBPARTITION q1_1999_northeast VALUES ('NY', 'VM', 'NJ'),
SUBPARTITION q1_1999_southeast VALUES ('FL', 'GA'),
SUBPARTITION q1_others VALUES (DEFAULT) TABLESPACE tbs_4
),
PARTITION q2_1999 VALUES LESS THAN ( TO_DATE('1-JUL-1999','DD-MON-YYYY'))
TABLESPACE tbs_2
(SUBPARTITION q2_1999_northwest VALUES ('OR', 'WA'),
SUBPARTITION q2_1999_southwest VALUES ('AZ', 'UT', 'NM'),
SUBPARTITION q2_1999_northeast VALUES ('NY', 'VM', 'NJ'),
SUBPARTITION q2_1999_southeast VALUES ('FL', 'GA'),
SUBPARTITION q2_1999_northcentral VALUES ('SD', 'WI'),
SUBPARTITION q2_1999_southcentral VALUES ('OK', 'TX')
),
PARTITION q3_1999 VALUES LESS THAN (TO_DATE('1-OCT-1999','DD-MON-YYYY'))
TABLESPACE tbs_3
(SUBPARTITION q3_1999_northwest VALUES ('OR', 'WA'),
SUBPARTITION q3_1999_southwest VALUES ('AZ', 'UT', 'NM'),
SUBPARTITION q3_others VALUES (DEFAULT) TABLESPACE tbs_4
),
PARTITION q4_1999 VALUES LESS THAN ( TO_DATE('1-JAN-2000','DD-MON-YYYY'))
TABLESPACE tbs_4
);

-- template
CREATE TABLE emp_sub_template (deptno NUMBER, empname VARCHAR(32), grade NUMBER)
PARTITION BY RANGE(deptno) SUBPARTITION BY HASH(empname)
SUBPARTITION TEMPLATE
(SUBPARTITION a TABLESPACE ts1,
SUBPARTITION b TABLESPACE ts2,
SUBPARTITION c TABLESPACE ts3,
SUBPARTITION d TABLESPACE ts4
)
(PARTITION p1 VALUES LESS THAN (1000),
PARTITION p2 VALUES LESS THAN (2000),
PARTITION p3 VALUES LESS THAN (MAXVALUE)
);

ocm4  Choose the appropriate partition key
https://shenh.tripod.com/Oracleblog/index.blog/1825000/ocm4-choose-the-appropriate-partition-key/

 

1):

http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/partconc.htm#i449863

Partition Key
Each row in a partitioned table is unambiguously assigned to a single partition. The partition key is a set of one or more columns that determines the partition for each row. Oracle automatically directs insert, update, and delete operations to the appropriate partition through the use of the partition key. A partition key:

Consists of an ordered list of 1 to 16 columns

Cannot contain a LEVEL, ROWID, or MLSLABEL pseudocolumn or a column of type ROWID

Can contain columns that are NULLable


Top Partitioned Tables Issues
Doc ID: Note:165599.1 

 

ocm4  Choose appropriate indexing methods (local, global, prefixed, and nonprefixed)
https://shenh.tripod.com/Oracleblog/index.blog/1825002/ocm4-choose-appropriate-indexing-methods/


admin guide: chapter 17
http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/partiti.htm#i1106387

Top Partitioned Index Issues
Doc ID: Note:165309.1

1):
Creating a Range-Partitioned Global Index
CREATE INDEX month_ix ON sales(sales_month)
GLOBAL PARTITION BY RANGE(sales_month)
(PARTITION pm1_ix VALUES LESS THAN (2)
PARTITION pm2_ix VALUES LESS THAN (3)
PARTITION pm3_ix VALUES LESS THAN (4)
PARTITION pm4_ix VALUES LESS THAN (5)
PARTITION pm5_ix VALUES LESS THAN (6)
PARTITION pm6_ix VALUES LESS THAN (7)
PARTITION pm7_ix VALUES LESS THAN (8)
PARTITION pm8_ix VALUES LESS THAN (9)
PARTITION pm9_ix VALUES LESS THAN (10)
PARTITION pm10_ix VALUES LESS THAN (11)
PARTITION pm11_ix VALUES LESS THAN (12)
PARTITION pm12_ix VALUES LESS THAN (MAXVALUE));

CREATE INDEX hgidx ON tab (c1,c2,c3) GLOBAL
PARTITION BY HASH (c1,c2)
(PARTITION p1 TABLESPACE tbs_1,
PARTITION p2 TABLESPACE tbs_2,
PARTITION p3 TABLESPACE tbs_3,
PARTITION p4 TABLESPACE tbs_4);

2): local index: index columns is the same as partition key columns

CREATE INDEX loc_dept_ix ON dept(deptno) LOCAL;

CREATE INDEX emp_ix ON emp(deptno)
LOCAL STORE IN (ts7, ts8, ts9);


3):

ocm4  Perform partition maintenance operations
https://shenh.tripod.com/Oracleblog/index.blog/1825004/ocm4-perform-partition-maintenance-operations/

1): query
The following query displays the subpartition names and tablespaces:

SELECT TABLESPACE_NAME, PARTITION_NAME, SUBPARTITION_NAME
FROM DBA_TAB_SUBPARTITIONS WHERE TABLE_NAME='EMP_SUB_TEMPLATE'
ORDER BY TABLESPACE_NAME;

2): modify
ADD PARTITION
COALESCE PARTITION, COALESCE SUBPARTITION
DROP PARTITION
EXCHANGE PARTITION, EXCHANGE SUBPARTITION
MERGE PARTITIONS, MERGE SUBPARTITIONS
MODIFY DEFAULT ATTRIBUTES
MODIFY PARTITION,MODIFY SUBPARTITION
MOVE PARTITION
RENAME PARTITION
SPLIT PARTITION
TRUNCATE PARTITION

admin guide: 17 Managing Partitioned Tables and Indexes
http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/partiti.htm#i1007318

ALTER TABLE q1_sales_by_region
ADD PARTITION q1_nonmainland VALUES ('HI', 'PR')
STORAGE (INITIAL 20K NEXT 20K) TABLESPACE tbs_3
NOLOGGING;

ALTER TABLE sales ADD PARTITION q1_2000
VALUES LESS THAN (2000, 04, 01) COMPRESS
SUBPARTITIONS 8 STORE IN tbs5;

ALTER TABLE diving MODIFY PARTITION locations_us
ADD SUBPARTITION us_locs5 TABLESPACE us1;

ALTER TABLE quarterly_regional_sales
ADD PARTITION q1_2000 VALUES LESS THAN (TO_DATE('1-APR-2000','DD-MON-YYYY'))
STORAGE (INITIAL 20K NEXT 20K) TABLESPACE ts3 NOLOGGING
(
SUBPARTITION q1_2000_northwest VALUES ('OR', 'WA'),
SUBPARTITION q1_2000_southwest VALUES ('AZ', 'UT', 'NM'),
SUBPARTITION q1_2000_northeast VALUES ('NY', 'VM', 'NJ'),
SUBPARTITION q1_2000_southeast VALUES ('FL', 'GA'),
SUBPARTITION q1_2000_northcentral VALUES ('SD', 'WI'),
SUBPARTITION q1_2000_southcentral VALUES ('OK', 'TX')
);

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

ALTER INDEX q1_sales_by_region_locix
MODIFY DEFAULT ATTRIBUTES TABLESPACE tbs_4;

ALTER INDEX q1_sales_by_region_locix
REBUILD PARTITION q1_nonmainland TABLESPACE tbs_4;

ALTER INDEX hgidx ADD PARTITION p5;

ALTER TABLE ouu1
COALESCE PARTITION;

ALTER TABLE diving MODIFY PARTITION us_locations
COALESCE SUBPARTITION;

ALTER INDEX hgidx COALESCE PARTITION;

1):
ALTER TABLE sales DROP PARTITION dec98;
ALTER INDEX sales_area_ix REBUILD;

ALTER INDEX sales_area_ix REBUILD PARTITION jan99_ix;
ALTER INDEX sales_area_ix REBUILD PARTITION feb99_ix;
ALTER INDEX sales_area_ix REBUILD PARTITION mar99_ix;

2):
DELETE FROM sales WHERE TRANSID < 10000;
ALTER TABLE sales DROP PARTITION dec98;

3):
ALTER TABLE sales DROP PARTITION dec98
UPDATE INDEXES;

-- -----------------------------------
1):
ALTER TABLE sales
DISABLE CONSTRAINT dname_sales1;
ALTER TABLE sales DROP PARTITTION dec98;
ALTER TABLE sales
ENABLE CONSTRAINT dname_sales1;

2):
DELETE FROM sales WHERE TRANSID < 10000;
ALTER TABLE sales DROP PARTITION dec94;

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

ALTER INDEX npr DROP PARTITION P1;
ALTER INDEX npr REBUILD PARTITION P2;

-- ------------------------------------
ALTER TABLE table_name
DISABLE CONSTRAINT constraint_name KEEP INDEX

ALTER TABLE stocks
EXCHANGE PARTITION p3 WITH TABLE stock_table_3;

ALTER TABLE t2 EXCHANGE PARTITION p1 WITH TABLE t1
WITH VALIDATION;

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

ALTER TABLE sales EXCHANGE SUBPARTITION q3_1999_s1
WITH TABLE q3_1999 INCLUDING INDEXES;

-- ----------------------------------------
ALTER TABLE four_seasons
MERGE PARTITIONS quarter_one, quarter_two INTO PARTITION quarter_two
UPDATE INDEXES;

ALTER TABLE four_seasons MODIFY PARTITION
quarter_two REBUILD UNUSABLE LOCAL INDEXES;


ALTER TABLE q1_sales_by_region
MERGE PARTITIONS q1_northcentral, q1_southcentral
INTO PARTITION q1_central
STORAGE(MAXEXTENTS 20);

ALTER TABLE all_seasons
MERGE PARTITIONS quarter_1, quarter_2 INTO PARTITION quarter_2
SUBPARTITIONS 8;

ALTER TABLE quarterly_regional_sales
MERGE SUBPARTITIONS q1_1999_northwest, q1_1999_southwest
INTO SUBPARTITION q1_1999_west
TABLESPACE ts4;
-- -------------------------------------------
ALTER TABLE emp
MODIFY DEFAULT ATTRIBUTES FOR PARTITION p1 TABLESPACE ts1;

ALTER TABLE scubagear MODIFY PARTITION ts1 UNUSABLE LOCAL INDEXES;

ALTER TABLE dept MODIFY PARTITION p1
REBUILD UNUSABLE LOCAL INDEXES;

ALTER TABLE sales_by_region
MODIFY PARTITION region_south
ADD VALUES ('OK', 'KS');

ALTER TABLE quarterly_regional_sales
MODIFY SUBPARTITION q1_1999_southeast
ADD VALUES ('KS');

ALTER TABLE sales_by_region
MODIFY PARTITION region_south
DROP VALUES ('OK', 'KS');

ALTER TABLE quarterly_regional_sales
MODIFY SUBPARTITION q1_1999_southeast
DROP VALUES ('KS');

-- --------------------------------------
template:
ALTER TABLE emp_sub_template
SET SUBPARTITION TEMPLATE
(SUBPARTITION e TABLESPACE ts1,
SUBPARTITION f TABLESPACE ts2,
SUBPARTITION g TABLESPACE ts3,
SUBPARTITION h TABLESPACE ts4
);

You can drop a subpartition template by specifying an empty list:

ALTER TABLE emp_sub_template
SET SUBPARTITION TEMPLATE ( );

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

ALTER TABLE parts MOVE PARTITION depot2
TABLESPACE ts094 NOLOGGING COMPRESS;

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

ALTER TABLE scuba_gear MOVE SUBPARTITION bcd_types
TABLESPACE tbs23 PARALLEL (DEGREE 2);

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

ALTER TABLE scubagear RENAME PARTITION sys_p636 TO tanks;

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

ALTER TABLE sales_by_region
SPLIT PARTITION region_east VALUES ('CT', 'MA', 'MD')
INTO
( PARTITION region_east_1
TABLESPACE tbs2,
PARTITION region_east_2
STORAGE (NEXT 2M PCTINCREASE 25))
PARALLEL 5;

ALTER TABLE sales_by_region
SPLIT PARTITION region_unknown VALUES ('MT', 'WY', 'ID')
INTO
( PARTITION region_wildwest,
PARTITION region_unknown);

ALTER TABLE all_seasons SPLIT PARTITION quarter_1
AT (TO_DATE('16-dec-1997','dd-mon-yyyy'))
INTO (PARTITION q1_1997_1 SUBPARTITIONS 4 STORE IN (ts1,ts3),
PARTITION q1_1997­_2);

ALTER TABLE quarterly_regional_sales SPLIT PARTITION q1_1999
AT (to_date('15-Feb-1999','dd-mon-yyyy'))
INTO ( PARTITION q1_1999_jan_feb
TABLESPACE ts1,
PARTITION q1_1999_feb_mar
STORAGE (NEXT 2M PCTINCREASE 25) TABLESPACE ts2)
PARALLEL 5;

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

ALTER TABLE sales TRUNCATE PARTITION dec98;
ALTER INDEX sales_area_ix REBUILD;

ocm4  Maintain indexes on a partitioned table
https://shenh.tripod.com/Oracleblog/index.blog/1825005/ocm4-maintain-indexes-on-a-partitioned-table/

 SKIP_UNUSABLE_INDEXES init.ora parameter
UPDATE INDEXES sub clauses

1): By default, the following operations on partitions on a heap-organized table mark all global indexes as unusable:

ADD (HASH)
COALESCE (HASH)
DROP
EXCHANGE
MERGE
MOVE
SPLIT
TRUNCATE

ALTER TABLE DROP PARTITION P1 UPDATE INDEXES;

How to Backup Partition of Range Partitioned Table with Local Indexes
Doc ID: Note:412264.

 

ocm4  Create and manage LOB segments
https://shenh.tripod.com/Oracleblog/index.blog/1825007/ocm4-create-and-manage-lob-segments/

http://download-east.oracle.com/docs/cd/B14117_01/appdev.101/b10796/adlob_ta.htm

http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_3001.htm

http://www.idevelopment.info/data/Oracle/DBA_tips/LOBs/LOBS_2.shtml

CREATE TABLE test_lobtable (
id NUMBER
, xml_file CLOB
, image BLOB
, log_file BFILE
)
LOB (xml_file, image)
STORE AS (
TABLESPACE lob_data
CHUNK 4096
CACHE
STORAGE (MINEXTENTS 2)
INDEX (
TABLESPACE lob_index
STORAGE (MAXEXTENTS UNLIMITED)
)
)
/

ALTER TABLE test_lobtable
ADD (image2 BLOB)
LOB (image2) STORE AS image2_lob_seg (
TABLESPACE lob_data
CHUNK 4096
PCTVERSION 5
ENABLE STORAGE IN ROW
INDEX image2_lob_idx (
TABLESPACE lob_index
)
)
/

ALTER TABLE test_lobtable
MODIFY LOB (image) (
STORAGE (NEXT 1M)
CACHE
)
/

ALTER TABLE test_lobtable
MOVE TABLESPACE users2
LOB (xml_file) STORE AS (
TABLESPACE lob_data2
)
/

SELECT
table_name "Table"
, column_name "Column"
, segment_name "Segment"
, index_name "Index"
FROM user_lobs
WHERE table_name = 'TEST_LOBTABLE';


SELECT
segment_name "Segment"
, segment_type "Type"
, tablespace_name "Tablespace"
FROM user_segments
ORDER BY segment_name DESC;

Segment TS Type Tablespace
------------------------- ------------ ------------------------------
XML_FILE_LOB_SEG LOBSEGMENT LOB_DATA
XML_FILE_LOB_IDX LOBINDEX LOB_DATA
TEST_LOBTABLE TABLE USERS
IMAGE_LOB_SEG LOBSEGMENT LOB_DATA2
IMAGE_LOB_IDX LOBINDEX LOB_DATA2
IMAGE2_LOB_SEG LOBSEGMENT LOB_DATA
IMAGE2_LOB_IDX LOBINDEX LOB_DATA

ocm4  Apply parallelism appropriately
https://shenh.tripod.com/Oracleblog/index.blog/1825009/ocm4-apply-parallelism-appropriately/ 


1): data warehouse guide: Parallelization Rules for SQL Statements
http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/usingpe.htm#i1007537

2): data warehouse guide: query and monitor
http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/usingpe.htm#i1008510

ocm4  Tune memory for parallel operations
https://shenh.tripod.com/Oracleblog/index.blog/1825010/ocm4-tune-memory-for-parallel-operations/

On systems where parallel execution will never be used, PARALLEL_MAX_SERVERS can be set to zero.

On large systems with abundant SGA memory, PARALLEL_EXECUTION_MESSAGE_SIZE can be increased to improve throughput.

data warehouse guide
http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/usingpe.htm#sthref2210

ocm4  Set parallel parameters
https://shenh.tripod.com/Oracleblog/index.blog/1825011/ocm4-set-parallel-parameters/


1):
show parameter parallel

eg: PARALLEL_MAX_SERVERS


2):
ALTER TABLE orders PARALLEL 4;
ALTER INDEX iorders PARALLEL 4;
SELECT /*+ PARALLEL(orders, 4) */ COUNT(*) FROM orders;


ALTER SESSION DISABLE PARALLEL DML|DDL|QUERY
ALTER SESSION ENABLE PARALLEL DML|DDL|QUERY

eg:
ALTER SESSION DISABLE PARALLEL DDL;
ALTER SESSION ENABLE PARALLEL DML;

ALTER SESSION FORCE PARALLEL DDL PARALLEL 5;

 


Posted by shenh at 10:58 PM EST
Updated: Tuesday, 6 January 2009 11:23 PM EST
OCM 3: Managing Database Availability

ocm3  Create a recovery catalog database
https://shenh.tripod.com/Oracleblog/index.blog/1824950/ocm3create-a-recovery-catalog-database/

http://download-east.oracle.com/docs/cd/B19306_01/backup.102/b14191/rcmcatdb001.htm

CREATE USER rman IDENTIFIED BY cat
TEMPORARY TABLESPACE temp
DEFAULT TABLESPACE tools
QUOTA UNLIMITED ON tools;

sql>GRANT RECOVERY_CATALOG_OWNER TO rman;


rman
RMAN> CONNECT CATALOG rman/cat@catdb

Run the CREATE CATALOG command to create the catalog. The creation of the catalog can take several minutes. If the catalog tablespace is this user's default tablespace, then you can run this command:

CREATE CATALOG;

You can specify the tablespace name for the catalog in the CREATE CATALOG command. For example:

CREATE CATALOG TABLESPACE cat_ts;

You can check the results by using SQL*Plus to query the recovery catalog to see which tables were created:

SQL> SELECT TABLE_NAME FROM USER_TABLES;

ocm3  Configure Recovery Manager
https://shenh.tripod.com/Oracleblog/index.blog/1824951/ocm3configure-recovery-manager/


http://www.globusz.com/ebooks/Oracle/00000018.htm#3

register, unregister a target database

http://download-east.oracle.com/docs/cd/B19306_01/backup.102/b14191/rcmcatdb002.htm

% rman TARGET / CATALOG rman/cat@catdb

If the target database is not mounted, then mount or open it:

RMAN> STARTUP MOUNT;

Register the target database in the connected recovery catalog:

RMAN> REGISTER DATABASE;

RMAN> REPORT SCHEMA;

Cataloging Older Files in the Recovery Catalog


If you have datafile copies, backup pieces or archive logs on disk, you can catalog them in the recovery catalog using the CATALOG command. When using a recovery catalog, cataloging older backups that have aged out of the control file lets RMAN use the older backups during restore operations. For example:

RMAN> CATALOG DATAFILECOPY '/disk1/old_datafiles/01_01_2003/users01.dbf';
RMAN> CATALOG ARCHIVELOG '/disk1/arch_logs/archive1_731.dbf',
'/disk1/arch_logs/archive1_732.dbf';
RMAN> CATALOG BACKUPPIECE '/disk1/backups/backup_820.bkp';
You can also catalog multiple backup files in a directory at once, using the CATALOG START WITH command, as shown in this example:

RMAN> CATALOG START WITH '/disk1/backups/';

RMAN lists the files to be added to the RMAN repository and prompts for confirmation before adding the backups.

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

unregister:

LIST BACKUP SUMMARY
LIST COPY SUMMARY

DELETE BACKUP DEVICE TYPE sbt;
DELETE BACKUP DEVICE TYPE DISK;
DELETE COPY;

RMAN will list the backups that it intends to delete and prompt for confirmation before deleting them.

Run the UNREGISTER DATABASE command. For example:

UNREGISTER DATABASE;

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

The script removes all records with status DELETED from the recovery catalog.
@?/rdbms/admin/prgrmanc.sql

-- ---------------------------------------------
RESYNC CATALOG :
populate controlfile information about the database to rman catalog

CONTROL_FILE_RECORD_KEEP_TIME


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

instance recovery: FAST_START_MTTR_TARGET
1): ALTER SYSTEM SET FAST_START_MTTR_TARGET=30;

2): The maximum value for FAST_START_MTTR_TARGET is 3600 seconds (one hour).

3):
SQL> SELECT TARGET_MTTR, ESTIMATED_MTTR
FROM V$INSTANCE_RECOVERY;

-- -----------------------------------
sbtest:
$ORACLE_HOME/lib/libobk.so on UNIX

RUN
{
ALLOCATE CHANNEL c1 DEVICE TYPE sbt
PARMS='SBT_LIBRARY=/vendor/lib/some_mm_lib.so',
'ENV=(NSR_SERVER=tape_svr,NSR_CLIENT=oracleclnt,NSR_GROUP=oracle_tapes)';
}

% sbttest some_file.f -trace sbtio.log
% sbttest tbs_33.f -dbname prod

ocm3  Use Recovery Manager to perform database backups
https://shenh.tripod.com/Oracleblog/index.blog/1824952/ocm3use-recovery-manager-to-perform-database-backups/

rman target=/
{
allocate channel c1 ;
allocate channel c2 ;
allocate channel c3 ;
backup incremental level=0 database;
}

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

LIST SCRIPT NAMES;
LIST GLOBAL SCRIPT NAMES;
LIST ALL SCRIPT NAMES;

CREATE SCRIPT full_backup
{
BACKUP DATABASE PLUS ARCHIVELOG;
DELETE OBSOLETE;
}

RUN { EXECUTE SCRIPT full_backup; }

PRINT SCRIPT full_backup;
PRINT SCRIPT full_backup TO FILE 'my_script_file.txt';

REPLACE SCRIPT full_backup
{
BACKUP DATABASE PLUS ARCHIVELOG;
}

DELETE SCRIPT 'full_backup'; 

 

ocm3  Use Recover Manager to perform complete database restore and recovery operations
https://shenh.tripod.com/Oracleblog/index.blog/1824953/ocm3use-recover-manager-to-perform-complete-database-restore-and-recovery-operations/

Best Test Case:
http://www.oracle.com.cn/viewthread.php?tid=50419

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

1): restore a bad control file

rman nocatalog target "sys/sunsdl"
RMAN> configure controlfile autobackup on;
RMAN> configure controlfile autobackup format for device type disk to 'c:\temp\%F';
RMAN> backup database;

text file:
SQL> alter database backup controlfile to trace;

binary file:
SQL> alter database backup controlfile to 'c:\temp\controlfile.bak';

RMAN> copy CURRENT CONTROLFILE TO 'c:\cf.cpy';

recover:
SQL> shutdown abort;
SQL> startup nomount

 CREATE CONTROLFILE REUSE DATABASE "DF" NORESETLOGS  ARCHIVELOG
  2  --  SET STANDBY TO MAXIMIZE PERFORMANCE
  3      MAXLOGFILES 5
  4      MAXLOGMEMBERS 3
  5      MAXDATAFILES 100
  6      MAXINSTANCES 1
  7      MAXLOGHISTORY 226
  8  LOGFILE
  9    GROUP 1 'C:\ORACLE\ORADATA\PDF\REDO01.LOG'  SIZE 100M,
10    GROUP 2 'C:\ORACLE\ORADATA\PDF\REDO02.LOG'  SIZE 100M,
11    GROUP 3 'C:\ORACLE\ORADATA\PDF\REDO03.LOG'  SIZE 100M
12  -- STANDBY LOGFILE
13  DATAFILE
14    'C:\ORACLE\ORADATA\PDF\SYSTEM01.DBF',
15    'C:\ORACLE\ORADATA\PDF\UNDOTBS01.DBF',
16    'C:\ORACLE\ORADATA\PDF\INDX01.DBF',
17    'C:\ORACLE\ORADATA\PDF\TOOLS01.DBF',
18    'C:\ORACLE\ORADATA\PDF\USERS01.DBF'
19  CHARACTER SET ZHS16GBK
20  ;

SQL> alter database open;
SQL> startup
SQL> recover database ;  --because of shutdown abort
SQL> alter database open;

SQL> startup mount
SQL> recover database using backup controlfile;
SQL> recover database using backup controlfile until cancel;
SQL> alter database open resetlogs;

select CHECKPOINT_CHANGE# from v$database;

SQL> select GROUP#,SEQUENCE#,archived, STATUS from v$log;

    GROUP#  SEQUENCE# ARC STATUS
---------- ---------- --- ----------------
         1          5 NO  CURRENT
         2          3 YES ACTIVE 
         3          4 YES ACTIVE

SQL> select resetlogs_change# - 1,CONTROLFILE_CHANGE# from v$database;

RESETLOGS_CHANGE#-1 CONTROLFILE_CHANGE#
------------------- -------------------
              68658               69410

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

RMAN> restore controlfile from autobackup;
RMAN> set dbid=3171861129  -- if startup nomount is run by rman, don't need this
RMAN> SET CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/temp/%F';

alter database clear logfile group 1;
alter database clear logfile group 2;

SQL> alter database open noresetlogs;
SQL> alter database open resetlogs;

SQL> archive log list;
SQL> alter system switch logfile;

SQL> select GROUP#,SEQUENCE#,archived, STATUS from v$log;

    GROUP#  SEQUENCE# ARC STATUS
---------- ---------- --- ----------------
         1          2 YES ACTIVE
         2          1 YES INACTIVE
         3          3 NO  CURRENT
-- ----------------------------------------------------------
-- ----------------------------------------------------------
-- ----------------------------------------------------------

RMAN>  backup format 'c:\noarch_%s%p1.bak' database;
RMAN> copy current controlfile to 'c:\currcont.ctl';

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

RMAN> run {
?uro;€?uro;€?uro;€ allocate channel test type disk;
?uro;€?uro;€?uro;€ restore controlfile to 'd:\control.ctl';
       release channel test;
?uro;€?uro;€?uro;€}

RMAN> run {
        set until time='2005-02-17 15:01:20';
        restore database;
        recover database;
        alter database open resetlogs;
        }

RMAN> register database;
     RMAN> list incarnation of database;
     RMAN> reset database;
     RMAN> list incarnation of database;
    
SQL> alter database clear unarchived logfile 'D:\ORACLE\ORADATA\ORACLE\REDO03.LOG';                                                                                                                                           
SQL> alter database clear unarchived logfile 'D:\ORACLE\ORADATA\ORACLE\REDO02.LOG';                                                                            
SQL> alter database clear unarchived logfile 'D:\ORACLE\ORADATA\ORACLE\REDO01.LOG';

RMAN> run {
       allocate channel test type disk;
       SET ARCHIVELOG DESTINATION TO 'D:\oracle\oradata\archive';
       RESTORE ARCHIVELOG ALL;
       release channel test;
     }

STARTUP MOUNT
     RMAN> run {
     2> restore datafile 1;
     3> recover datafile 1;
     4> alter database open;
     5> }
    
RMAN> run {
     2> restore tablespace system;
     3> recover tablespace system;
     4> alter database open;
     5> }

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

select US#,NAME,ts#,STATUS$,FLAGS from undo$;

*.undo_management='AUTO'
*.undo_retention=10800
*.undo_tablespace='UNDOTBS1'
_allow_resetlogs_corruption=true
_corrupted_rollback_segments=(_SYSSMU1$,_SYSSMU2$,_SYSSMU3$,_SYSSMU4$,_SYSSMU5$,_SYSSMU6$,_SYSSMU7$,_SYSSMU8$,_SYSSMU9$,_SYSSMU10$,_SYSSMU11$)
_offline_rollback_segments=true

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

ocm3  Set Flashback Database parameters
https://shenh.tripod.com/Oracleblog/index.blog/1824954/ocm3set-flashback-database-parameters/


http://www.globusz.com/ebooks/Oracle/00000018.htm

1. flashback logs
2. recyclebin
3. undo tablespace and undo retention

DB_RECOVERY_FILE_DEST=/u01/...
DB_RECOVERY_FILE_DEST_SIZE=20G
DB_FLASHBACK_RETENTION_TARGET=1440

ALTER SYSTEM SET DB_RECOVERY_FILE_DEST=$ORACLE_BASE/flash_recovery_area/mylcl/
ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE=20G;
SQL>archive log list #-- Ensure that the database is in archive log mode
SQL> ALTER DATABASE FLASHBACK ON;
DISABLE FLASH BACK
SQL> ALTER DATABASE FLASHBACK OFF;

-- ------------------------------------------------
startup MOUNT EXCLUSIVE ;
ALTER DATABASE FLASHBACK ON;
ALTER DATABASE OPEN;
SELECT FLASHBACK_ON FROM V$DATABASE;

ALTER TABLESPACE USERS FLASHBACK OFF;  

 

ocm3  Monitor Flashback Database logs and statistics
https://shenh.tripod.com/Oracleblog/index.blog/1824955/ocm3monitor-flashback-database-logs-and-statistics/

V$FLASHBACK_DATABASE_STAT
V$FLASHBACK_DATABASE_LOG

select logon_user, operation, table_name, table_owner from flashback_transaction_query where hextoraw(xid) = '04001E0015020000';

http://kevin.allenpress.com/docs/oracle10g/backup.102/b14192/rpfbdb003.htm

http://www.globusz.com/ebooks/Oracle/00000019.htm

ocm3  Perform a Flashback Database operation
https://shenh.tripod.com/Oracleblog/index.blog/1824956/ocm3perform-a-flashback-database-operation/

init.ora
db_recovery_file_dest
db_recovery_file_dest_size

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

sql> startup mount exclusive;
sql> alter database flashback on;

-- ------------------------------------
1. shudown the database;
2. startup the database in mount state;
3. sql> flashback database to
timestamp to_timestamp('2004-12-16 16:10:10', 'YYYY-MM-DD HH24:MI:SS');
3a): sql>flashback database to scn 1329643;
4. open the database -- open resetlogs;

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


http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_flashback.htm

http://orafaq.com/node/50

http://www.globusz.com/ebooks/Oracle/00000019.htm

V$DATABASE
V$FLASHBACK_ DATABASE_LOG
V$FLASHBACK_ DATABASE_STAT

http://www.oracle.com/technology/obe/obe10gdb/ha/flashback/flashback.htm

http://www.oracle.com/technology/oramag/oracle/flashback/index.html
http://www.oracle.com/technology/oramag/oracle/06-nov/o66recovery.html
http://www.oracle.com/technology/oramag/oracle/05-may/o35ocp.html
http://www.oracle.com/technology/oramag/oracle/05-mar/o25ocp.html
http://www.oracle.com/technology/oramag/oracle/04-may/o34tech_avail.html

http://www.oracle.com/technology/pub/articles/10gdba/week5_10gdba.html


http://www.oracle-base.com/articles/10g/Flashback10g.php

ocm3  Configure a flash recovery area
https://shenh.tripod.com/Oracleblog/index.blog/1824957/ocm3configure-a-flash-recovery-area/


http://www.oracleadvice.com/10g/10g_RMAN.htm

db_recovery_file_dest_size # Set size of flash recovery area
db_recovery_file_dest # Set location of flash recovery area. Turns on OMF feature.

Contents
Datafile: copies Created by the new ‘BACKUP AS COPY’ RMAN command

Controlfile auto-backups Including SPFILEs

Archived redo logs: Oracle automatically housekeeps old files

Flashback logs: Changed block copies used to reconstruct datafiles

RMAN files / backupsets: Created by RMAN

*Online redo logs: Oracle can generate names of multiplexed copies
log_archive_dest_n=db_recovery_file_dest

*Current Controlfile: Multiplexed copy


The log_archive_dest and log_archive_duplex_dest parameters are not compatible with a flash recovery area. You must use log_archive_dest_n instead.

log_archive_dest_10 is implicitly set to the db_recovery_file_dest.

OMF: you should use different locations for
• db_create_file_dest
• db_create_online_log_dest_n
• db_recovery_file_dest

control file location:
control_files: init.ora create one copy of each named file (non-OMF)
db_create_online_log_dest_n: Place one controlfile copy in each of db_create_online_log_dest_n
db_create_file_dest & db_recovery_file_dest: one controlfile copy each
db_recovery_file_dest: OMF controlfile in the flash recovery area only
None non-OMF controlfile in a platform-dependent place


online redo logs location:
1. Place one member in each of db_create_online_log_dest_n up to MAXLOGMEMBERS
2. Place one member in each of db_create_file_dest & db_recovery_file_dest
3. Create one member in db_recovery_file_dest as a permanent file
4. Create non-OMF online redo logs in a platform-dependent place

 


Posted by shenh at 10:02 PM EST
Updated: Tuesday, 6 January 2009 10:16 PM EST
OCM2: Enterprise Manager Grid Control
ocm2  Install the Enterprise Manager Grid Control software
https://shenh.tripod.com/Oracleblog/index.blog/1824922/ocm2-install-the-enterprise-manager-grid-control-software/

http://static7.userland.com/oracle/gems/alejandroVargas/GridControl10gR2Install.pdf

http://download.oracle.com/docs/cd/B12037_01/em.101/b12013/firewalls.htm


port info:
$ORACLE_HOME/sysman/setupinfo.txt
ORACLE_HOME/sysman/config/emoms.properties
ORACLE_HOME/install/portlist.ini

# Start everything
/u01/app/oracle/product/10.2.0/db10g/bin/dbstart
/u01/app/oracle/product/10.2.0/oms10g/opmn/bin/opmnctl startall
/u01/app/oracle/product/10.2.0/agent10g/bin/emctl start agent

# Stop everything
/u01/app/oracle/product/10.2.0/agent10g/bin/emctl stop agent
/u01/app/oracle/product/10.2.0/oms10g/opmn/bin/opmnctl stopall
/u01/app/oracle/product/10.2.0/db10g/bin/dbshut

http://www.iselfschooling.com/oracle10g/Grid.htm




http://oracle.iselfschooling.com:7777/em

http://njds0036:7777/em

http://gcds0040.private.linksynergy.com:4889/em

sysman sys password



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

http://www.itpub.net/224872.html

http://www.google.com/search?hl=en&q=site%3Awww.oracle.com+obe+gridcontrol

http://www.oracle.com/technology/obe/obe10gemgc_10202/install/install.htm

http://www.oracle.com/technology/obe/obe10gemgc_10203/patching/patching.htm

http://www.oracle.com/technology/obe/obe10gem/index.html
http://www.oracle.com/technology/obe/obe10gem/indexR1.html
http://www.oracle.com/technology/obe/obe10gemgc_10202/index.html
http://www.oracle.com/technology/obe/obe10gemgc_10202/patching/patching.htm
http://www.oracle.com/technology/obe/obe10gemgc_10203/index.html

http://www.oracle.com/technology/obe/obe10gemgc_10203/patchwizard/patchwizard.htm

http://www.oracle.com/technology/obe/obe10gem/grid/ctrlmng/ctrlmng.htm

http://www.oracle.com/technology/obe/obe10gem/install/index.html
http://www.oracle.com/technology/obe/obe10gem/install/gridinst/gridinst.htm
http://www.oracle.com/technology/obe/obe10gem/install/agentinst/agentinst.htm
http://www.oracle.com/technology/obe/obe10gem/install/mngadmin/mngadmin.htm
http://www.oracle.com/technology/obe/obe10gem/install/addwebapp/addwebapp.htm

http://www.oracle.com/technology/obe/obe10gemgc_10202/patchwizard/patchwizard.htm

http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/enterprise_manager_configuration/enterprise_configuration_and_policies.htm

http://www.oracle.com/technology/obe/obe10gemgc_10202/host/host.htm

http://www.oracle.com/technology/obe/obe10gemgc_10202/slm/slm.htm https://shenh.tripod.com/Oracleblog/index.blog/1824923/ocm2-configure-the-enterprise-manager-repository/


ocm2  Configure the Enterprise Manager repository
http://www.oracle-base.com/articles/10g/Oracle10gR2GridControlInstallationOnRedHatAndCentOS.php 

 


http://users.telenet.be/oraguy.be/Papers/configure%20the%20database%20control%20repository.pdf

-- -----------------------------------
Manually configure the Oracle 10g EM dbconsole
emca -deconfig dbcontrol db -repos drop

-- drop the sysman schema by following command
emca -deconfig dbcontrol db -repos drop

-- create it again
emca -deconfig dbcontrol db -repos create.

emca -repos create
emca -config dbcontrol db

http://10.130.132.94/temp/phpbb2/viewtopic.php?t=108

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

sysman

emctl emctl status dbconsole emctl status agent
emca
repmanager

$ORACLE_HOME\sysman\admin\emdrep\bin\RepManager -connect UTF8 -action drop

%ORACLE_HOME%\install\portlist.ini

http://www.oracle.com/technology/deploy/availability/pdf/EM_HA_Arch_10gR1.pdf
http://www.oracle.com/technology/deploy/availability/pdf/MAA_WP_10gR2_EnterpriseManagerBestPractices.pdf


Software download db2 : hp-ux ibm-aix
http://www.itpub.net/634237.html

ocm2  Create Enterprise Manager Grid Control users
https://shenh.tripod.com/Oracleblog/index.blog/1824924/ocm2-create-enterprise-manager-grid-control-users/

grid control home --> setup --> administrators --> create

Creating Roles and Administrators
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/creating_roles_administrators/creating_administrators_and_roles.htm



http://www.oracle.com/technology/obe/obe10gEMR2/quick_start/index.html




Preferred Credentials (user password etc )
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/preferred_credentials/preferred_credentials.htm

System Monitoring ( lots of stuff: user-define, baseline )
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/system_monitoring/system_monitoring.htm

Creating Groups ( operation applying to all targets in a group)
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/groups/groups.htm


System and Services ( define a system and a service, and use Root Cause Analysis.)
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/system_services/system_services.htm

Enterprise Configuration Management (hardware,software change information )
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/enterprise_manager_configuration/enterprise_configuration_and_policies.htm

Provisioning (patching,clone db)
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/provisioning/provisioning.htm

Information Publisher (create, schedule, and publish reports)
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/information_publishers/information_publishers.htm


Management Plug-ins (third party software)
management plug-in is a target type provided by the user or a third party to extend Enterprise Manager's set of predefined target types.
http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/extensibility/extensibility.htm 


ocm2  Use Enterprise Manager to modify a database configuration
https://shenh.tripod.com/Oracleblog/index.blog/1824925/ocm2-use-enterprise-manager-to-modify-a-database-configuration/

ocm2  Configure Enterprise Manager to modify a database availability
https://shenh.tripod.com/Oracleblog/index.blog/1824927/ocm2-configure-enterprise-manager-to-modify-a-database-availability/

select a database over databases or target --> adminitration


ocm2  Create and manage jobs
https://shenh.tripod.com/Oracleblog/index.blog/1824929/ocm2-create-and-manage-jobs/

Creating Jobs

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_job.htm#BABHCBFD


http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/jobs/creating_jobs.htm

grid control home --> jobs (tab)

1):
init.ora
job_queue_processes = 10

2):
dba_jobs

3):
dbms_job.*


dba_jobs_running

BEGIN
DBMS_JOB.CHANGE(14144, null, null, 'sysdate+3');
COMMIT;
END;

note: must commit;

http://download-east.oracle.com/docs/cd/B14117_01/appdev.101/b10802/d_job.htm#996728

http://www.psoug.org/reference/dbms_job.html

http://www.dba-oracle.com/tips_oracle_dbms_job.htm


DBMS_SCHEDULER

 


ocm2  Create and monitor alerts
https://shenh.tripod.com/Oracleblog/index.blog/1824927/ocm2-configure-enterprise-manager-to-modify-a-database-availability/

all targets (or other ) --> manage metrics --> edit thresholds

http://www.globusz.com/ebooks/Oracle/00000014.htm

DBMS_SERVER_ALERT.*

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_salt.htm#sthref6921

1):
DBMS_SERVER_ALERT.SET_THRESHOLD(
DBMS_SERVER_ALERT.CPU_TIME_PER_CALL,
DBMS_SERVER_ALERT.OPERATOR_GE, '8000',
DBMS_SERVER_ALERT.OPERATOR_GE, '10000',
1, 2, 'inst1',
DBMS_SERVER_ALERT.OBJECT_TYPE_SERVICE, 'dev.oracle.com');

a warning alert is issued when CPU time exceeds 8000 microseconds for each user call and a critical alert is issued when CPU time exceeds 10,000 microseconds for each user call.

The observation period is set to 1 minute. This period specifies the number of minutes that the condition must deviate from the threshold value before the alert is issued.

The number of consecutive occurrences is set to 2. This number specifies how many times the metric value must violate the threshold values before the alert is generated.

The name of the instance is set to inst1.

The constant DBMS_ALERT.OBJECT_TYPE_SERVICE specifies the object type on which the threshold is set. In this example, the service name is dev.oracle.com.

Note: If you don’t want Oracle to send any metric-based alerts, simply set the warning value and the critical value to NULL.


2):
DBMS_SERVER_ALERT.GET_THRESHOLD(
metrics_id IN NUMBER,
warning_operator OUT NUMBER,
warning_value OUT VARCHAR2,
critical_operator OUT NUMBER,
critical_value OUT VARCHAR2,
observation_period OUT NUMBER,
consecutive_occurrences OUT NUMBER,
instance_name IN VARCHAR2,
object_type IN NUMBER,
object_name IN VARCHAR2)




-- ------------------------------------------------
DBA_ALERT_HISTORY
dba_outstanding_alerts
dba_thresholds

v_$active_session_history
dba_advisor_journal
dba_advisor_objects
dba_advisor_parameters
dba_advisor_rationale
dba_advisor_recommendations
dba_advisor_sqlw_journal
dba_advisor_tasks
dba_advisor_usage
dba_hist_snapshot
dba_alert_history
dba_outstanding_alerts
dba_thresholds


http://download-east.oracle.com/docs/cd/B14099_19/manage.1012/b16242/udm2.htm 


ocm2  Create notifications
https://shenh.tripod.com/Oracleblog/index.blog/1824931/ocm2-create-notifications/

Notifications ( executing operating system commands (including scripts) and PL/SQL procedures )
By using SNMP traps, the Enterprise Manager notification system also enables you to invoke the functionality of SNMP-enabled third-party applications such as HP OpenView. Some administrators may want to send a notification to third-party applications when a certain metric has exceeded a threshold.

Notifications are defined via notification methods and notification rules.

http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/notification/notification.htm


http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_dcn.htm#sthref1645

DBMS_CHANGE_NOTIFICATION.*

step 1):
GRANT EXECUTE ON DBMS_CHANGE_NOTIFICATION TO HR;
GRANT CHANGE NOTIFICATION TO HR;

ALTER SYSTEM SET "JOB_QUEUE_PROCESSES"=4;
 


ocm2  Implement Grid Control and Database Control
https://shenh.tripod.com/Oracleblog/index.blog/1824933/ocm2-implement-grid-control-and-database-control/

 -- ----------------------------------------------------------
Manually configure the Oracle 10g EM dbconsole

emca -deconfig dbcontrol db -repos drop

-- drop the sysman schema by following command
emca -deconfig dbcontrol db -repos drop

-- create it again
emca -deconfig dbcontrol db -repos create.


execute dbms_workload_repository.modify_snapshot_settings(interval => 0);

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

create:
http://www.akadia.com/services/ora_dbconsole.html

drop and recreate:
http://forums.oracle.com/forums/thread.jspa?threadID=478330&tstart=60

Now start the Oracle EM dbconsole Build Script
($ORACLE_HOME/bin/emca for Linux and
$ORACLE_HOME\Bin\emca.bat for Windows).

$ emca -repos create
$ emca -config dbcontrol db

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

[oracle@gcds0022 ~]$ cd $ORACLE_HOME/bin
[oracle@gcds0022 bin]$ emctl status dbconsole
TZ set to GMT
OC4J Configuration issue. /u01/app/oracle/product/10.2.0/db_1/oc4j/j2ee/OC4J_DBC

onsole_gcds0022.private.linksynergy.com_ORCL not found.
[oracle@gcds0022 bin]$ emca -repos create

STARTED EMCA at Jun 28, 2007 10:43:28 AM
EM Configuration Assistant, Version 10.2.0.1.0 Production
Copyright (c) 2003, 2005, Oracle. All rights reserved.

Enter the following information:
Database SID: ORCL
Listener port number: 1521
Password for SYS user:
Password for SYSMAN user:
Password for SYSMAN user:
Do you wish to continue? [yes(Y)/no(N)]: y
Jun 28, 2007 10:48:30 AM oracle.sysman.emcp.EMConfig perform
INFO: This operation is being logged at /u01/app/oracle/product/10.2.0/db_1/cfgt

oollogs/emca/ORCL/emca_2007-06-28_10-43-28-AM.log.
Jun 28, 2007 10:48:30 AM oracle.sysman.emcp.EMReposConfig createRepository
INFO: Creating the EM repository (this may take a while) ...
Jun 28, 2007 10:51:07 AM oracle.sysman.emcp.EMReposConfig invoke
INFO: Repository successfully created
Enterprise Manager configuration completed successfully
FINISHED EMCA at Jun 28, 2007 10:51:07 AM
[oracle@gcds0022 bin]$ emca -config dbcontrol db

STARTED EMCA at Jun 28, 2007 10:51:33 AM
EM Configuration Assistant, Version 10.2.0.1.0 Production
Copyright (c) 2003, 2005, Oracle. All rights reserved.

Enter the following information:
Database SID: ORCL
Listener port number: 1521
Password for SYS user:
Password for DBSNMP user:
Password for SYSMAN user:
Email address for notifications (optional): hshen@linkshare.com
Outgoing Mail (SMTP) server for notifications (optional): mail.linkshare.com
Jun 28, 2007 10:54:25 AM oracle.sysman.emcp.EMDBPostConfig performConfiguration
INFO: Database Control started successfully
Jun 28, 2007 10:54:25 AM oracle.sysman.emcp.EMDBPostConfig performConfiguration
INFO: >>>>>>>>>>> The Database Control URL is http://gcds0022.private.linksynergy.com:1158/em

<<<<<<<<<<<
Enterprise Manager configuration completed successfully
FINISHED EMCA at Jun 28, 2007 10:54:25 AM

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

You have specified the following settings

Database ORACLE_HOME ................ /u01/app/oracle/product/10.2.0/db_1

Database hostname ................ gcds0022.private.linksynergy.com
Listener port number ................ 1521
Database SID ................ ORCL
Email address for notifications ............... hshen@linkshare.com
Outgoing Mail (SMTP) server for notifications ............... mail.linkshare.com

-----------------------------------------------------------------
Do you wish to continue? [yes(Y)/no(N)]: y
Jun 28, 2007 10:52:38 AM oracle.sysman.emcp.EMConfig perform
INFO: This operation is being logged at /u01/app/oracle/product/10.2.0/db_1/cfgtoollogs/emca/ORCL/

emca_2007-06-28_10-51-33-AM.log.
Jun 28, 2007 10:52:45 AM oracle.sysman.emcp.util.DBControlUtil startOMS
INFO: Starting Database Control (this may take a while) ...

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

alter system set job_queue_processes=10 scope=both;

emca -config dbcontrol db

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

/u01/app/oracle/product/10.2.0/db_1/bin/emctl start dbconsole

$ emctl start dbconsole
$ emctl stop dbconsole
$ emctl status dbconsole

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

RC scripts: auto start db console:

http://www.akadia.com/download/documents/dbconsole.txt


http://lvds0025.private.linksynergy.com:1158/em

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

sysman: dbconsole repository

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

This operation is being logged at
/u01/app/oracle/product/10.2.0/db_1/cfgtoollogs/emca/ORCL/emca_2007-03-19_04-30-57-PM.log

/u01/app/oracle/product/10.2.0/db_1/oc4j/j2ee/OC4J_DBConsole_lvds0023.private.linksynergy.com_ORCL

isqlplusctl status

isqlplusctl stop

emctl status dbconsole

emctl stop dbconsole

show parameter job_queue_processes

alter system set job_queue_processes=0 scope=both;

alter system set job_queue_processes=10 scope=both;


disable crontab jobs


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


http://lvds0025.private.linksynergy.com:1158/em/console/aboutApplication

/u01/app/oracle/product/10.2.0/cfgtoollogs/emca/ORC1/emca_repos_drop_2007-03-19_03-47-29-PM.log

[19-03-2007 15:47:30] Dropping the repository..
[19-03-2007 15:47:30] Quiescing DB ...
[19-03-2007 15:47:30] File - /tmp/JuvsldGrz6/kd1RrI7SlL.sql.
[19-03-2007 16:11:30] Return code = 245.
[19-03-2007 16:11:31] Failed.
[19-03-2007 16:11:31] Checking for Repos User ...
[19-03-2007 16:11:31] File - /tmp/K3aPcaoazi/Jaolu9kcLv.sql.
[19-03-2007 16:11:39] Return code = 0.
[19-03-2007 16:11:39] Exists.
[19-03-2007 16:11:39] Repos User exists..
[19-03-2007 16:11:39] Clearing EM Contexts ...
[19-03-2007 16:11:39] Clearing contexts. File - /tmp/T74p04p7L2/hnhVJkOy05.sql.

[19-03-2007 16:13:58] Return code = 0.
[19-03-2007 16:13:58] Done.
[19-03-2007 16:13:58] Unquiescing DB ...
[19-03-2007 16:13:58] Temp File - /tmp/jgBIRtOqMx/wN1CZj0YlT.sql.
[19-03-2007 16:13:58] Return code = 0.
[19-03-2007 16:13:58] Done.
[19-03-2007 16:13:58] Dropped Repository Successfully.


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

drop and recreate the dbcontrol repository.
emca -deconfig dbcontrol db -repos drop

Delete any remaining subdirectories in the ORACLE_HOME with the old
hostname).

emca -config dbcontrol db -repos create

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


begin DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(527040,30); end;

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

ALTER SYSTEM SET pga_aggregate_target = 629145600 COMMENT='1200M'
ALTER SYSTEM SET workarea_size_policy = "AUTO"

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

create index LINK.MERCHANT_SITE("MID","BID_STATUS");

isqlplusctl start| stop

isqlplusctl start

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


ocm2  Choose the appropriate tablespace type for the intended use
https://shenh.tripod.com/Oracleblog/index.blog/1824934/ocm2-choose-the-appropriate-tablespace-type-for-the-intended-use/

dedicated tablespace for user sysman and user mgmt_views, locally managed tablespace, automatic segment management.

ocm2  Create Scheduler jobs
https://shenh.tripod.com/Oracleblog/index.blog/1824935/ocm2-create-scheduler-jobs/

http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sched.htm#CIHHBGGI

http://www.oracle.com/technology/obe/obe10gEMR2/Quick_Start/jobs/creating_jobs.htm

http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/schedadmin.htm

http://www.globusz.com/ebooks/Oracle/00000017.htm

-- ----------------------------------------------------------
--Verify enabled status:
SELECT * FROM DBA_SCHEDULER_JOBS WHERE JOB_NAME = 'GATHER_STATS_JOB';

select * from dba_jobs;

select * from DBA_SCHEDULER_JOBS;

select * from DBA_SCHEDULER_JOBS where job_name = 'GATHER_STATS_JOB';

--disable
BEGIN
DBMS_SCHEDULER.DISABLE('GATHER_STATS_JOB');
END;
/

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


http://www.aurora-consult.com.au/paper/hong200711.pdf


dbms_scheduler

dba_schedulers

http://www.aurora-consult.com.au/paper/hong200711.pdf

 

BEGIN
/* A simple schedule job */
DBMS_SCHEDULER.CREATE_JOB
(job_name => 'JOB_SCHEMA_STATS_HR'
,job_type => 'plsql_block'
,job_action =>
'begin
dbms_stats.gather_schema_stats(''HR'');
end;'
,start_date => to_timestamp_tz('01/12/2007 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval => 'freq=MONTHLY'
,enabled => true
,comments => 'Generate HR schema stats every month'
);
END;
/

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

BEGIN
/* Using Schedule, Program and Job */

DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_FIRST_DAY_EACH_MTH '
,start_date => to_timestamp_tz('01/12/2007 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval => 'freq=MONTHLY'
,comments => 'Run first day each month'
);

DBMS_SCHEDULER.CREATE_PROGRAM
(program_name => 'PROG_SCHEMA_STATS_HR'
,program_type => 'plsql_block'
,program_action =>
'begin
dbms_stats.gather_schema_stats(''HR'');
end;'
,enabled => true
,comments => 'Generate HR schema stats'
);

DBMS_SCHEDULER.DROP_JOB
('JOB_SCHEMA_STATS_HR'
,true
);

DBMS_SCHEDULER.CREATE_JOB
(job_name => 'JOB_SCHEMA_STATS_HR'
,program_name => 'PROG_SCHEMA_STATS_HR'
,schedule_name => 'SCHD_FIRST_DAY_EACH_MTH'
,enabled => true
,comments => 'Generate HR schema stats every month'
);
END;
/

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

CREATE OR REPLACE PROCEDURE schema_stats
(p_schema in varchar2)
IS
BEGIN
DBMS_STATS.GATHER_SCHEMA_STATS (p_schema);
END;
/

,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

BEGIN
/* Using program arguments */
DBMS_SCHEDULER.CREATE_PROGRAM
(program_name => 'PROG_SCHEMA_STATS'
,program_type => 'stored_procedure'
,program_action => 'schema_stats'
,number_of_arguments => 1
,enabled => false
,comments => 'Generate schema stats'
);

DBMS_SCHEDULER.DEFINE_PROGRAM_ARGUMENT
(program_name => 'PROG_SCHEMA_STATS'
,argument_position => 1
,argument_name => 'schema'
,argument_type => 'VARCHAR2'
);

DBMS_SCHEDULER.ENABLE ('PROG_SCHEMA_STATS');

DBMS_SCHEDULER.DROP_JOB
('JOB_SCHEMA_STATS_HR'
,true
);

DBMS_SCHEDULER.CREATE_JOB
(job_name => 'JOB_SCHEMA_STATS_HR'
,program_name => 'PROG_SCHEMA_STATS'
,schedule_name => 'SCHD_FIRST_DAY_EACH_MTH'
,enabled => false
,comments => 'Generate HR schema stats every month'
);

DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE
(job_name => 'JOB_SCHEMA_STATS_HR'
,argument_position => 1
,argument_value => 'HR'
);

DBMS_SCHEDULER.ENABLE ('JOB_SCHEMA_STATS_HR');

DBMS_SCHEDULER.CREATE_JOB
(job_name => 'JOB_SCHEMA_STATS_SCOTT'
,program_name => 'PROG_SCHEMA_STATS'
,schedule_name => 'SCHD_FIRST_DAY_EACH_MTH'
,enabled => false
,comments => 'Generate SCOTT schema stats every month'
);

DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE
(job_name => 'JOB_SCHEMA_STATS_SCOTT'
,argument_position => 1
,argument_value => 'SCOTT'
);

DBMS_SCHEDULER.ENABLE ('JOB_SCHEMA_STATS_SCOTT');
END;
/

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

BEGIN
/* Complex scheduling example 1: Public Holidays */
DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_2008_PUBLIC_HOLIDAYS'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,end_date => to_timestamp_tz('31/12/2008 23:59:59','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=DAILY;
bydate=20080101,20080128,20080303,20080321,20080324,20080425,
20080929,20081225,20081226'
,comments => 'Public Holidays 2008'
);
END;
/
The following example creates a schedule consisting of all 2008 working days:
BEGIN
/* Complex scheduling example 2: Working Days */
DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_2008_WORKING_DAYS'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,end_date => to_timestamp_tz('31/12/2008 23:59:59','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=DAILY;
byday=MON,TUE,WED,THU,FRI;
exclude=SCHD_2008_PUBLIC_HOLIDAYS'
,comments => 'Run on every working day'
);
END;
/
The following example creates a schedule consisting of the first working day of every month in 2008:
BEGIN
/* Complex scheduling example 3: 1st Working Day in a Month */
DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_2008_1ST_WK_DAY_EACH_MTH'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,end_date => to_timestamp_tz('31/12/2008 23:59:59','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=MONTHLY;
byday=MON,TUE,WED,THU,FRI;
exclude=SCHD_2008_PUBLIC_HOLIDAYS;
bysetpos=1'
,comments => 'Run on 1st working day every month'
);
END;
/

-------------------------------------------------------------
BEGIN
/* Complex scheduling example 4: 1st and 3rd Monday each month */
DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_1ST_3RD_MON_EACH_MTH'
,start_date => to_timestamp_tz('03/12/2007 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=MONTHLY;
byday=1MON,3MON'
,comments => 'Run on every 1st and 3rd Monday each month'
);
END;
/
The following example creates a schedule consisting of the last day of each quarter:
BEGIN
/* Complex scheduling example 5: Quarter */
DBMS_SCHEDULER.CREATE_SCHEDULE
(schedule_name => 'SCHD_LAST_DAY_EACH_QTR'
,start_date => to_timestamp_tz('31/12/2008 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=YEARLY;
bymonth=MAR,JUN,SEP,DEC;
bymonthday=-1'
,comments => 'Run on every last day each quarter'
);
END;
/
-------------------------------------------------------------

CREATE OR REPLACE PROCEDURE show_schedule
(schedule_name in varchar2
,start_date in timestamp
,repeat_interval in varchar2
,iteration in number)
AS
v_start_date timestamp;
v_after_date timestamp;
v_next_date timestamp;
BEGIN
dbms_output.put_line (schedule_name);
v_start_date := start_date;
v_after_date := v_start_date-(1/86400);

for i in 1..iteration loop
dbms_scheduler.evaluate_calendar_string
(repeat_interval
,v_start_date
,v_after_date
,v_next_date
);

dbms_output.put_line (v_next_date);
v_after_date:= v_next_date;

end loop;

dbms_output.put_line ('============================');
END;
/

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

set serveroutput on

exec dbms_output.enable (1000000);

begin
show_schedule
(schedule_name => 'SCHD_2008_PUBLIC_HOLIDAYS'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=DAILY;
bydate=20080101,20080128,20080303,20080321,20080324,20080425,
20080929,20081225,20081226'
,iteration => 9);

show_schedule
(schedule_name => 'SCHD_2008_WORKING_DAYS'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=DAILY;
byday=MON,TUE,WED,THU,FRI;
exclude=SCHD_2008_PUBLIC_HOLIDAYS'
,iteration => 21);

show_schedule
(schedule_name => 'SCHD_2008_1ST_WK_DAY_EACH_MTH'
,start_date => to_timestamp_tz('01/01/2008 00:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=MONTHLY;
byday=MON,TUE,WED,THU,FRI;
exclude=SCHD_2008_PUBLIC_HOLIDAYS;
bysetpos=1'
,iteration => 12);

show_schedule
(schedule_name => 'SCHD_1ST_3RD_MON_EACH_MTH'
,start_date => to_timestamp_tz('03/12/2007 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=MONTHLY;
byday=1MON,3MON'
,iteration => 26);

show_schedule
(schedule_name => 'SCHD_LAST_DAY_EACH_QTR'
,start_date => to_timestamp_tz('31/12/2008 05:00:00','dd/mm/yyyy hh24:mi:ss')
,repeat_interval =>
'freq=YEARLY;
bymonth=MAR,JUN,SEP,DEC;
bymonthday=-1'
,iteration => 5);
end;
/

set serverout off

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

DBA_OBJECTS                All objects in the database
DBA_SCHEDULER_PROGRAMS     All scheduler programs in the database
DBA_SCHEDULER_JOBS         All scheduler jobs in the database
DBA_SCHEDULER_JOB_CLASSES  All scheduler classes in the database
DBA_SCHEDULER_WINDOWS      All scheduler windows in the database
DBA_SCHEDULER_PROGRAM_ARGS All arguments of all scheduler programs in the database
DBA_SCHEDULER_JOB_ARGS     All arguments with set values of all scheduler jobs in the database
DBA_SCHEDULER_JOB_LOG         Logged information for all scheduler jobs
DBA_SCHEDULER_JOB_RUN_DETAILS The details of a job run
DBA_SCHEDULER_WINDOW_LOG      Logged information for all scheduler windows
DBA_SCHEDULER_WINDOW_DETAILS The details of a window
DBA_SCHEDULER_WINDOW_GROUPS  All scheduler window groups in the database

DBA_SCHEDULER_WINGROUP_MEMBERS Members of all scheduler window groups in the database
DBA_SCHEDULER_SCHEDULES        All schedules in the database
DBA_SCHEDULER_GLOBAL_ATTRIBUTE All scheduler global attributes
DBA_SCHEDULER_CHAINS           All scheduler chains in the database
DBA_SCHEDULER_CHAIN_RULES      All rules from scheduler chains in the database
DBA_SCHEDULER_CHAIN_STEPS      All steps of scheduler chains in the database
DBA_SCHEDULER_RUNNING_CHAINS   All steps of all running chains in the database

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

col object_type format a15
col object_name format a30
col status format a10

select
object_type
,object_name
,status
from
      user_objects
where
      object_type in ('PROGRAM', 'JOB', 'SCHEDULE')
order by object_type, object_name
/

Output:
OBJECT_TYPE OBJECT_NAME STATUS
--------------- ------------------------------ ----------
JOB JOB_SCHEMA_STATS_HR VALID
JOB JOB_SCHEMA_STATS_SCOTT VALID
PROGRAM PROG_SCHEMA_STATS VALID
PROGRAM PROG_SCHEMA_STATS_HR VALID
SCHEDULE SCHD_1ST_3RD_MON_EACH_MTH VALID
SCHEDULE SCHD_2008_1ST_WK_DAY_EACH_MTH VALID
SCHEDULE SCHD_2008_PUBLIC_HOLIDAYS VALID
SCHEDULE SCHD_2008_WORKING_DAYS VALID
SCHEDULE SCHD_FIRST_DAY_EACH_MTH VALID
SCHEDULE SCHD_LAST_DAY_EACH_QTR VALID

Example 2
set linesize 100
col schedule_name format a30
col start_date format a20
col end_date format a20
col repeat_interval format a15

select
schedule_name
,to_char(start_date, 'dd/mm/yyyy hh24:mi:ss') start_date
,to_char(end_date, 'dd/mm/yyyy hh24:mi:ss') end_date
,substr(repeat_interval,1,10)||'...' repeat_interval
from
     user_scheduler_schedules
order by schedule_name
/

Output:
SCHEDULE_NAME START_DATE END_DATE REPEAT_INTERVAL
------------------------------ -------------------- -------------------- ---------------
SCHD_1ST_3RD_MON_EACH_MTH 03/12/2007 05:00:00 freq=MONTH...
SCHD_2008_1ST_WK_DAY_EACH_MTH 01/01/2008 00:00:00 31/12/2008 23:59:59 freq=MONTH...
SCHD_2008_PUBLIC_HOLIDAYS 01/01/2008 00:00:00 31/12/2008 23:59:59 freq=DAILY...
SCHD_2008_WORKING_DAYS 01/01/2008 00:00:00 31/12/2008 23:59:59 freq=DAILY...
SCHD_FIRST_DAY_EACH_MTH 01/12/2007 05:00:00 freq=MONTH...
SCHD_LAST_DAY_EACH_QTR 31/12/2008 05:00:00 freq=YEARL..

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

Example 3
set linesize 100
col program_name format a20
col program_type format a20
col program_action format a50
select
program_name
,program_type
,program_action
from user_scheduler_programs
order by program_name
/

Output:
PROGRAM_NAME PROGRAM_TYPE PROGRAM_ACTION
-------------------- -------------------- --------------------------------------------------
PROG_SCHEMA_STATS STORED_PROCEDURE schema_stats
PROG_SCHEMA_STATS_HR PLSQL_BLOCK begin
dbms_stats.gather_schema_stats('HR');
end;


Example 4
col job_name format a25
col state format a10
col program_name format a20
col job_class format a25
col job_type format a10
col job_action format a20

select
job_name
,state
,program_name
,job_type
,job_action
from user_scheduler_jobs
order by job_name
/

Output:
JOB_NAME STATE PROGRAM_NAME JOB_TYPE JOB_ACTION
------------------------- ---------- -------------------- ------------
JOB_SCHEMA_STATS_HR SCHEDULED PROG_SCHEMA_STATS
JOB_SCHEMA_STATS_SCOTT SCHEDULED PROG_SCHEMA_STATS
System Privileges
Common DBA_SCHEDULER privileges:

Privileges Description
CREATE JOB     Ability to create/alter/drop jobs, schedules and programs

CREATE ANY JOB Ability to create/alter/drop jobs, schedules and programs
               belonging to any user

EXECUTE ANY PROGRAM Use programs belonging to any user

EXECUTE ANY CLASS Ability to create/alter/drop job classes

MANAGE SCHEDULER Ability to create/alter/drop job classes, windows and
                 window groups belonging to any user

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

begin
print_table ( q'# select * from DBA_SCHEDULER_JOBS where job_name = 'GATHER_STATS_JOB' #' );
end;
/

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


DBMS_SCHEDULER.CREATE_JOB(
JOB_NAME => 'TEST_JOB1',
JOB_TYPE => 'PLSQL_BLOCK',
JOB_ACTION => 'DELETE FROM PERSONS WHERE SYSDATE=SYSDATE-1',
START_DATE => '28-JUNE-04 07.00.00 PM AUSTRALIA/SYDNEY',
REPEAT_INTERVAL => 'FREQ=DAILY;INTERVAL=2',
END_DATE => '20-NOV-04 07.00.00 PM AUSTRALIA/SYDNEY',
COMMENTS => 'TEST JOB')

Possible values are:
plsql_block
stored_procedure
executable

JOB_ACTION specifies the exact procedure, command, or script that the job will execute.
START_DATE and END_DATE These parameters specify the date that a new job should start and end. (Many jobs may not have an end_date parameter, since they are ongoing jobs.)
REPEAT_
INTERVAL You can specify a repeat interval in one of two ways:
Use a PL/SQL date/time expression.
Use a database calendaring expression.


Specifying Intervals

FREQ takes YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, and SECONDLY.

FREQ=DAILY; INTERVAL=10 executes a job every 10 days
FREQ=HOURLY; INTERVAL=2 executes a job every other hour
FREQ=WEEKLY; BYDAY=FRI executes a job every Friday.
FREQ=WEEKLY; INTERVAL=2; BYDAY=FRI executes a job every other Friday.
FREQ=MONTHLY; BYMONTHDAY=1 executes a job on the last day of the month
FREQ=YEARLY; BYMONTH=DEC; BYMONTHDAY=31 executes a job on the 31st of December.
FREQ=MONTHLY; BYDAY=2FRI executes a job every second Friday of the month

Refer to PL/SQL Packages and Types Reference 10g Release 1, Chapter 83, Table 83-9 Values for repeat_interval.

Note: You’ll be the owner of a job if you create it in your own schema. However, if you create it in another schema, that schema user will be owner of the job.

Enabling and Disabling Jobs

All jobs are disabled by default when you create them. You must explicitly enable them in order to activate and schedule them.

DBMS_SCHEDULER.ENABLE ('TEST_JOB1')

DBMS_SCHEDULER.DISABLE ('TEST_JOB1')

Dropping a Job

DBMS_SCHEDULER.DROP_JOB (JOB_NAME => 'test_job1')

Running and Stopping a Job

DBMS_SCHEDULER.RUN_JOB('TEST_JOB1')

DBMS_SCHEDULER.STOP_JOB('TEST_JOB1')

In both the STOP_JOB and RUN_JOB procedures, there is a FORCE argument, which is set to FALSE by default. By setting FORCE=TRUE, you can stop or drop a job immediately by using the appropriate procedure. You must have the MANAGE SCHEDULER system privilege to use the FORCE setting.

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

Prioritizing Jobs

You can prioritize jobs at two levels: class and job.
The prioritization at the class level is based on the resources allocated to each resource consumer group by the currently active resource plan. The consumer group that a job class maps to can be specified when creating a job class.
At job level, the job priority ranges from 1 to 5, with 1 being the highest priority and 3 being the default.
When you have more than one job within the same class scheduled for the same time, the JOB_PRIORITY of the individual jobs determines which job starts first.
DBMS_SCHEDULER.SET_ATTRIBUTE (

NAME => 'test_job',

ATTRIBUTE => 'job_priority',

VALUE => 1)

Window Priorities

If there are more than one window to open at the same time, the Scheduler will close all windows except one, using the following rules of precedence:

If two windows overlap, the window with the higher priority opens and the window with the lower priority closes.
If two windows of the same priority overlap, the active window remains open.
If you are at the end of a window and you have other windows defined for the same time period, the window that has the highest percentage of time remaining will open.
Window Groups

A window group is a collection of windows, and is part of the SYS schema.
The concept of a window group is for convenience only, and its use is purely optional.
Unsetting Component Attributes

DBMS_SCHEDULER.SET_ATTRIBUTE_NULL('test_program', 'COMMENTS')

Altering Common Component Attributes

There are some attributes that are common to all Scheduler components.
Use the procedure SET_SCHEDULER_ATTRIBUTE to set these common, or global level, attributes.
These are the global attributes:
DEFAULT_TIMEZONE

If jobs and windows specifications use the calendering syntax but omit the start date, the Scheduler derives the time zone from the DEFAULT_TIMEZONE attribute.

Oracle recommends that you set the DEFAULT_TIMEZONE attribute to a region’s name instead of absolute time zone offset, in order to ensure that daylight saving adjustments are being taken into account.

LOG_HISTORY

This attribute refers to the number of days the Scheduler will retain job and window logs.

MAX_JOB_SLAVE_PROCESSES

The Scheduler determines the optimal number of job slave processes, based on your processing requirements. However, you can set a limit on the number of job slave processes using the MAX_JOB_SLAVE_PROCESSES attribute, whose default value is NULL, and the range is from 1 to 999.

Event-Based Scheduling

Jobs can be triggered based on events. An application can notify the Scheduler to start a job by enqueuing a message onto an Oracle Streams AQ queue. In other words, the job runs when the event is raised.
There are two types of events:
User- or application-generated events: An application can raise an event to be consumed by the Scheduler. The Scheduler reacts to the event by starting a job. Example of such events: a running job completes; a file arrives on the file system; an account within the database is locked; and the inventory reaches a low threshold.
Scheduler-generated events: The Scheduler can raise an event to indicate state changes that occur within the Scheduler itself. For example, the Scheduler can raise an event when a job starts, when a job completes, when a job exceeds its allotted run time, and so on.
To create an event-based job, you must set these two attributes with the CREATE_JOB procedure:

queue_spec: A queue specification that includes the name of the queue where your application enqueues messages to raise job start events, or in the case of a secure queue, the <queue_name>, <agent_name> pair
event_condition: A conditional expression based on message properties that must evaluate to TRUE for the message to start the job. The expression must use the same syntax as an Oracle Streams AQ rule condition. You can include user data properties in the expression, provided that the message payload is a user-defined object type, and that you prefix object attributes in the expression with tab.user_data.
For more information about how to create queues and enqueue messages, refer to the Oracle Streams Advanced Queuing User’s Guide and Reference documentation.

Events Raised by the Scheduler

First you must create the job by using the CREATE_JOB procedure and then use the SET_ATTRIBUTE procedure to modify the attribute’s default value. The Scheduler then raises the events by enqueuing messages onto the default event queue SYS.SCHEDULER$_EVENT_QUEUE.

The queue is based on the SCHEDULER$_EVENT_INFO type, which contains the following attributes: event_type,object_owner, object_name, event_timestamp, error_code, error_msg, event_status, log_id, run_count and failure_count.

The event type can be one of the following:

JOB_START: A job has started for the first time, or a job was started on a retry attempt. To determine which is the case, you can use the EVENT_STATUS field for further details: 0x01 - normal start, 0x02 - retry
JOB_SUCCEEDED
JOB_FAILED: The job resulted in an error or was not able to run due to process death or database shutdown. The EVENT_STATUS field indicates the cause of failure: 0x04: Error during job execution, 0x08: Slave crash or forced shutdown
JOB_BROKEN: The job is marked broken after retrying unsuccessfully.
JOB_COMPLETED: The job has a status of COMPLETED after it has reached its maximum number of runs or its end date.
JOB_STOPPED: The job terminated normally after a soft or hard kill was issued. The EVENT_STATUS field indicates how the job was stopped: 0x10 - Stop without force, 0x20 - Stop with force
JOB_OVER_MAX_DUR: The job has been running for a longer amount of time than was specified by the job max_run_duration attribute.
JOB_SCH_LIM_REACHED: The schedule limit for a job has been exceeded and the job has been rescheduled.
DBMS_SCHEDULER.SET_ATTRIBUTE('hr.do_backup', 'raise_events', DBMS_SCHEDULER.JOB_FAILED)

DBMS_SCHEDULER.CREATE_JOB(

job_name=>'ADMIN.REPORT_FAILED_BACKUP',

job_type => 'STORED_PROCEDURE',

job_action => 'ADMIN.REPORT_BACKUP_FAILURE',

start_date => SYSTIMESTAMP,

event_condition =>

'tab.user_data.object_owner = ''HR'' and tab.user_data.object_name = ''DO_BACKUP''

and tab.user_data.event_type ='DBMS_SCHEDULER.JOB_FAILED',

queue_spec => 'SYS.SCHEDULER$_EVENT_QUEUE,QUEUE_AGT')

Viewing Information About the Scheduler

DBA_SCHEDULER_
JOBS
This view provides the status and general information about scheduled jobs in your database.
DBA_SCHEDULER_
RUNNING_JOBS
This view provides you with information regarding currently running jobs.
DBA_SCHEDULER_
JOB_RUN_DETAILS
This view provides information about status and the duration of execution for all jobs in your database.
DBA_SCHEDULER_
SCHEDULES
This view provides information on all current schedules in your database.

Scheduler Job Chain

A chain is a named series of programs that are linked together for a combined objective. Each position within a chain of interdependent programs is referred to as a step. Each step can point to one of the following: a program, another chain (a nested chain), an event.

Note: This feature introduced in Oracle 10g release 2.

To create and use a chain:

1. Create a chain object

DBMS_SCHEDULER.CREATE_CHAIN (

CHAIN_NAME => 'bulk_load_chain',

RULE_SET_NAME => NULL,

EVALUATION_INTERVAL => NULL,

COMMENTS => 'Load data and run reports')

2. Define one or more chain steps. You define a step that points to a program or nested chain.

DBMS_SCHEDULER.DEFINE_CHAIN_STEP (

CHAIN_NAME => 'bulk_load_chain',

STEP_NAME => 'do_bulk_load',

PROGRAM_NAME => 'hr.load_data_prog)

Also you can define a step that waits for an event to occur by using the DEFINE_CHAIN_EVENT_STEP procedure. Procedure arguments can point to an event schedule or can include an in-line queue specification and event condition.

DBMS_SCHEDULER.DEFINE_CHAIN_EVENT_STEP (

CHAIN_NAME => 'bulk_load_chain',

STEP_NAME => 'stop_when_disk_full_evt'

EVENT_SCHEDULE_NAME => 'disk_full_sched')

DBMS_SCHEDULER.DEFINE_CHAIN_EVENT_STEP (

CHAIN_NAME => 'bulk_load_chain',

STEP_NAME => 'load_data_evt',

EVENT_CONDITION => 'tab.user_data.object_owner=''HR'' and tab.user_data.object_name = ''DATA.TXT'' and tab.user_data.event_type =''FILE_ARRIVAL'' ',

QUEUE_SPEC => 'HR.LOAD_JOB_EVENT_Q')

3. Define chain rules. Each rule has a condition and an action.

If the condition evaluates to TRUE, the action is performed. Conditions are usually based on the outcome of one or more previous steps. A condition accepts Boolean and numeric integer values in an expression. The entire expression must evaluate to a Boolean value.

The simplified syntax of a chain condition is as follows:

'factor|NOT(factor)[AND|OR factor]'

factor:

stepname ERROR_CODE number|[NOT]step_condition

When creating a rule condition using the simplified syntax:

You specify one or more factors, and a Boolean operator (AND, OR, or NOT).
A factor can be either a simple Boolean value (TRUE or FALSE) or a chain condition. A chain condition describes the condition of another step in the job chain. You can use the following to describe the chain condition:
The current state of the chain step:
SUCCEEDED
FAILED
STOPPED
COMPLETED
The error code returned by the chain step. The error is a numeric value, and can be:
Evaluated within a numeric clause
Compared to a list of values using an IN clause
You can use negative factors, by enclosing the factor in parentheses and prefixing the factor with the NOT operator.

Examples:

'step1 SUCCEEDED AND step2 ERROR_CODE = 3'

'TRUE'

'step3 NOT COMPLETED AND NOT (step1 SUCCEEDED)'

'step2 ERROR_CODE NOT IN (1,2,3)'

You can also refer to attributes of chain steps of the chain (this is called bind-variable syntax). The syntax is as follows:

STEP_NAME.ATTRIBUTE

Possible attributes are: completed, state, start_date, end_date, error_code, and duration.
Possible values for the state attribute include: 'NOT_STARTED', 'SCHEDULED', 'RUNNING', 'PAUSED', 'SUCCEEDED', 'FAILED', and 'STOPPED'.
If a step is in the state 'SUCCEEDED', 'FAILED', or 'STOPPED', its completed attribute is set to 'TRUE'; otherwise, completed is 'FALSE'.
Some examples of the bind variable syntax are:

':step1.state=''SUCCEEDED'' and :step2.error_code=3'

'1=1'

':step3.state != ''COMPLETED'''

':step2.error_code not in (1,2,3)'

':step1.state = ''NOT_STARTED'''

The rule action specifies what is to be done as a result of the rule being triggered. A typical action is to run a specified step. Possible actions include:

START step_1[,step_2...]
STOP step_1[,step_2...]
END [{end_value | step_name.error_code}]
When the job starts and at the end of each step, all rules are evaluated to see what action or actions occur next. You can also configure rules to be evaluated at regular intervals by using the EVALUATION_INTERVAL attribute of the chain.

You add a rule to a chain with the DEFINE_CHAIN_RULE procedure:

BEGIN

DBMS_SCHEDULER.DEFINE_CHAIN_RULE (

CHAIN_NAME => 'bulk_load_chain',

CONDITION => 'TRUE', -- starting step

ACTION => 'START load_data_evt,
stop_when_disk_full_evt',

Rule_Name => 'dataload_rule1',

COMMENTS => 'start the chain');

DBMS_SCHEDULER.DEFINE_CHAIN_RULE (

CHAIN_NAME => 'bulk_load_chain',

CONDITION => 'load_data_evt COMPLETED',

ACTION => 'START do_bulk_load',

RULE_NAME => 'dataload_rule2');

END;

4. Enable a chain with the ENABLE procedure (A chain is always created disabled). Enabling an already enabled chain does not return an error.

DBMS_SCHEDULER.ENABLE ('bulk_load_chain');

5. To run a chain, you must create a job of type 'CHAIN'. The job action must refer to the chain name.

BEGIN

DBMS_SCHEDULER.CREATE_JOB (

job_name => 'bulk_load_chain_job',

job_type => 'CHAIN',

job_action => 'bulk_load_chain',

repeat_interval => 'freq=daily;byhour=7',

enabled => TRUE);

END;

Managing Job Chains

The RUN_CHAIN procedure immediately runs a chain by creating a run-once job with the job name given. If no job_name is given, one is automatically assigned in the form SCHED_CHAIN_JOB${N}. If a list of start steps is given, only those steps are started when the chain begins running (steps that would have normally started are not run). If no list of start steps is given, then the chain starts normally
DBMS_SCHEDULER.RUN_CHAIN('chain_name','job_name','steps_to_start')

The DROP_CHAIN_RULE procedure removes a rule from an existing chain. If dropping this rule makes the chain invalid, the user should first disable the chain to ensure that it does not run.
DBMS_SCHEDULER.DROP_CHAIN_RULE('chain_name','rule_name')

Disable a chain
DBMS_SCHEDULER.DISABLE('chain_name')

Drop a chain
DBMS_SCHEDULER.DROP_CHAIN('chain_name')

Alter the SKIP or PAUSE attributes of a chain step by using the ALTER_CHAIN procedure. The ALTER_CHAIN procedure affects only future runs of the specified steps.
Alter the steps in a running chain by using the ALTER_RUNNING_CHAIN procedure
Drop a step from a chain by using the DROP_CHAIN_STEP procedure
Monitoring Job Chains

DBA_SCHEDULER_CHAINS

contains information about the chain owner and name; the rule set name and rule set owner for the chain; the number of rules; the number of steps; whether or not the chain is enabled; whether or not the chain uses an evaluation interval; and whether or not the chain uses a user-defined rule set.

DBA_SCHEDULER_CHAIN_RULES

displays the name and owner of the chain for which the rule was defined; the rule name, owner, and condition; and the action to be performed if the condition evaluates to TRUE.

DBA_SCHEDULER_CHAIN_STEPS

displays the name and owner of the chain for which the step was created; the step name; the program name and owner; whether the step should be skipped or not; and whether or not the step should be paused after it completes.

DBA_SCHEDULER_RUNNING_CHAINS

contains the chain name and owner; the name and owner of the job that points to the chain; the name of the steps in the chain and their current state; errors encountered by the chain step; the time at which the chain step started and ended; how long it took the step to complete; and the name of the job running the step, if it is current executing.

ocm2  Create schedules
https://shenh.tripod.com/Oracleblog/index.blog/1824936/ocm2-create-schedules/

http://www.globusz.com/ebooks/Oracle/00000017.htm

Creating a Schedule

DBMS_SCHEDULER.CREATE_SCHEDULE(

SCHEDULE_NAME => 'TEST_SCHEDULE',

START_DATE => SYSTIMESTAMP,

END_DATE => SYSTIMESTAMP + 30,

REPEAT_INTERVAL => 'FREQ=HOURLY;INTERVAL= 12',

COMMENTS => 'EVERY 12 HOURS')

Note the following about creating a Schedule:

When you create a schedule, Oracle provides access to PUBLIC. Thus, all users can use your schedule, without any explicit grant of privileges to do so.
You specify the start and end times using the TIMESTAMP WITH TIME ZONE datatype. The Scheduler also supports all NLS_TIMESTAMP_TZ_FORMAT settings.

You must use a calendering expression to create the repeat interval.

DBMS_SCHEDULER.CREATE_JOB(
JOB_NAME => 'TEST_JOB02',
PROGRAM_NAME => 'TEST_PROGRAM',
SCHEDULE_NAME => 'TEST_SCHEDULE')

Altering a Schedule

You can alter the attributes (except SCHEDULE_NAME) of a schedule by using the SET_ATTRIBUTE procedure of the DBMS_SCHEDULER package.

Dropping a Schedule

DBMS_SCHEDULER.DROP_SCHEDULE(SCHEDULE_NAME => 'TEST_SCHEDULE');

When you drop a schedule by using the FORCE=TRUE attribute, you’ll drop the schedule, even if there are jobs and windows that use the schedule. The Scheduler first disables the dependent jobs/windows before dropping the schedule itself. 


ocm2  Assign jobs to windows
https://shenh.tripod.com/Oracleblog/index.blog/1824938/ocm2-assign-jobs-to-windows/

Working with Scheduler Windows

Windows enable the automatic changing of resource plans based on a schedule.

Creating a Window

Windows are always created in the SYS schema.
To create a window, you must have the MANAGE SCHEDULER system privilege.
A window is automatically enabled upon its creation.
DBMS_SCHEDULER.CREATE_WINDOW (

WINDOW_NAME => 'TEST_WINDOW',

START_DATE => '01-JAN-05 12:00:00AM',

REPEAT_INTERVAL => 'FREQ=DAILY',

RESOURCE_PLAN => 'TEST_RESOURCEPLAN',

DURATION => INTERVAL '60' MINUTE,

END_DATE => '31-DEC-05 12:00:00AM',

WINDOW_PRIORITY => 'HIGH',

COMMENTS => 'Test Window')

START_DATE Time when the Window will open.
REPEAT_INTERVAL The next time the window will open again.
RESOURCE_PLAN Tells us that while this window is open, resource allocation to all the jobs that run in this window will be guided by the resource plan directives in the resource plan TEST_RESOURCEPLAN.
DURATION Window will remain open for a period of 60 minutes, after which it will close.
END_DATE Window will open for the last time on December 31, 2005, after which it will be disabled and closed.
WINDOW_PRIORITY Possible values are: LOW, HIGH.
When two Windows overlap, the high-priority window will open and the lower-priority window does not open.


You can create a window using a saved schedule:

DBMS_SCHEDULER.CREATE_WINDOW (

WINDOW_NAME => 'TEST_WINDOW',

SCHEDULE_NAME => 'TEST_SCHEDULE',

RESOURCE_PLAN => 'TEST_RESOURCEPLAN',

DURATION => interval '160' minute,

COMMENTS => 'Test Window')

Opening a Window

A window will automatically open at a time specified by its START_TIME attribute.
Only one window can be open at any given time.
A window can be manually opened:
DBMS_SCHEDULER.OPEN_WINDOW (

WINDOW_NAME =>'BACKUP_WINDOW',

DURATION => '0 12:00:00')

When you specify the duration, you can specify days, hours, minutes, seconds, in that order.

You can open an already open window. If you do this, the duration of the window will last a time period equal to its duration attribute.
Closing a Window

DBMS_SCHEDULER.CLOSE_WINDOW('BACKUP_WINDOW')

A running job may close upon the closing of its window, if you create a job with the attribute STOP_ON_WINDOW_CLOSE set to TRUE.

Disabling a Window

You can only disable a window if no job uses that window or if the window is not open.
If the window is open, you can disable it by using the DISABLE program with the FORCE=TRUE attribute.
DBMS_SCHEDULER.DISABLE (NAME => 'BACKUP_WINDOW')

Dropping a Window

You can drop a window by using the DROP_WINDOW procedure.
If a job associated with a window is running, a DROP_WINDOW procedure will continue to run through to completion and is disabled after it completes.
If you set the STOP_ON_WINDOW_CLOSE attribute to TRUE, however, the job will immediately stop when you drop an associated window.
 

ocm2  Create programs
https://shenh.tripod.com/Oracleblog/index.blog/1824940/ocm2-create-programs/

http://www.globusz.com/ebooks/Oracle/00000017.htm

Creating a Program

DBMS_SCHEDULER.CREATE_PROGRAM(
PROGRAM_NAME => 'TEST_PROGRAM',
PROGRAM_ACTION => 'SCOTT.UPDATE_SCHEMA_STATS',
PROGRAM_TYPE => 'STORED_PROCEDURE',
ENABLED => TRUE)

Note: If you want to create the program in a different user’s schema, you must qualify the program name with the schema name.

ocm2  Create job classes
https://shenh.tripod.com/Oracleblog/index.blog/1824941/ocm2-create-job-classes/

http://www.globusz.com/ebooks/Oracle/00000017.htm

Creating a Job Class

Using job classes helps you prioritize jobs by allocating resources differently among the various jobs.
All job classes are created in the SYS schema. To create a job class you need MANAGE SCHEDULER privilege.
For users to create jobs that belong to a job class, the job owner must have EXECUTE privileges on the job class.
There is a default job class, DEFAULT_JOB_CLASS, to which all jobs will belong if you don’t explicitly assign them to a job class.
DBMS_SCHEDULER.CREATE_JOB_CLASS (

JOB_CLASS_NAME => 'ADMIN_JOBS',

RESOURCE_CONSUMER_GROUP => 'ADMIN_GROUP',

LOGGING_LEVEL => DBMS_SCHEDULER.LOGGING_OFF

LOGGING_HISTORY => 30,

COMMENTS => 'Admin related jobs.')

LOGGING_
LEVEL
This attribute specifies how much information is logged. The three possible options are:
DBMS_SCHEDULER.LOGGING_OFF
DBMS_SCHEDULER.LOGGING_RUNS
DBMS_SCHEDULER.LOGGING_FULL:
In addition to recording every run of a job, the Scheduler will log every time a job is created, enabled, disabled, altered, and so on.

Note: As a DBA, you can set logging at the job class level in order to audit Scheduler jobs. In this case, an individual user can only increase the amount of logging the individual job level.

LOGGING_HISTORY Specifies the number of days (default is 30) that the database will retain the logs before purging them.
Oracle will automatically create a daily job called the PURGE_LOG, which cleans the log entries.


Manually Purging a Job Class Log

By default, once a day, the Scheduler will purge all window logs and job logs that are older than 30 days.

DBMS_SCHEDULER.PURGE_LOG(LOG_HISTORY=7,

WHICH_LOG =>'JOB_LOG')

LOG_HISTORY This specifies how much history (in days) to keep. The valid range is 0-999. If set to 0, no history is kept.
WHICH_LOG This specifies which type of log. Valid values are: JOB_LOG, WINDOW_LOG, AND JOB_AND_WINDOW_LOG.

You can purge log of a specific job:

DBMS_SCHEDULER.PURGE_LOG (

LOG_HISTORY => 1,

JOB_NAME => 'TEST_JOB1')

You can modify the retention period (the default is 30days) of the logs for a job class:

DBMS_SCHEDULER.SET_ATTRIBUTE(

'TEST_JOB_CLASS', 'log_history', '7')

In order to clear all window and job logs:

DBMS_SCHEDULER.PURGE_LOG()

Altering a Job Class

DBMS_SCHEDULER.SET_ATTRIBUTE(

NAME => 'ADMIN_JOBS',

ATTRIBUTE => 'START_DATE',

VALUE => '01-JAN-2005 9:00:00 PM US/Pacific')

You can change the START_DATE, END_DATE, and other logging-related attributes as well.

Dropping a Job Class

DBMS_SCHEDULER.DROP_JOB_CLASS('TEST_CLASS')

If you want to drop a job class with jobs in it, you must specify the FORCE=TRUE option in your DROP_JOB_CLASS procedure. When you do this, the jobs in the dropped job class are disabled and moved to the default job class in your database. If the job is already running when you drop its job class, the job will run to completion anyway. 

ocm2  Install the Enterprise Manager Grid Control infrastructure
https://shenh.tripod.com/Oracleblog/index.blog/1824942/ocm2-install-the-enterprise-manager-grid-control-infrastructure/

 

ocm2  Deploy Enterprise Manager Grid Control agents
https://shenh.tripod.com/Oracleblog/index.blog/1824944/ocm2-deploy-enterprise-manager-grid-control-agents/

http://download.oracle.com/docs/cd/B19306_01/readmes.102/b28832/toc.htm

http://<OMS_host>:<OMS_port>/agent_download/agent_install_readme.html

http://mgmthost27.acme.com:4889/agent_download/10.2.0.2.0/<platform>

OMShost=stadv26.us.oracle.com
httpPort=4889

<OMS_HOME>/sysman/agent_download/10.2.0.1.0/<platform>/agentDownload.linux

./agentDownload.<platform> -b /scratch/agentInstall
./agentDownload.<platform> -b /scratch/agentInstall -c "host1,host2,host3" -n myCRS -l

<Agent_Home>/bin/emctl secure agent <password>

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

 1): harder, need unlock on the server   
./emctl unsecure agent

-- OMS Upload URL - http://alalpboo136.choicepoint.net:4889/em/upload/ is locked or unavailable.
-- Unsecuring Agent...  Failed.

2): easier
./emctl secure agent
./emctl upload agent

./emctl stop agent
./emctl start agent

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

ocm2  Configure Grid Control for business requirements
https://shenh.tripod.com/Oracleblog/index.blog/1824945/ocm2-configure-grid-control-for-business-requirements/

 


Posted by shenh at 9:31 PM EST
Updated: Tuesday, 6 January 2009 9:58 PM EST
OCM1: Server Configuration


1. Server Configuration
ocm1  Create the database
https://shenh.tripod.com/Oracleblog/index.blog/1824896/ocm1-create-the-database/

1): set environment variables
dbca&


10g R2 manual create db withtout omf

control_files=('/u01/app/oradata/orcl/control01.ctl',
'/u01/app/oradata/orcl/control02.ctl',
'/u01/app/oradata/orcl/control03.ctl')
db_name=orcl
db_block_size=8192
undo_management=auto
shared_pool_size=100000000

create database orcl
logfile
group 1 ('/u01/app/oradata/orcl/redo01.log') size 10m,
group 2 ('/u01/app/oradata/orcl/redo02.log') size 10m,
group 3 ('/u01/app/oradata/orcl/redo03.log') size 10m
datafile '/u01/app/oradata/orcl/system01.dbf' size 100m
autoextend on next 1m maxsize unlimited
extent management local
sysaux datafile '/u01/app/oradata/orcl/sysaux.dbf' size 100m
autoextend on next 1m maxsize unlimited
extent management local
undo tablespace undo
datafile '/u01/app/oradata/orcl/undo01.dbf' size 100m
default temporary tablespace temp
tempfile '/u01/app/oradata/orcl/temp.dbf' size 100m;

@?/rdbms/admin/catalog
@?/rdbms/admin/catproc

2): use and create templates for dbca

Cloning Databases Using DBCA
The "Template Management" section of the Database Configuration Assistant (DBCA) can be used to clone databases. The following method creates a clone of and existing database including both the structure and the data:

Start the Database Configuration Assistant (DBCA).
On the "Welcome" screen click the "Next" button.
On the "Operations" screen select the "Manage Templates" option and click the "Next" button.
On the "Template Management" screen select the "Create a database template" option and select the "From and existing database (structure as well as data)" sub-option then click the "Next" button.
On the "Source database" screen select the relevant database instance and click the "Next" button.
On the "Template properties" screen enter a suitable name and description for the template, confirm the location for the template files and click the "Next" button.
On the "Location of database related files" screen choose either to maintain the file locations or to convert to OFA structure (recommended) and click the "Finish" button.
On the "Confirmation" screen click the "OK" button.
Wait while the Database Configuration Assistant progress screen gathers information about the source database, backs up the database and creates the template.
By default the template files are located in the "$ORACLE_HOME/assistants/dbca/templates" directory.

http://www.oracle-base.com/articles/10g/ServerConfiguration10g.php

3):
create database .

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

Create a Database Manually

Even if your company standardizes on using the GUI tools, such as DBCA, it would be a good idea to create a database manually at least once, not only to help you with this test (although it will help you to pass this portion of the exam), but so that you have an idea of what the DBCA is doing behind the scenes. This knowledge will help you to make more informed decisions in creating your databases, going forward, regardless of how you create them.

  • Step 1: Decide on Your Instance's System Identifier (SID)

The first step in creating the database is to determine the System Identifier (SID). This is what the environment will be set to when your database starts up and shuts down, and what the instance processes will have in their names as unique identifiers.

  • Step 2: Create the Initialization Parameter File

In the ORACLE_HOME/dbs directory, a set of generic initialization files are available for you to copy and customize to your situation. There is one for a regular OLTP database, one for a data warehouse database, and one for a combination database. Find the one that most closely matches what you intend your database to be used for, copy it to another name (saving the template for reuse later), and make your specific alterations to the copy.

Name the copied init.ora file init<SID>.ora because this is the default naming convention that the Oracle server looks for when it tries to start up the instance.

Edit this file's parameters so that your database and your instance will run effectively on your system.

Let's address the parameters in the initialization file in greater depth:

DB_NAME Must be set to a text string of eight characters or less. During database creation, the value assigned to DB_NAME is recorded in the database's datafiles, redo log files, and control files. If, when you attempt to start the database instance, the value of DB_NAME as recorded in the initialization parameter file and the database name in the control files are not the same, the database will not start.

DB_DOMAIN A text string that specifies the network domain where the database is created. This is often the name of the organization that owns the database. If the new database will be a part of a distributed database system, special attention needs to be paid to this parameter before database creation.

CONTROL_FILES Is assigned the comma-separated list of control file names to use for the new database. When you execute the CREATE DATABASE statement, the control files listed as values assigned to this parameter are created. If you fail to specify a filename for the CONTROL_FILES parameter, Oracle creates a file with a default operating system dependant filename.

DB_BLOCK_SIZE Specifies the standard block size of the database. This size is used in the creation of the system tablespace and by default in any other tablespaces created. Take care when determining what this value should be because after the database is created, the value cannot be changed.

UNDO_MANAGEMENT Determines whether the database starts in automatic undo management mode. A value of AUTO enables automatic undo management; MANUAL enables manual undo management mode. In 9i, AUTO is suggested, but MANUAL is default.

UNDO_TABLESPACE When the instance starts in automatic undo management mode, it needs to have a tablespace in which to store its undo information. The default is SYS_UNDOTBS and is automatically created if you execute a CREATE DATABASE statement with the UNDO_MANAGEMENT initialization parameter set to AUTO and no UNDO TABLESPACE statement in the CREATE DATABASE statement.

  • Step 3: Connect to and Start the Instance

Connect to the instance as SYSDBA either using operating system authentication or the password file method of authentication and start up the instance using the STARTUP command.

NOTE

If your parameter file is not in the default location or is not named init<SID>.ora, you may need to specify the PFILE clause in the STARTUP command for the instance to start.

Because you do not yet have a database attached to the instance, you need to start up the instance in NOMOUNT state:
SQL> startup nomount;

The instance is now started and ready for the CREATE DATABASE command.

There are several options for starting up the database. The following are the ways that you can start up the instance and the database, and what each means:

STARTUP NOMOUNT Starts the instance but does not mount the database.

STARTUP MOUNT Starts the instance and mounts the database but does not open the database.

STARTUP OPEN Starts the instance and mounts and opens the database.

STARTUP RESTRICT Starts the instance, mounts and opens the database; however, access is restricted to users with restricted session privileges.

STARTUP RECOVER Starts the instance but leaves the database closed and begins recovery for whatever failure scenario occurred.

STARTUP FORCE Forces the instance to shutdown abort and immediately startup open. This option should only be used for instances having problems either starting or stopping.

  • Step 4: Issue the CREATE DATABASE Statement

To create the database, issue the CREATE DATABASE command. The CREATE DATABASE command creates data files, control files, redo log files, the system tablespace along with the data file associated with it, and a system rollback segment. It creates the tables that underlie the data dictionary, assigns the character set to the database, optionally sets the database time zone, and mounts and opens the database for use.

The general format follows:
CREATE DATABASE [database name]
[CONTROLFILE REUSE]
[LOGFILE [GROUP integer] file specification]
[MAXLOGFILES integer]
[MAXLOGMEMBERS integer]
[MAXLOGHISTORY integer]
[MAXDATAFILES integer]
[MAXINSTANCES integer]
[ARCHIVELOG|NOARCHIVELOG]
[CHARACTER SET charset]
[NATIONAL CHARACTER SET charset]
[DATAFILE filespec [autoextend]]
[DEFAULT TEMPORARY TABLESPACE tablespace filespec]
[UNDO TABLESPACE tablespace DATAFILE filespec]
[SET TIME_ZONE [time_zone_region]];

Database is the name of the database that you are creating. If the name of the database is omitted, the initialization parameter DB_NAME is used. The database name should be the same as the DB_NAME parameter.

Control file reuse specifies that an existing control file identified by the control file parameter in the initialization file should be reused.

Log file group identifies the names of the log files to be used and the group to which they belong.

MAXLOGFILES specifies the maximum number of redo log files that can ever be created in the database.

MAXLOGMEMBERS specifies the maximum number of redo log file members that any given log file group can have in the database.

MAXLOGHISTORY specifies the maximum number of archive redo logs for automatic media recovery.

AUTOEXTEND enables or disables the automatic extension of SYSTEM tablespace's data files in the database.

MAXDATAFILES controls the initial sizing of the data file section of the control file at the time when the CREATE DATABASE or CREATE CONTROLFILE commands are issued. If an attempt is made to add a new file with a number greater than the value set to the MAXDATAFILES parameter, but less than the DB_FILES parameter, it causes the control file to expand automatically so that the data files section can accommodate the new files.

The MAXINSTANCES parameter is optional and is primarily used for Real Application Clusters (RAC) environments. The default, if left unspecified, is 1.

The optional ARCHIVELOG|NOARCHIVELOG statement provides the option for the database's redo log files to automatically initially be archived. This is an optional statement at database creation time. NOARCHIVELOG is the default if ARCHIVELOG is not specified. If, after database creation, you choose to change the archive log mode of the database, you can use the ALTER DATABASE command to change between the two. ARCHIVELOG establishes that the redo logs can be reused, but only after they have been archived. NOARCHIVELOG establishes that the redo logs can be reused without archiving their contents.

CHARACTER SET is the character set that the database uses to store the data.

The NATIONAL CHARACTER SET parameter is optional and is used to store data in columns specifically defined as NCHAR, NCLOB, or NVARCHAR2.

NOTE

More on National Language Support (NLS) and its associated parameters will be covered in Chapter 7, "Globalization Support."

DATAFILE, when connected directly to the CREATE DATABASE statement, is the file specification used to specify the data files to be used for the system tablespace.

DEFAULT TEMPORARY TABLESPACE instructs the database to assign this tablespace to all users created without having a temporary tablespace specified.

UNDO TABLESPACE creates and names the undo tablespace and the associated data files that should be used to store undo records for the database if you have specified (as Oracle suggests) UNDO_MANAGEMENT=AUTO in the initialization parameter file.

A working example of a CREATE DATABASE script follows:
create database mydb1 controlfile reuse
Logfile
Group 1 ('/mydatabases/mydb1/log01a.log',
'/mydatabase02/mydb1/log01b.log') size 50M,
Group 2 ('/mydatabases/mydb1/log02a.log',
'/mydatabase02/mydb1/log02b.log') size 50M,
Group 3 ('/mydatabases/mydb1/log03a.log',
'/mydatabase02/mydb1/log03b.log') size 50M,
Group 4 ('/mydatabases/mydb1/log04a.log',
'/mydatabase02/mydb1/log04b.log') size 50M
Datafile '/mydatabases/mydb1/mydb1_system.dbf' 250M
AUTOEXTEND ON MAXSIZE 500M
Undo tablespace mydb1_undo1
Datafile '/mydatabases/mydb1/mydb1_undo1.dbf' 50M
Default temporary tablespace mydb1temp tempfile
'/mydatabases/mydb1/mydb1temp1.dbf' size 75M
Extent management local
Character set US7ASCII
MAXLOGFILES 10
MAXLOGMEMBERS 10
MAXLOGHISTORY 1
MAXDATAFILES 500;

CAUTION

If you use the CONTROLFILE REUSE command, make absolutely sure that you don't specify a control file attached to another database. The reuse command will cause it to be overwritten. Although this will not cause the database and instance to crash (the one that had the control file overwritten) immediately, it is cause for care and concern. Oracle will not tell you that you are overwriting the wrong file, and, if you don't realize it, this can cause the overwritten database to not start after it is shut down.

If you are using Oracle Managed File (OMF) systems and you have specified the appropriate OMF initialization parameters in the parameter file (DB_CREATE_FILE_DEST and DB_CREATE_ONLINE_DEST_n), the following statement creates the database:
Startup nomount
Create database
Default temporary tablespace mydb1temp;

At this point, your database now contains data files (at least a limited number of them), control files, redo log files, the SYS and SYSTEM users, and all the internal data dictionary tables, but no data dictionary views. You can see the dynamic performance views, such as V$LOGFIEL, V$CONTROLFILE, and V$DATAFILE. If you have not yet changed the default passwords for SYS (change_on_install) and SYSTEM (manager), now is a good time to do it.

  • Step 5: Run Scripts to Build Data Dictionary Views

Now that you have a database, you need to complete the data dictionary views and procedures. In the ORACLE_HOME/rdbms/admin directory, a pair of scripts need to be run to complete the database's data dictionary creation. CATALOG.sql creates the data dictionary views from which you can gain insight into the contents of the database. CATPROC.sql creates the objects required to use PL/SQL.

  • Step 6: Run Scripts to Install Additional Options

This step is optional. However, if you need to add any of the optional products, such as Spatial or InterMedia, you can now run the scripts to add these products to your database. You can locate the scripts and the following procedures in the Oracle documentation.

  • Step 7: Create a Server Parameter File

This step is optional, although highly recommended by Oracle. Your Oracle database was created by starting the instance with a parameter file, or PFILE. Because it is editable, you can migrate, easily, your new database to using a server parameter file. Creation of the server parameter file (or spfile) is accomplished by issuing the following statement:
Create spfile from pfile;

This command looks in the default location (ORACLE_HOME/dbs) for an initialization parameter file (or PFILE) with the default name. If your database is named mydb1, the default name would be initmydb1.ora. The command creates an spfile with the default name in the same default location unless otherwise specified.

NOTE

More on parameter files and server parameter files can be found in Chapter 4.

  • Step 8: Back Up the Database

Now that your database is created, take this chance to shut down the database and take a cold backup of the new database.

  • Step 9: Create Additional Tablespaces

After the backups are finished, you can restart the database and create new tablespaces, tables, and users; add data; and in general, open the new database for business.

 

ocm1  Determine and set sizing parameters for database structures
https://shenh.tripod.com/Oracleblog/index.blog/1824898/ocm1-determine-and-set-sizing-parameters-for-database-structures/

1): alter database backup controlfile to trace

alter database backup controlfile to trace as 'c:\\a.trc'

to see initial db setting


CREATE CONTROLFILE REUSE DATABASE "ORCL" NORESETLOGS ARCHIVELOG
MAXLOGFILES 16
MAXLOGMEMBERS 3
MAXDATAFILES 100
MAXINSTANCES 8
MAXLOGHISTORY 292
LOGFILE
GROUP 1 'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\REDO01.LOG' SIZE 50M,
GROUP 2 'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\REDO02.LOG' SIZE 50M,
GROUP 3 'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\REDO03.LOG' SIZE 50M
-- STANDBY LOGFILE

DATAFILE
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\SYSTEM01.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\UNDOTBS01.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\SYSAUX01.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\USERS01.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\EXAMPLE01.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\MGMT.DBF',
'C:\ORACLE10GDB\PRODUCT\10.2.0\ORADATA\ORCL\MGMT_ECM_DEPOT1.DBF'
CHARACTER SET WE8MSWIN1252
;

2):
Structures are Tablespaces,Tables.

Tablespaces
1. All tablespaces can be locally managed [ UNDO/TEMP/Datafile ]
2. Extent management [ AUTOALLOCATE / UNIFORM ]
AUTOALLOCATE is the default . 

ocm1  Create and manage temporary, permanent, and undo tablespaces
https://shenh.tripod.com/Oracleblog/index.blog/1824899/ocm1create-and-manage-temporary-permanent-and-undo-tablespaces/


drop tablespace xxx;

drop tablespace xxx including contents;

drop tablespace xxx including contents and datafiles;

drop tablespace xxx cascade constraints;

alter tablespace xxx add datafile 'xxx' size 200m autoextend on next 10m maxsize 1000M;

alter database datafile 'xxx' resize 500m;

alter tablespace test01 rename to test02;

alter tablespace xxx read only;
alter tablespace xxx read write;

alter tablespace xxx online;
alter tablespace xxx offline;


alter database default temorary tablespace temp;


alter database default tablespace users;

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

OMF: Oracle Managed File

DB_CREATE_FILE_DEST

-- ------------------------------------------
PERMANENT
CREATE TABLESPACE hold_data datafile '/u02/oradata/mylcl/hold_data.dbf'
size 100M EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;
TEMPORARY
Create TEMPORARY TABLESPACE TEMP_DATA tempfile '/u02/oradata/mylcl/temp_data.dbf'
size 100M EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;
UNDO
Create UNDO TABLESPACE UNDOTBS1 datafile '/u02/oradata/mylcl/undotbs1.dbf'
size 100M EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;

alter tablespace USER_DATA ADD DATAFILE '/u06/oradata/ORC1/user_data27.dbf' size 8000M;

1): dba_tablespaces

http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_7003.htm

CREATE BIGFILE TABLESPACE bigtbs_01
DATAFILE 'bigtbs_f1.dat'
SIZE 20M AUTOEXTEND ON;

CREATE UNDO TABLESPACE undots1
DATAFILE 'undotbs_1a.f'
SIZE 10M AUTOEXTEND ON
RETENTION GUARANTEE;

CREATE UNDO TABLESPACE undots1
DATAFILE 'undotbs_1a.f'
SIZE 10M AUTOEXTEND ON
RETENTION NOGUARANTEE;

CREATE TEMPORARY TABLESPACE temp_demo
TEMPFILE 'temp01.dbf' SIZE 5M AUTOEXTEND ON;

ALTER SYSTEM SET DB_CREATE_FILE_DEST = '$ORACLE_HOME/rdbms/dbs';

CREATE TEMPORARY TABLESPACE tbs_05;

Adding a Temporary Tablespace to a Tablespace Group: Example

CREATE TEMPORARY TABLESPACE tbs_temp_01
TEMPFILE 'temp02.dbf' SIZE 5M AUTOEXTEND ON
TABLESPACE GROUP tbs_grp_01;


CREATE TABLESPACE tbs_01
DATAFILE 'tbs_f2.dat' SIZE 40M
ONLINE;

CREATE TABLESPACE tbs_03
DATAFILE 'tbs_f03.dbf' SIZE 20M
LOGGING;

CREATE TABLESPACE tbs_02
DATAFILE 'diskb:tbs_f5.dat' SIZE 500K REUSE
AUTOEXTEND ON NEXT 500K MAXSIZE 100M;

CREATE TABLESPACE tbs_04 DATAFILE 'file_1.f' SIZE 10M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K;

CREATE TABLESPACE auto_seg_ts DATAFILE 'file_2.f' SIZE 1M
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;

Creating Oracle-managed Files: Examples

The following example sets the default location for datafile creation and creates a tablespace with a datafile in the default location. The datafile is 100M and is autoextensible with an unlimited maximum size:

ALTER SYSTEM SET DB_CREATE_FILE_DEST = '$ORACLE_HOME/rdbms/dbs';

CREATE TABLESPACE omf_ts1;
The following example creates a tablespace with an Oracle-managed datafile of 100M that is not autoextensible:

CREATE TABLESPACE omf_ts2 DATAFILE AUTOEXTEND OFF;

ocm1  Stripe data files across multiple physical devices and locations
https://shenh.tripod.com/Oracleblog/index.blog/1824900/ocm1stripe-data-files-across-multiple-physical-devices-and-locations/

1): alter database backup controlfile to trace;

2): select name from v$datafile
select member from v$logfile
select name from v$controlfile
select name from v$tmpfile

3): startup mount;
alter database rename file ... to ...

-- -------------------------------------------
Goal of striping data is simple:-
To avoid I/O bottlenecks during parallel processing, all tablespaces
accessed by parallel operations should be striped.
Many current OS's support disk striping hence DBA's need not stripe data
across the disk.
In the event that you have to stripe data across Disks then
you should distribute the load evenly across the Disks.
More information
Oreilly
Let us say we have to stripe database files and we have 2 disk controllers
CONTROLLER 1 CONTROLLER 2
/u02 /u03
/u04 /u05
/u06 /u07
/u08 /u09
Create a tablespace which will look as one logical device
from oracle perspective and spread it across the disks.
CREATE TABLESPACE MYDATA
DATAFILE '/u02/oradata/mylcl/mydata.dbf' size 2M ,
DATAFILE '/u03/oradata/mylcl/mydata.dbf' size 2M ,
DATAFILE '/u04/oradata/mylcl/mydata.dbf' size 2M ,
DATAFILE '/u05/oradata/mylcl/mydata.dbf' size 2M
extent management local SEGMENT SPACE MANAGEMENT AUTOALLOCATE;

ocm1  Configure the database environment to support optimal data access performance
https://shenh.tripod.com/Oracleblog/index.blog/1824901/ocm1configure-the-database-environment-to-support-optimal-data-access-performance/

1): memory
2): disk

ocm1  Create and manage database configuration files
https://shenh.tripod.com/Oracleblog/index.blog/1824902/ocm1create-and-manage-database-configuration-files/

1): pfile and spfile
$ORACLE_HOME/dbs/init_SID.ora

2): create pfile from spfile;
create spfile from pfile;

3): alter system set ...=.. scope=[both|memory|spfile] sid='*'
show parameter ... 

ocm1  Create and manage bigfile tablespaces
https://shenh.tripod.com/Oracleblog/index.blog/1824904/ocm1create-and-manage-bigfile-tablespaces/

http://www.databasejournal.com/features/oracle/article.php/3646226

select TABLESPACE_NAME, BIGFILE from DBA_TABLESPACES;

ALTER DATABASE SET DEFAULT BIGFILE TABLESPACE;

CREATE DATABASE mydb
USER SYS IDENTIFIED BY password
USER SYSTEM IDENTIFIED BY password
SET DEFAULT BIGFILE TABLESPACE
UNDO TABLESPACE undotbs
DEFAULT TEMPORARY TABLESPACE temp;

http://www.adp-gmbh.ch/ora/concepts/tablespaces.html

1. Bigfile is a big tablespace with single datafile.
2. Supported only for locally managed databases.

What to do if you have to increase space on a big file tablespace:-
1. RESIZE
alter tablespace bigtbs resize 120g;
2. AUTOEXTEND
alter tablespace bigtbs autoextend on next 20G;
-- ----------------------------------------------------------------

1):
create bigfile tablespace xxx

create smallfile tablespace xxx

2): default

ocm1  Create and manage multiple network configuration files
https://shenh.tripod.com/Oracleblog/index.blog/1824905/ocm1create-and-manage-multiple-network-configuration-files/

netmgr&
netca&

cmctl&

http://www.lc.leidenuniv.nl/awcourse/oracle/network.920/a96580/admintoo.htm#483397

tnsnames.ora => Client side file
sqlnet.ora => Server / client side file
listener.ora => server side file.

cman.ora

Location of these files is in $ORACLE_HOME/network/admin/

1):
tnsnames.ora
listener.ora
sqlnet.ora

2): using netca &
netmgr &

3): connection manager
cmctl&
cman.ora

ocm1  Create and configure a listener
https://shenh.tripod.com/Oracleblog/index.blog/1824907/ocm1create-and-configure-a-listener/

netca&
netmgr&
listener.ora

$ORACLE_HOME/network/admin
TNS_ADMIN

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

Here is a sample listener.ora file:-
SID_LIST_LISTENER_10g =
(SID_LIST =
(SID_DESC =
(SID_NAME = DWDEV01)
(ORACLE_HOME = /u02/app/oracle/product/10.2.0/db_1)
)
)
LISTENER_10g =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1530))
)
)
The key to note is that it is not a default listener, we have configured
a new listener for our Database purpose. Also note that it is listening
on port 1530.
To start the listener :-
$lsnrctl stop LISTENER_10G
$lsnrctl start LISTENER_10G
$lsnrctl stat LISTENER_10G #-- to get the statistics of the listener.

ocm1  Configure the database instance to support shared server connections
https://shenh.tripod.com/Oracleblog/index.blog/1824908/ocm1configure-the-database-instance-to-support-shared-server-connections/

select * from v$shared_server

alter system set shared_server=5 ;

alter system set DISPATCHERS="(PROTOCOL=TCP)(DISPATCHERS=2)" ;

select * from v$dispatcher;

select * from v$process where addr = '1FA54CAC';
select * from v$session -- where ;

http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14231/manproc.htm#ADMIN00502

http://www.oracle-training.cc/10g_304.htm

http://www.orafaq.com/forum/t/69829/0/

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

1):
shared_servers

disable:
alter system set SHARED_SERVERS=0.
ALTER SYSTEM SET DISPATCHERS = '';

2):

show parameter shared_server


V$QUEUE
V$DISPATCHER
V$DISPATCHER_RATE

V$DISPATCHER
Provides information on the dispatcher processes, including name, network address, status, various usage statistics, and index number.

V$DISPATCHER_CONFIG
Provides configuration information about the dispatchers.

V$DISPATCHER_RATE
Provides rate statistics for the dispatcher processes.

V$QUEUE
Contains information on the shared server message queues.

V$SHARED_SERVER
Contains information on the shared servers.

V$CIRCUIT
Contains information about virtual circuits, which are user connections to the database through dispatchers and servers.

V$SHARED_SERVER_MONITOR
Contains information for tuning shared server.

V$SGA
Contains size information about various system global area (SGA) groups. May be useful when tuning shared server.

V$SGASTAT
Contains detailed statistical information about the SGA, useful for tuning.

V$SHARED_POOL_RESERVED
Lists statistics to help tune the reserved pool and space within the shared pool.



SELECT NAME, NETWORK FROM V$DISPATCHER;
ALTER SYSTEM SHUTDOWN IMMEDIATE 'D002';


DISPATCHERS="(PROTOCOL=TCP)(DISPATCHERS=2)"

DISPATCHERS='(PROT=tcp)(DISP=5)', '(PROT-tcps)(DISP=3)

Example: Forcing the IP Address Used for Dispatchers The following hypothetical example will create two dispatchers that will listen on the specified IP address. The address must be a valid IP address for the host that the instance is on. (The host may be configured with multiple IP addresses.)

DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)(HOST=144.25.16.201))(DISPATCHERS=2)"
Example: Forcing the Port Used by Dispatchers To force the dispatchers to use a specific port as the listening endpoint, add the PORT attribute as follows:

DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)(PORT=5000))"
DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)(PORT=5001))"

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

Oracle Net Services and Shared Servers
Oracle 10g Simplified Shared Server Configuration

shared_servers
max_shared_servers
shared_server_sessions
dispatchers
max_dispatchers
circuits

notes:
In 10g, the DISPATCHERS parameter does not have to be specifed in order to enable shared servers. If it is not and shared server is configured then a dispatcher listening on TCP/IP port 1521 is started automatically. Configuration of the DISPATCHERS parameter is required for dispatchers that do not listen on the TCP/IP protocol or require other optional subparameters.

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

Oracle Connection Manager
connection manager:

http://www.stanford.edu/dept/itss/docs/oracle/10g/network.101/b10775/cman.htm#i491788

CMAN1=
(CONFIGURATION=
(ADDRESS=(PROTOCOL=tcp)(HOST=proxysvr)(PORT=1521))
(RULE_LIST=
(RULE=(SRC=206.62.226.32/27)(DST=sales-server)(SRV=*)(ACT=accept)
(ACTION_LIST=(AUT=on)(MCT=120)(MIT=30)))
(RULE=(SRC=206.26.226.32)(DST=proxysvr)(SRV=cmon)(ACT=accept)))
(PARAMETER_LIST=
(MAX_GATEWAY_PROCESSES=8)
(MIN_GATEWAY_PROCESSSES=3)
(REMOTE_ADMIN=YES)))

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


1): shared server or MTS
http://www.oracleadvice.com/Tips/MTS.htm

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

Init parameters for setting up shared server:-

>SHARED_SERVERS , should be greater than 0
>MAX_SHARED_SERVERS
>SHARED_SERVER_SESSIONS
>DISPATCHER
>MAX_DISPATCHERS
>CIRCUITS -- Total number of circuits avail. for in/out operations.

>Configuring a shared server:-

ALTER SYSTEM SET SHARED_SERVER=10;
ALTER SYSTEM SET DISPATCHERS="(PROTOCOL=TCP)(DISPATCHERS=2)";

Shutting down a specific dispatcher:
>SELECT * FROM v$dispatcher;
>ALTER SYSTEM SHUTDOWN IMMEDIATE 'D003';

DISABLING SHARED SERVERS
>ALTER SYSTEM SET SHARED_SERVER=0;

After enabling the shared server's make sure you have the
SERVER=SHARED entry in the tnsnames.ora file.

TEST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost )(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = TEST)
(SERVER = SHARED)
)
)

Verify that you are actually connected as SHARED by
querying v$session view.


-- --------------------------------------------
init.ora

large_pool_size = 314572800
mts_dispatchers = "(address=(protocol=tcp)(host=sparc01))(dispatchers=2)"
mts_max_dispatchers = 5
mts_servers = 125
mts_max_servers = 500


-- ---------------------------------------------
large_pool_size in init.ora


tnsnames.ora
(SERVER=shared)
(SERVER=dedicated)

test=
(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=test-server)(PORT=1521))
(CONNECT_DATA=
(SERVICE_NAME=test.us.rmapant.com)
(SERVER=shared)))

test=
(DESCRIPTION=
(ADDRESS=(PROTOCOL=tcp)(HOST=test-server)(PORT=1521))
(CONNECT_DATA=
(SERVICE_NAME=test.us.rampant.com)
(SERVER=dedicated)))

Configure the client profile (sqlnet.ora file)
use_dedicated_server=on

This parameter tells Oracle to add (SERVER=dedicated)
to the connect_data section of the connect
descriptor the client uses.

ocm1  Set up network tracing
https://shenh.tripod.com/Oracleblog/index.blog/1824912/ocm1set-up-network-tracing/

To enable tracing at the server, find the sqlnet.ora file for the server and
create the following lines in it:
$ORACLE_HOME/network/admin/sqlnet.ora
-------------------------------------
TRACE_TIMESTAMP_SERVER = ON
TRACE_LEVEL_SERVER = 16
TRACE_UNIQUE_SERVER = ON
TRACE_DIRECTORY=/oracle/trace
To enable tracing at the client, find the sqlnet.ora file for the client and
create the following lines in it:
%ORACLE_HOME%\network\admin\sqlnet.ora
-------------------------------------
TRACE_TIMESTAMP_CLIENT = ON
TRACE_LEVEL_CLIENT = 16
TRACE_UNIQUE_CLIENT = ON
To enable tracing at the listener, find the listener.ora file and create the
following line in it:
$ORACLE_HOME/network/admin/listener.ora
-------------------------------------
TRACE_LEVEL_LISTENER=16
TRACE_FILE_LISTENER=listener.trc (listener.trc is the default)
TRACE_DIRECTORY_LISTENER=$ORACLE_HOME/network/trace
lsnrctl reload
you should have the trace file afterwards.
The trace file should be similar to :-
____________________________________________________________________________
TNSLSNR for Linux: Version 10.2.0.1.0 - Production on 24-DEC-2006 08:27:17
Copyright (c) 1991, 2005, Oracle. All rights reserved.
[24-DEC-2006 08:27:17:993] --- TRACE CONFIGURATION INFORMATION FOLLOWS ---
[24-DEC-2006 08:27:17:993] New trace stream is /tmp/listener.trc
[24-DEC-2006 08:27:17:993] New trace level is 16
[24-DEC-2006 08:27:17:993] --- TRACE CONFIGURATION INFORMATION ENDS ---
[24-DEC-2006 08:27:17:993] nscontrol: entry
[24-DEC-2006 08:27:17:993] ntvlaarl: entry
[24-DEC-2006 08:27:17:993] ntvlin: entry
[24-DEC-2006 08:27:17:993] nlstdipi: entry
[24-DEC-2006 08:27:17:993] nlstdipi: exit
[24-DEC-2006 08:27:17:993] ntvllt: entry
[24-DEC-2006 08:27:17:993] ntvllt: tcp.validnode_checking not turned on
[24-DEC-2006 08:27:17:993] ntvllt: exit
[24-DEC-2006 08:27:17:993] ntvlin: exit
[24-DEC-2006 08:27:17:993] ntvlaarl: Reload Success for tcp
____________________________________________________________________________
[ ] Manage Oracle network processes (the Listener Control utility)
$lsnrctl start
$lsnrctl stop
$lsnrctl
LSNRCTL> set current listener_10g
Current Listener is listener_10g
LSNRCTL> stat
Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1530)))
STATUS of the LISTENER
------------------------
Alias listener_10g
Version TNSLSNR for Linux: Version 10.2.0.1.0 - Production
Start Date 24-DEC-2006 08:19:45
Uptime 0 days 0 hr. 16 min. 35 sec
Trace Level support
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u02/app/oracle/product/10.2.0/db_1/network/admin/listener.ora
Listener Log File
/u02/app/oracle/product/10.2.0/db_1/network/log/listener_10g.log
Listener Trace File /tmp/listener.trc
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1530)))
Services Summary...
Service "DWDEV01" has 1 instance(s).
Instance "DWDEV01", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
LSNRCTL>


-- ------------------------------------
sqlnet.ora

server side network trace
client side network trace

$ORACLE_HOME\network\trace

TRACE_DIRECTORY_CLIENT
TRACE_DIRECTORY_SERVER

TRACE_TIMESTAMP_CLIENT=on
TRACE_TIMESTAMP_SERVER=on
TRACE_UNIQUE_CLIENT=on

TRACE_LEVEL_CLIENT
TRACE_LEVEL_SERVER

off (equivalent to 0) provides no tracing
user (equivalent to 4) traces to identify user-induced error conditions
admin (equivalent to 6) traces to identify installation-specific problems

support (equivalent to 16) provides trace information for troubleshooting information for Oracle Support Services



http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14212/troublestng.htm#sthref1709 


ocm1  Manage Oracle network processes (the Listener Control utility)
https://shenh.tripod.com/Oracleblog/index.blog/1824913/ocm1manage-oracle-network-processes-the-listener-control-utility/

lsnrctl status
lsnrctl start
lsnrctl stop
lsnrctl reload
lsnrctl service

-- ---------------------------------------------
$lsnrctl start
$lsnrctl stop
$lsnrctl
LSNRCTL> set current listener_10g
Current Listener is listener_10g
LSNRCTL> stat
Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1530)))
STATUS of the LISTENER
------------------------
Alias listener_10g
Version TNSLSNR for Linux: Version 10.2.0.1.0 - Production
Start Date 24-DEC-2006 08:19:45
Uptime 0 days 0 hr. 16 min. 35 sec
Trace Level support
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u02/app/oracle/product/10.2.0/db_1/network/admin/listener.ora
Listener Log File
/u02/app/oracle/product/10.2.0/db_1/network/log/listener_10g.log
Listener Trace File /tmp/listener.trc
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1530)))
Services Summary...
Service "DWDEV01" has 1 instance(s).
Instance "DWDEV01", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
LSNRCTL>


ocm1  Configure the network environment to allow connections to multiple databases
https://shenh.tripod.com/Oracleblog/index.blog/1824914/ocm1configure-the-network-environment-to-allow-connections-to-multiple-databases/

tnsnames.ora

multiple tns entries

-- ---------------------------------------
configure tnsnames.ora
configure listener.ora
tnsping each one
configure .profile in order to connect to multiple database's

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

1): cman.ora

2): failover to another database

3): single listener for multiple databases

      ( multiple sid for a single listener )

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

tnsnames.ora for failover and load balance

 


ocm1  Use configurationless connections
https://shenh.tripod.com/Oracleblog/index.blog/1824916/ocm1use-configurationless-connections/

sqlnet.ora
NAMES.DIRECTORY_PATH= (EZCONNECT,TNSNAMES)


scott/xxx@hostname:1521/ORCL
scott/xxx@//hostname:1521/ORCL


-- --------------------------------------------------
We have to use EZCONNECT to connect.
$ORACLE_ADMIN/sqlnet.ora
________________________________
NAMES.DIRECTORY_PATH= (EZCONNECT,TNSNAMES)
________________________________
$sqlplus /nolog
SQL> connect mhg/mhg@//localhost:1530/DWDEV01
Connected.
Where localhost is the host server , 1530 is the portname and DWDEV01 is the SERVICE NAME.

connect sys@"//gcds0040:1521/SRCH" as sysdba


Posted by shenh at 8:45 PM EST
Updated: Tuesday, 6 January 2009 9:26 PM EST
Sunday, 21 December 2008
Oracle Database 10g OCM Prep Course

 

http://www.itpub.net/viewthread.php?tid=1044550

 


Posted by shenh at 4:20 PM EST
Updated: Sunday, 21 December 2008 4:29 PM EST
Monday, 13 October 2008
grid control agent unreachable


1. Stop the Agent with "emctl stop agent"

2. Backup then edit the file agent ORACLE_HOME/sysman/admin/default_collection/instance.xmlp and change the line:

<CollectionItem NAME="health_check" UPLOAD="NO" COLLECT_WHEN_DOWN="TRUE">
to
<CollectionItem NAME="health_check" UPLOAD="NO" COLLECT_WHEN_DOWN="TRUE" DISABLED="TRUE">

3. Startup the agent with "emctl start agent"


Agent ORACLE_HOME/sysman/log/*

Note 379423.1 - How to edit or disable the Health Check Metric Collection in Grid Control 10.2

Note.430993.1 Ext/Pub Problem - Healthcheck Metric Collections Fails with Missing Error Messages

Note.473690.1 Ext/Mod Problem - emagent.trc shows "Instance Health Check initialization failed"

Note.469227.1 Comparison Between the Database Healthcheck and Database Response Metrics

Posted by shenh at 1:31 AM EDT
good news for TTS and read only tablespace

-- good news for TTS ( Transportable Tablespace )

Patch 2227223 ALTER TABLESPACE READ ONLY HANGING WHEN THERE ARE ACTIVE TX IN ANY TABLESPACE
 

alter tablespace xxx read only;

Posted by shenh at 1:27 AM EDT
Sunday, 28 September 2008

Now Playing: php site


php manual:
http://www.php.net/manual/en/

string function:
http://www.php.net/manual/en/book.strings.php
http://us.php.net/manual/en/function.strchr.php

number:
http://us3.php.net/number_format

Oracle oci8 manual:
http://us3.php.net/oci8

Oracle oci8 example:
http://us3.php.net/manual/en/oci8.examples.php

oci at orafaq: older version
http://www.orafaq.com/faqphp.htm


PHP FAQ on Oracle site:
http://www.oracle.com/technology/tech/php/htdocs/php_faq.html

Oracle PHP Cookbook:
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/index.html
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/index.html

The Underground PHP and Oracle Manual:
http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

PHP OCI Manual:
http://us2.php.net/oci8

Oracle related PHP:
http://oss.oracle.com/oracle-plus-php.html

PHP on Oracle OTN:
http://www.oracle.com/technology/tech/php/index.html

hitch hike Oracle PHP: ( concept, no code )
http://www.oracle.com/technology/pub/articles/php_experts/index.html

deployment:
http://www.oracle.com/technology/pub/articles/deployphp/index.html

Oracle php magazine:
http://oracle.phpmagazine.net/

http://blog.phpdeveloper.org/
http://blog.phpguy.org/category/php/


php oci8 class at database journal:
http://www.databasejournal.com/features/oracle/article.php/3763916
http://www.databasejournal.com/features/oracle/article.php/1547531
http://www.databasejournal.com/features/php/archives.php

Oracle Data Types:
http://www.techonthenet.com/oracle/datatypes.php
http://www.dbasupport.com/forums/showthread.php?t=43698


Oracle php cookbook:
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/index.html

http://www.orafaq.com/faqphp.htm
http://www.orafaq.com/faq/php

http://wiki.oracle.com/page/php?t=anon

Oracle + PHP:
http://oss.oracle.com/oracle-plus-php.html

http://us2.php.net/manual/en/oci8.examples.php
http://us2.php.net/oci8

Performance: Reduce parsing and binding variable part:
http://static7.userland.com/oracle/gems/alisonHolloway/ahollowaosdc2006.pdf

Oracle PHP in Win32: ( php4 and Apache 1.3 )
http://vsbabu.org/tutorials/oraphp.html

PHP Manual:
http://www.php.net/manual/en/


Oracel php on otn:
http://www.oracle.com/technology/pub/articles/tech_dev.html#oss

Latest 11G Tuning Tips:
http://tek.phparch.com/mats/slides/christopher_jones-web_scale_php.pdf

http://www.oracle.com/technology/tech/php/index.html

Oracle PHP Tutorial on Database Journal:
http://www.databasejournal.com/features/oracle/article.php/3763916
http://www.dbasupport.com/oracle/ora10g/php_intro.shtml


http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

http://www.oracle.com/technology/tech/php/index.html

http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

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

http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/index.html

*): dml and select
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/seliverstov-reports.html

1):  calling pl/sql, stored procedures and reference cursors

http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_sps.html

2):  dml transaction in php
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_transactions.html

3): date and time
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_dates.html

4): Binding variables in Oracle and PHP
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/ullman_bindings.html

5): lob and php
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_lobs.html


2):

http://www.oracle.com/technology/tech/oci/pdf/building-best-drivers.v9.pdf

 


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

http://search.cpan.org/~burak/PHP-Session-DBI-0.20/lib/PHP/Session/DBI.pm
http://search.cpan.org/~miyagawa/PHP-Session-0.26/lib/PHP/Session.pm


http://68.142.116.70/docs/cd/B19306_01/server.102/b14190/confmods.htm#HSADM003

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

function my_connect($un, $pw, $db)
{
$c = oci_pconnect($un, $pw, $db);
return $c;
}

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

$c = my_connect('hr', 'hrpwd', '//localhost/XE');
$s = oci_parse($c, 'select sysdate from dual');
oci_execute($s);
$row = oci_fetch_array($s);
echo $row['SYSDATE'] . "\n";

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


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

P116:

<?php
$c = oci_connect("hr", "hrpwd", "//localhost/XE");
$s = oci_parse($c, 'select city, postal_code from locations');
oci_execute($s);

print '<table border="1">';
while ($row = oci_fetch_array($s, OCI_RETURN_NULLS)) {
print '<tr>';
foreach ($row as $item)
print '<td>'.$item.'</td>';
print '</tr>';
}
print '</table>';
oci_close($c);
?>

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

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

Connecting to Oracle Using OCI8
102
close.php
<?php
function do_query($c, $query)
{
$s = oci_parse($c, $query);
oci_execute($s);
oci_fetch_all($s, $res);
echo "<pre>";
var_dump($res);
echo "</pre>";
}
$c1 = oci_connect('hr', 'hrpwd', '//localhost/XE');
$c2 = oci_connect('hr', 'hrpwd', '//localhost/XE');
do_query($c1, 'select user from dual');
oci_close($c1);
do_query($c1, 'select user from dual'); // fails
do_query($c2, 'select user from dual'); // succeeds
oci_close($c2);
?>

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

$c = oci_pconnect("hr", "hrpwd", "//localhost/XE");
do_query($c, "select sysdate from dual");
$s = oci_parse($c,
"alter session set nls_date_format=’YYYY-MM-DD HH24:MI:SS’");
$r = oci_execute($s);
do_query($c, "select sysdate from dual");


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

 


http://www.orafaq.com/wiki/PHP

http://www.orafaq.com/faq/php

http://www.orafaq.com/faqphp.htm


Oracle PHP at UPENN:
http://fusion.sas.upenn.edu/~robertom/conference/phpquebec2007/oracle_and_php.pdf

http://www.oracle.com/technology/tech/oci/pdf/building-best-drivers.v9.pdf

Zend And Oracle:
http://static.zend.com/topics/oracle_and_php.pdf

Sample Chapter:

book: Oracle Database 10g Express Edition PHP Web Programming ( ISBN: 0072263253 )
http://www.oracle.com/technology/books/pdfs/mclauglin-php-ch7.pdf

book: Learning PHP ( chapter 8: cookie Best )
http://www.oracle.com/technology/tech/php/pdf/php5_ch08.pdf

book: php cookbook: ( chapter 9: cookie )
http://www.oracle.com/technology/tech/php/pdf/ch08.pdf

book: Programming PHP:
http://www.oracle.com/technology/tech/php/htdocs/php_prog.html

book: Easy Oracle PHP: Create Dynamic Web Pages with Oracle Data

PHP Oracle Webhosting:
http://www.phporaclehosting.com/

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

http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

http://www.oracle.com/technology/tech/php/index.html

http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

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

http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/index.html

1):  calling pl/sql, stored procedures and reference cursors

http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_sps.html

2):  dml transaction in php
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_transactions.html

3): date and time
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_dates.html

4): Binding variables in Oracle and PHP
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/ullman_bindings.html

5): lob and php
http://www.oracle.com/technology/pub/articles/oracle_php_cookbook/fuecks_lobs.html


2):

http://www.oracle.com/technology/tech/oci/pdf/building-best-drivers.v9.pdf

 


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

http://search.cpan.org/~burak/PHP-Session-DBI-0.20/lib/PHP/Session/DBI.pm
http://search.cpan.org/~miyagawa/PHP-Session-0.26/lib/PHP/Session.pm


http://68.142.116.70/docs/cd/B19306_01/server.102/b14190/confmods.htm#HSADM003

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

function my_connect($un, $pw, $db)
{
$c = oci_pconnect($un, $pw, $db);
return $c;
}

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

$c = my_connect('hr', 'hrpwd', '//localhost/XE');
$s = oci_parse($c, 'select sysdate from dual');
oci_execute($s);
$row = oci_fetch_array($s);
echo $row['SYSDATE'] . "\n";

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


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

P116:

<?php
$c = oci_connect("hr", "hrpwd", "//localhost/XE");
$s = oci_parse($c, 'select city, postal_code from locations');
oci_execute($s);

print '<table border="1">';
while ($row = oci_fetch_array($s, OCI_RETURN_NULLS)) {
print '<tr>';
foreach ($row as $item)
print '<td>'.$item.'</td>';
print '</tr>';
}
print '</table>';
oci_close($c);
?>

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

 


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

Connecting to Oracle Using OCI8
102
close.php
<?php
function do_query($c, $query)
{
$s = oci_parse($c, $query);
oci_execute($s);
oci_fetch_all($s, $res);
echo "<pre>";
var_dump($res);
echo "</pre>";
}
$c1 = oci_connect('hr', 'hrpwd', '//localhost/XE');
$c2 = oci_connect('hr', 'hrpwd', '//localhost/XE');
do_query($c1, 'select user from dual');
oci_close($c1);
do_query($c1, 'select user from dual'); // fails
do_query($c2, 'select user from dual'); // succeeds
oci_close($c2);
?>

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

$c = oci_pconnect("hr", "hrpwd", "//localhost/XE");
do_query($c, "select sysdate from dual");
$s = oci_parse($c,
"alter session set nls_date_format=’YYYY-MM-DD HH24:MI:SS’");
$r = oci_execute($s);
do_query($c, "select sysdate from dual");


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

 


Posted by shenh at 3:57 PM EDT
Tuesday, 16 September 2008
finding the dependent object


set linesize 1000 trimspool on

-- define my_name=DBMS_ADVISOR

define my_name=X$KTUXE

select * from (
SELECT name, type, 'USED IN' REFERENCE  
FROM dba_dependencies
WHERE referenced_name = '&&MY_NAME'
UNION
SELECT referenced_name, REFERENCED_TYPE type,
'USING' REFERENCE  
FROM dba_dependencies
WHERE name = '&&MY_NAME'
)
order by REFERENCE, type;

DBA_ADVISOR_DEF_PARAMETERS

 

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


dict:
V$FIXED_TABLE
V$FIXED_VIEW_DEFINITION


select table_name from dict where table_name like '%FIX%'

 


Posted by shenh at 4:47 PM EDT
Updated: Tuesday, 16 September 2008 4:49 PM EDT
transaction rollback time


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

http://www.wisdomforce.com/resources/docs/complete_rollback_script.pdf

SELECT sum(ktuxesiz) xx FROM x$ktuxe order by 1;

sys.x_$ktuxe or sys.x$ktuxe, try out first.


set serveroutput on size 1000000

DECLARE
CURSOR tx
IS
SELECT /*+ USE_NL(S,T,X) */
NVL
(s.username,
'session no more exists or running on the other node of RAC'
),
x.ktuxeusn, x.ktuxeslt, x.ktuxesqn, x.ktuxesiz
FROM ((sys.x_$ktuxe x LEFT JOIN sys.gv_$transaction t ON
t.xidusn = x.ktuxeusn AND t.xidslot = x.ktuxeslt AND
t.xidsqn = x.ktuxesqn AND x.inst_id = t.inst_id) LEFT JOIN
sys.gv_$session s ON
s.saddr = t.ses_addr AND
s.inst_id = t.inst_id)
WHERE x.ktuxesta = 'ACTIVE' AND x.ktuxesiz > 1;
user_name VARCHAR2 (80);
xid_usn NUMBER;
xid_slot NUMBER;
xid_sqn NUMBER;
used_ublk1 NUMBER;
used_ublk2 NUMBER;
BEGIN
OPEN tx;
LOOP
FETCH tx
INTO user_name, xid_usn, xid_slot, xid_sqn, used_ublk1;
EXIT WHEN tx%NOTFOUND;
IF tx%ROWCOUNT = 1
THEN
sys.DBMS_LOCK.sleep (120);
SELECT SUM (ktuxesiz)
INTO used_ublk2
FROM sys.x_$ktuxe
WHERE ktuxeusn = xid_usn
AND ktuxeslt = xid_slot
AND ktuxesqn = xid_sqn
AND ktuxesta = 'ACTIVE';
IF used_ublk2 < used_ublk1
THEN
sys.DBMS_OUTPUT.put_line ('session (' || user_name || ')');
sys.DBMS_OUTPUT.put_line
( 'transaction '
|| xid_usn
|| '.'
|| xid_slot
|| '.'
|| xid_sqn
|| ' will finish rolling back at approximately '
|| TO_CHAR ( SYSDATE
+ used_ublk2
/ (used_ublk1 - used_ublk2)
/ 30
/ 24,
'HH24:MI:SS DD-MON-YYYY'
)
);
END IF;
END IF;
END LOOP;
IF user_name IS NULL
THEN
sys.DBMS_OUTPUT.put_line ('No transactions appear to be rolling back.');
END IF;
END;
/

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


show parameter fast_start_parallel_rollback

V$FAST_START_SERVERS

V$FAST_START_TRANSACTIONS

select usn,state, undoblocksdone,undoblockstotal,cputime from V$FAST_START_TRANSACTIONS;

select * from v$rollstat where xacts >0;


select usn, state, undoblockstotal "Total", undoblocksdone "Done",
undoblockstotal,undoblocksdone,cputime
from v$fast_start_transactions
/


set linesize 100
alter session set NLS_DATE_FORMAT='DD-MON-YYYY HH24:MI:SS';

column XX heading "Estimated Time|to Compelete"

select usn, state, undoblockstotal "Total", undoblocksdone "Done", undoblockstotal-undoblocksdone "ToDo",
decode(cputime,0,'unknown',sysdate+(((undoblockstotal-undoblocksdone) / (
undoblocksdone / cputime)) / 86400)) xx
from v$fast_start_transactions;

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


Posted by shenh at 4:46 PM EDT
Updated: Friday, 23 January 2009 11:45 AM EST
global database name, database link, and global_names=true init.ora parameter:

global database name, database link, and global_names=true init.ora parameter:

 * Global database link names must match database global names
 * Your GLOBAL_NAMES initialization parameter should be set to TRUE
 * You must enable the plug and play setting for your listeners

The global name is a combination of the database name and domain.


--  query the database global name:
select global_name from global_name;

-- change database global name:
ALTER DATABASE RENAME GLOBAL_NAME TO testdb.heaven.com;
ALTER DATABASE RENAME GLOBAL_NAME TO EVRSBS04.DBT.NET

-- The global database name used is on a remote database
   to ensure that it's DB links conform to GLOBAL_NAMES=true.

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

If I set global_names = true, then the db link naming rule goes into effect.

SQL> select * from dual@dby.world;

D
-
X

1 row selected.

SQL> alter session set global_names = true;

Session altered.

SQL> select * from dual@dby.world;
select * from dual@dby.world
                   *
ERROR at line 1:
ORA-02085: database link DBY.WORLD connects to DBYT.WORLD


notes:
Using global names would be safer then relying on the tnsnames.ora file.  
Relying on the tnsnames.ora file seems too shaky -- too easy to mess up when
you havent had quite enough sleep some night.  global names will just stop you.


select sys_context('userenv','db_name') db_name from dual;
select sys_context( 'userenv', 'db_name' ) sc, global_name from global_name;

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

Posted by shenh at 4:44 PM EDT
Monday, 4 August 2008
dbms_metadata get_ddl


http://www.psoug.org/reference/dbms_metadata.html

set pagesize 0
set long 90000
set feedback off
set echo off

SET LONG 10000

set longchunk 10000

dbms_metadata.get_granted_ddl

dbms_metadata.get_sysprivs

dbms_metadata.set_filter

dbms_metadata.set_transform_param

1):
-- omit the storage clause
exec dbms_metadata.set_transform_param( dbms_metadata.session_transform, 'STORAGE',FALSE);

exec dbms_metadata.set_transform_param( dbms_metadata.session_transform, 'DEFAULT');

2):
dmsf := dbms_metadata.session_transform
dbms_metadata.set_transform_param(dmsf, 'TABLESPACE', FALSE);
dbms_metadata.set_transform_param(dmsf, 'STORAGE', FALSE);
dbms_metadata.set_transform_param(dmsf, 'SEGMENT_ATTRIBUTES', FALSE);

SELECT dbms_metadata.get_ddl('TABLE', 'TEST')
FROM dual;

SELECT dbms_metadata.get_ddl('VIEW', 'MY_TABLES')
FROM dual;

SELECT dbms_metadata.get_ddl('FUNCTION', 'WHOAMI')
FROM dual;

SELECT dbms_metadata.get_ddl('TABLESPACE', 'UWDATA')
FROM dual;

select dbms_metadata.get_ddl('TABLESPACE', 'USERS') from dual;

 


Posted by shenh at 3:44 PM EDT
all_arguments desc standard


all_arguments

http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/feuerstein_codech.html


got all SQL function:

desc sys.standard

or

select distinct object_name 
from all_arguments
where
owner='SYS' and
package_name = 'STANDARD' and
object_name not like '%$%' and 
rownum < 10000
order by object_name
/

got all package:

select distinct package_name 
from all_arguments
where
owner='SYS' and
-- package_name = 'STANDARD' and
package_name not like '%$%' and 
rownum < 10000
order by package_name
/

 


Posted by shenh at 3:43 PM EDT
AUTONOMOUS_TRANSACTION authid current_user


PRAGMA AUTONOMOUS_TRANSACTION;

authid current_user
vs
pragma authid Definer

http://www.adp-gmbh.ch/ora/plsql/authid.html

create function f_authid_cu return number
  authid current_user
as begin
  return 0;
end f_authid_cu;
/

create function f_authid_d return number
  authid definer
as begin
  return 0;
end f_authid_d;
/


Posted by shenh at 3:41 PM EDT
Saturday, 12 July 2008
oem item list


1. Server Configuration
ocm1  Create the database
https://shenh.tripod.com/Oracleblog/index.blog/1824896/ocm1-create-the-database/

ocm1  Determine and set sizing parameters for database structures
https://shenh.tripod.com/Oracleblog/index.blog/1824898/ocm1-determine-and-set-sizing-parameters-for-database-structures/

ocm1  Create and manage temporary, permanent, and undo tablespaces
https://shenh.tripod.com/Oracleblog/index.blog/1824899/ocm1create-and-manage-temporary-permanent-and-undo-tablespaces/

ocm1  Stripe data files across multiple physical devices and locations
https://shenh.tripod.com/Oracleblog/index.blog/1824900/ocm1stripe-data-files-across-multiple-physical-devices-and-locations/

ocm1  Configure the database environment to support optimal data access performance
https://shenh.tripod.com/Oracleblog/index.blog/1824901/ocm1configure-the-database-environment-to-support-optimal-data-access-performance/

ocm1  Create and manage database configuration files
https://shenh.tripod.com/Oracleblog/index.blog/1824902/ocm1create-and-manage-database-configuration-files/

ocm1  Create and manage bigfile tablespaces
https://shenh.tripod.com/Oracleblog/index.blog/1824904/ocm1create-and-manage-bigfile-tablespaces/

ocm1  Create and manage multiple network configuration files
https://shenh.tripod.com/Oracleblog/index.blog/1824905/ocm1create-and-manage-multiple-network-configuration-files/

ocm1  Create and configure a listener
https://shenh.tripod.com/Oracleblog/index.blog/1824907/ocm1create-and-configure-a-listener/

ocm1  Configure the database instance to support shared server connections
https://shenh.tripod.com/Oracleblog/index.blog/1824908/ocm1configure-the-database-instance-to-support-shared-server-connections/

ocm1  Set up network tracing
https://shenh.tripod.com/Oracleblog/index.blog/1824912/ocm1set-up-network-tracing/


ocm1  Manage Oracle network processes (the Listener Control utility)
https://shenh.tripod.com/Oracleblog/index.blog/1824913/ocm1manage-oracle-network-processes-the-listener-control-utility/


ocm1  Configure the network environment to allow connections to multiple databases
https://shenh.tripod.com/Oracleblog/index.blog/1824914/ocm1configure-the-network-environment-to-allow-connections-to-multiple-databases/


ocm1  Use configurationless connections
https://shenh.tripod.com/Oracleblog/index.blog/1824916/ocm1use-configurationless-connections/

2. Enterprise Manager Grid Control
ocm2  Install the Enterprise Manager Grid Control software
https://shenh.tripod.com/Oracleblog/index.blog/1824922/ocm2-install-the-enterprise-manager-grid-control-software/


ocm2  Configure the Enterprise Manager repository
https://shenh.tripod.com/Oracleblog/index.blog/1824923/ocm2-configure-the-enterprise-manager-repository/

ocm2  Create Enterprise Manager Grid Control users
https://shenh.tripod.com/Oracleblog/index.blog/1824924/ocm2-create-enterprise-manager-grid-control-users/


ocm2  Use Enterprise Manager to modify a database configuration
https://shenh.tripod.com/Oracleblog/index.blog/1824925/ocm2-use-enterprise-manager-to-modify-a-database-configuration/

ocm2  Configure Enterprise Manager to modify a database availability
https://shenh.tripod.com/Oracleblog/index.blog/1824927/ocm2-configure-enterprise-manager-to-modify-a-database-availability/


ocm2  Create and manage jobs
https://shenh.tripod.com/Oracleblog/index.blog/1824929/ocm2-create-and-manage-jobs/


ocm2  Create and monitor alerts
https://shenh.tripod.com/Oracleblog/index.blog/1824927/ocm2-configure-enterprise-manager-to-modify-a-database-availability/


ocm2  Create notifications
https://shenh.tripod.com/Oracleblog/index.blog/1824931/ocm2-create-notifications/


ocm2  Implement Grid Control and Database Control
https://shenh.tripod.com/Oracleblog/index.blog/1824933/ocm2-implement-grid-control-and-database-control/


ocm2  Choose the appropriate tablespace type for the intended use
https://shenh.tripod.com/Oracleblog/index.blog/1824934/ocm2-choose-the-appropriate-tablespace-type-for-the-intended-use/


ocm2  Create Scheduler jobs
https://shenh.tripod.com/Oracleblog/index.blog/1824935/ocm2-create-scheduler-jobs/

ocm2  Create schedules
https://shenh.tripod.com/Oracleblog/index.blog/1824936/ocm2-create-schedules/


ocm2  Assign jobs to windows
https://shenh.tripod.com/Oracleblog/index.blog/1824938/ocm2-assign-jobs-to-windows/

ocm2  Create programs
https://shenh.tripod.com/Oracleblog/index.blog/1824940/ocm2-create-programs/

ocm2  Create job classes
https://shenh.tripod.com/Oracleblog/index.blog/1824941/ocm2-create-job-classes/

ocm2  Install the Enterprise Manager Grid Control infrastructure
https://shenh.tripod.com/Oracleblog/index.blog/1824942/ocm2-install-the-enterprise-manager-grid-control-infrastructure/

ocm2  Deploy Enterprise Manager Grid Control agents
https://shenh.tripod.com/Oracleblog/index.blog/1824944/ocm2-deploy-enterprise-manager-grid-control-agents/

ocm2  Configure Grid Control for business requirements
https://shenh.tripod.com/Oracleblog/index.blog/1824945/ocm2-configure-grid-control-for-business-requirements/


3. Managing Database Availability
ocm3  Create a recovery catalog database
https://shenh.tripod.com/Oracleblog/index.blog/1824950/ocm3create-a-recovery-catalog-database/

ocm3  Configure Recovery Manager
https://shenh.tripod.com/Oracleblog/index.blog/1824951/ocm3configure-recovery-manager/

ocm3  Use Recovery Manager to perform database backups
https://shenh.tripod.com/Oracleblog/index.blog/1824952/ocm3use-recovery-manager-to-perform-database-backups/

ocm3  Use Recover Manager to perform complete database restore and recovery operations
https://shenh.tripod.com/Oracleblog/index.blog/1824953/ocm3use-recover-manager-to-perform-complete-database-restore-and-recovery-operations/

ocm3  Set Flashback Database parameters
https://shenh.tripod.com/Oracleblog/index.blog/1824954/ocm3set-flashback-database-parameters/

ocm3  Monitor Flashback Database logs and statistics
https://shenh.tripod.com/Oracleblog/index.blog/1824955/ocm3monitor-flashback-database-logs-and-statistics/

ocm3  Perform a Flashback Database operation
https://shenh.tripod.com/Oracleblog/index.blog/1824956/ocm3perform-a-flashback-database-operation/

ocm3  Configure a flash recovery area
https://shenh.tripod.com/Oracleblog/index.blog/1824957/ocm3configure-a-flash-recovery-area/


4. Data Management
ocm4  Implement fine-grained auditing
https://shenh.tripod.com/Oracleblog/index.blog/1824988/ocm4-implement-finegrained-auditing/

ocm4  Create a secure application role
https://shenh.tripod.com/Oracleblog/index.blog/1824989/ocm4-create-a-secure-application-role/

ocm4  Grant specific privileges for a Flashback Query
https://shenh.tripod.com/Oracleblog/index.blog/1824990/ocm4-grant-specific-privileges-for-a-flashback-query/

ocm4  Set parameters for retaining undo
https://shenh.tripod.com/Oracleblog/index.blog/1824991/ocm4-set-parameters-for-retaining-undo/

ocm4  Implement fine-grained access control
https://shenh.tripod.com/Oracleblog/index.blog/1824994/ocm4-implement-finegrained-access-control/

ocm4  Create and manage contexts
https://shenh.tripod.com/Oracleblog/index.blog/1824995/ocm4-create-and-manage-contexts/

ocm4  Use SQL*Loader
https://shenh.tripod.com/Oracleblog/index.blog/1824996/ocm4-use-sqlloader/

ocm4  Implement transportable tablespaces between homogeneous and heterogeneous systems (using different methods of moving files)
https://shenh.tripod.com/Oracleblog/index.blog/1824997/ocm4-implement-transportable-tablespaces/

ocm4  Choose the appropriate partition method (range, hash, list, and composite)
https://shenh.tripod.com/Oracleblog/index.blog/1824999/ocm4-choose-the-appropriate-partition-method/

ocm4  Choose the appropriate partition key
https://shenh.tripod.com/Oracleblog/index.blog/1825000/ocm4-choose-the-appropriate-partition-key/

ocm4  Choose appropriate indexing methods (local, global, prefixed, and nonprefixed)
https://shenh.tripod.com/Oracleblog/index.blog/1825002/ocm4-choose-appropriate-indexing-methods/

ocm4  Perform partition maintenance operations
https://shenh.tripod.com/Oracleblog/index.blog/1825004/ocm4-perform-partition-maintenance-operations/

ocm4  Maintain indexes on a partitioned table
https://shenh.tripod.com/Oracleblog/index.blog/1825005/ocm4-maintain-indexes-on-a-partitioned-table/

ocm4  Create and manage LOB segments
https://shenh.tripod.com/Oracleblog/index.blog/1825007/ocm4-create-and-manage-lob-segments/

ocm4  Apply parallelism appropriately
https://shenh.tripod.com/Oracleblog/index.blog/1825009/ocm4-apply-parallelism-appropriately/

ocm4  Tune memory for parallel operations
https://shenh.tripod.com/Oracleblog/index.blog/1825010/ocm4-tune-memory-for-parallel-operations/

ocm4  Set parallel parameters
https://shenh.tripod.com/Oracleblog/index.blog/1825011/ocm4-set-parallel-parameters/

5. Data Warehouse Management
ocm5  Create external tables (Data Loader and Data Pump drivers)
https://shenh.tripod.com/Oracleblog/index.blog/1825019/ocm5-create-external-tables/

ocm5  Implement Data Pump export and import jobs for data transfer
https://shenh.tripod.com/Oracleblog/index.blog/1825020/ocm5-implement-data-pump-export-and-import-jobs-for-data-transfer/

ocm5  Implement Data Pump to and from remote databases
https://shenh.tripod.com/Oracleblog/index.blog/1825021/ocm5-implement-data-pump-to-and-from-remote-databases/

ocm5  Implement Replication/Streams
https://shenh.tripod.com/Oracleblog/index.blog/1825022/ocm5-implement-replicationstreams/

ocm5  Configure and manage master replication
https://shenh.tripod.com/Oracleblog/index.blog/1825023/ocm5-configure-and-manage-master-replication/

ocm5  Configure and manage distributed materialized views
https://shenh.tripod.com/Oracleblog/index.blog/1825024/ocm5-configure-and-manage-distributed-materialized-views/

ocm5  Configure and manage Streams for replication
https://shenh.tripod.com/Oracleblog/index.blog/1825025/ocm5-configure-and-manage-streams-for-replication/

6. Performance Management
ocm6  Install Statspack
https://shenh.tripod.com/Oracleblog/index.blog/1825027/ocm6-install-statspack/

ocm6  Adjust the default interval for statistics collection
https://shenh.tripod.com/Oracleblog/index.blog/1825028/ocm6-adjust-the-default-interval-for-statistics-collection/

ocm6  Customize the events that are monitored
https://shenh.tripod.com/Oracleblog/index.blog/1825030/ocm6-customize-the-events-that-are-monitored/

ocm6  Use ADDM to analyze statistics and to identify performance bottlenecks and fix them
https://shenh.tripod.com/Oracleblog/index.blog/1825031/ocm6-use-addm-to-analyze-statistics-and-to-identify-performance-bottlenecks-and-fix-them/

ocm6  Implement automatic shared memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825032/ocm6-implement-automatic-shared-memory-management/

ocm6  Tune memory using manual memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825034/ocm6-tune-memory-using-manual-memory-management/

ocm6  Monitor and tune SGA areas that are not automatically tuned
https://shenh.tripod.com/Oracleblog/index.blog/1825034/ocm6-tune-memory-using-manual-memory-management/

ocm6  Implement automatic SQL execution memory management
https://shenh.tripod.com/Oracleblog/index.blog/1825036/ocm6-implement-automatic-sql-execution-memory-management/

ocm6  Tune the PGA using work area size parameters
https://shenh.tripod.com/Oracleblog/index.blog/1825037/ocm6-tune-the-pga-using-work-area-size-parameters/

ocm6  Use the PGA Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825038/ocm6-use-the-pga-advisor/

ocm6  Create a Database Resource Manager plan with directives (active session count, max execution time)
https://shenh.tripod.com/Oracleblog/index.blog/1825039/ocm6-create-a-database-resource-manager-plan-with-directives/

ocm6  Create consumer groups
https://shenh.tripod.com/Oracleblog/index.blog/1825040/ocm6-create-consumer-groups/

ocm6  Configure consumer group mappings
https://shenh.tripod.com/Oracleblog/index.blog/1825041/ocm6-configure-consumer-group-mappings/

ocm6  Manage Services
https://shenh.tripod.com/Oracleblog/index.blog/1825042/ocm6-manage-services-oracle-database-10g-release-2/

ocm6  Create and manage objects to accommodate different data access methods (schema tuning)
https://shenh.tripod.com/Oracleblog/index.blog/1825043/ocm6-create-and-manage-objects-to-accommodate-different-data-access-methods-schema-tuning/

ocm6  Use the SQL Tuning Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825044/ocm6-use-the-sql-tuning-advisor/

ocm6  Use the SQL Access Advisor
https://shenh.tripod.com/Oracleblog/index.blog/1825045/ocm6-use-the-sql-access-advisor/

ocm6  Gather Optimizer statistics
https://shenh.tripod.com/Oracleblog/index.blog/1825046/ocm6-gather-optimizer-statistics/

ocm6  Interpret execution plan
https://shenh.tripod.com/Oracleblog/index.blog/1825047/ocm6-interpret-execution-plan/

ocm6  Use SQL tuning tools and features
https://shenh.tripod.com/Oracleblog/index.blog/1825048/ocm6-use-sql-tuning-tools-and-features/

7. Real Application Clusters
ocm7  Install Oracle Clusterware
https://shenh.tripod.com/Oracleblog/index.blog/1825049/ocm7-install-cluster-ready-services/

ocm7  Install the Oracle Database 10g software
https://shenh.tripod.com/Oracleblog/index.blog/1825050/ocm7-install-the-oracle-database-10g-software/

ocm7  Implement ASM failure groups
https://shenh.tripod.com/Oracleblog/index.blog/1825051/ocm7-implement-asm-failure-groups/

ocm7  Create and manage as ASM instance
https://shenh.tripod.com/Oracleblog/index.blog/1825052/ocm7-create-and-manage-as-asm-instance/

ocm7  Create and manage ASM disk groups
https://shenh.tripod.com/Oracleblog/index.blog/1825053/ocm7-create-and-manage-asm-disk-groups/

ocm7  Configure ASM for the shared disks, and create a clustered database
https://shenh.tripod.com/Oracleblog/index.blog/1825054/ocm7-configure-asm-for-the-shared-disks-and-create-a-clustered-database/

ocm7  Configure archiving
https://shenh.tripod.com/Oracleblog/index.blog/1825056/ocm7configure-archiving/

ocm7  Configure Services with a primary instance and an available instance
https://shenh.tripod.com/Oracleblog/index.blog/1825055/ocm7-configure-services-with-a-primary-instance-and-an-available-instance/

8. Data Guard
ocm8  Use Data Guard Manager and DGMGRL
https://shenh.tripod.com/Oracleblog/index.blog/1825057/ocm8-use-data-guard-manager-and-dgmgrl/

ocm8  Create and utilize a physical standby database
https://shenh.tripod.com/Oracleblog/index.blog/1825058/ocm8-create-and-utilize-a-physical-standby-database/

ocm8  Create and utilize a logical standby database
https://shenh.tripod.com/Oracleblog/index.blog/1825059/ocm8-create-and-utilize-a-logical-standby-database/

ocm8  Set up log transport services for various levels or protection
https://shenh.tripod.com/Oracleblog/index.blog/1825060/ocm8-set-up-log-transport-services-for-various-levels-or-protection/


ocm8  Configure the network environment to allow communication between the standby database and the primary database
https://shenh.tripod.com/Oracleblog/index.blog/1825061/ocm8-configure-the-network-environment-to-allow-communication-between-the-standby-database-and-the-primary-database/

ocm8  Open the physical standby database in a "ready-only" state
https://shenh.tripod.com/Oracleblog/index.blog/1825062/ocm8-open-the-physical-standby-database-in-a-readyonly-state/

ocm8 Perform a switchover operation and a failover operation
https://shenh.tripod.com/Oracleblog/index.blog/1825063/ocm8-perform-a-switchover-operation-and-a-failover-operation/

ocm8  Implement Data Guard
https://shenh.tripod.com/Oracleblog/index.blog/1825064/ocm8-implement-data-guard/

 


Posted by shenh at 4:52 PM EDT
Updated: Saturday, 12 July 2008 6:05 PM EDT
Saturday, 5 July 2008
ocm Oracle manual

All Books:

http://www.oracle.com/pls/db102/portal.all_books#index-ADV

 Oracle® Database High Availability Best Practices 10g R2 - B25159-01

http://download.oracle.com/docs/cd/B19306_01/server.102/b25159/monitor.htm#i1005919

Concepts
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14220/toc.htm

Database Administrator's Guide
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14231/toc.htm

 Application Developer's Guide - Fundamentals
http://download-east.oracle.com/docs/cd/B19306_01/appdev.102/b14251/toc.htm

Utilities
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14215/toc.htm

Net Services Administrator's Guide
http://download.oracle.com/docs/cd/B19306_01/network.102/b14212/toc.htm

Performance Tuning Guide
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm

2 Day + Performance Tuning Guide
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b28051/toc.htm

Oracle® Database Data Warehousing Guide
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14223/concept.htm

SQL*Plus® User's Guide and Reference
http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/toc.htm

DataGuard:
Data Guard Concepts and Administration
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14239/toc.htm

Streams Concepts and Administration
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14229/toc.htm


Streams Advanced Queuing User's Guide and Reference
http://download.oracle.com/docs/cd/B19306_01/server.102/b14257/toc.htm

Streams Replication Administrator's Guide
http://download.oracle.com/docs/cd/B19306_01/server.102/b14228/toc.htm

Advanced Replication
http://download.oracle.com/docs/cd/B19306_01/server.102/b14226/toc.htm

*** Advanced Replication Management API Reference
http://download.oracle.com/docs/cd/B19306_01/server.102/b14227/toc.htm 

Backup and Recovery Basics
http://download-est.oracle.com/docs/cd/B19306_01/backup.102/b14192/toc.htm

Backup and Recovery Advanced User's Guide
http://download.oracle.com/docs/cd/B19306_01/backup.102/b14191/toc.htm


Enterprise Manager Concepts
http://download.oracle.com/docs/cd/B19306_01/em.102/b31949/toc.htm

*** Enterprise Manager Grid Control Installation and Basic Configuration
http://download.oracle.com/docs/cd/B19306_01/em.102/b40103/toc.htm

*** Enterprise Manager Advanced Configuration
http://download.oracle.com/docs/cd/B19306_01/em.102/b40002/toc.htm

Enterprise Manager Grid Control Quick Installation Guide for Linux x86
http://download.oracle.com/docs/cd/B19306_01/install.102/b28091/toc.htm

Enterprise Manager Release Notes for Linux x86
http://download.oracle.com/docs/cd/B19306_01/relnotes.102/b16243/toc.htm

Enterprise Manager Management Agent Release Notes for Linux x86-64
http://download.oracle.com/docs/cd/B19306_01/relnotes.102/b28657/toc.htm

Enterprise Manager Oracle Database and Database-Related Metric Reference Manual
http://download.oracle.com/docs/cd/B19306_01/em.102/b25986/oracle_database.htm

http://download.oracle.com/docs/cd/B19306_01/em.102/b25986/preface.htm


*** Security Guide
http://download.oracle.com/docs/cd/B19306_01/network.102/b14266/toc.htm

Advanced Security Administrator's Guide
http://download.oracle.com/docs/cd/B19306_01/network.102/b14268/toc.htm


Posted by shenh at 4:54 PM EDT
Updated: Saturday, 12 July 2008 1:28 PM EDT

Newer | Latest | Older