You are on page 1of 707

Page 1 Oracle DBA Code Examples

Oracle DBA Code Examples
























Version Date: 30 July 2011
Editor: Ahmed Baraka
Page 2 Oracle DBA Code Examples

Document Purpose
This document is edited to be a quick reference of code examples used to achieve specific
Oracle DBA tasks. No explanation on any subject is presented.
The document is simply oriented based on the required task, the code to perform the task and
any precautions or warnings when using the code. Also, it will be specified if the code is
version specific. The document mainly demonstrates using SQL and PL/SQL code to achieve
any task. It does not concentrate on using OEM to perform a task. However, if there will be a
significant advantage, there could be just some hints on using OEM for some tasks.
Prerequisites
The document assumes that the reader has already the knowledge of Oracle database
administration.
How to Use the Document
1. Go to Contents section
2. Search the required task
3. Click on the required task link
4. Read the warnings and/or usage guideline, if any.
5. Make any modification in the code to match your case.
Oracle Database Versions
The code presented in the document is to operate on Oracle database versions 10g and 11g. It
will be stated, if the code is version specific.
Obtaining Latest Version of the Document
Latest version can be obtained from my site or by emailing me at info@ahmedbaraka.com
Usage Terms
Anyone is authorized to copy this document to any means of storage and present it in any
format to any individual or organization for non-commercial purpose free.
No individual or organization may use this document for commercial purpose without a
written permission from the editor.
This document is for informational purposes only, and may contain typographical errors and
technical inaccuracies.
There is no warranty of any type for the code or information presented in this
document. The editor is not responsible for any loses or damage resulted from
using the information or executing the code in this document.
If any one wishes to correct a statement or a typing error or add a new piece of information,
please send the request to info@ahmedbaraka.com

Page 3 Oracle DBA Code Examples

Document Parts
Part 1 Oracle DBA Fundamentals _______________________ 36
Part 2 Oracle Database Net Services ___________________ 238
Part 3 Oracle Database Backup and Recovery ____________ 247
Part 4 Oracle Database Security _______________________ 311
Part 5 Oracle Database Performance Tuning _____________ 340
Part 6 Oracle Automatic Storage Management (ASM) ______ 396
Part 7 Oracle Real Application Cluster __________________ 410
Part 8 Oracle RAC One Node __________________________ 529
Part 9 Oracle Warehousing___________________________ 551
Part 10 Oracle Database Utilities _______________________ 556
Part 11 Miscellaneous Oracle Database Topics _____________ 582
Part 12 PL/SQL Samples ______________________________ 596
Part 13 Appendixes__________________________________ 674

Page 4 Oracle DBA Code Examples

Contents
Part 1 Oracle DBA Fundamentals _______________________ 36
DBA: Best Practices ____________________________________ 37
DBA: Best Practice Guidelines for Standalone and RAC Databases____________37
Oracle Database Installation Consideration __________________ 38
Estimating Disk and Memoery Requirements ____________________________38
Optimal Flexible Architecture_________________________________________38
Oracle Products Installed with the 11.1 Release __________________________39
Installing Oracle 10g R2 on Enterprise Linux 4 _______________ 40
Installation Environment ____________________________________________40
Required Software _________________________________________________40
Used Hardware ___________________________________________________40
Installation Plan___________________________________________________40
1. Preinstallation tasks __________________________________________________ 40
2. Oracle Database 10g Software Installation_________________________________ 44
3. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software_____________ 44
4. Configure Listeners ___________________________________________________ 45
5. Create Database _____________________________________________________ 45
6. Postinstallation Tasks _________________________________________________ 45
Installing Oracle 11g R2 on Enterprise Linux 5 _______________ 47
Installation Environment ____________________________________________47
Required Software _________________________________________________47
Used Hardware ___________________________________________________47
Installation Plan___________________________________________________47
1. Preinstallation tasks __________________________________________________ 47
2. Oracle Database 11g Software Installation_________________________________ 53
3. Apply Patchset_______________________________________________________ 53
4. Configure Listeners ___________________________________________________ 53
5. Create Database _____________________________________________________ 53
6. Postinstallation Tasks _________________________________________________ 53
Page 5 Oracle DBA Code Examples

Installing Oracle 11g R2 on Enterprise Linux 5.5 with ASM______ 54
Installation Environment ____________________________________________54
Required Software _________________________________________________54
Used Hardware ___________________________________________________54
Installation Plan___________________________________________________54
1. Preinstallation tasks __________________________________________________ 55
2. Oracle Grid Infrastructure installation_____________________________________ 60
3. Oracle Grid Infrastructure Patching_______________________________________ 61
4. Oracle Database 11g R2 Software Installation ______________________________ 61
5. Oracle Database 11g R2 Software Patching ________________________________ 62
6. Install EM Agent in cluster nodes (if required) ______________________________ 62
7. ASM Diskgroups Creation ______________________________________________ 62
8. Database Creation____________________________________________________ 62
9. Postinstallation tasks__________________________________________________ 62
10. General Useful Postinstallation Tasks in Linux _____________________________ 62
Managing Oracle Database Instance _______________________ 64
Product Release Number ____________________________________________64
Oracle Database Release Number Format____________________________________ 64
Obtaining License Information________________________________________64
Managing the Instance Architecture ___________________________________64
Obtaining Information about the Instance Processes ___________________________ 64
Obtaining Information about the SGA_______________________________________ 65
Clearing the Buffer Cache ________________________________________________ 65
Database Administration Authentication ________________________________65
Using Operating System Authentication _____________________________________ 65
Using Password File Authentication_________________________________________ 66
Identifying Users SYSDBA or SYSOPER Users _________________________________ 66
Data Dictionary and Dynamic Performance Views_________________________66
Data Dictionary Creation _________________________________________________ 66
Startup and Shutdown______________________________________________66
Startup Levels _________________________________________________________ 66
Shutdown Levels _______________________________________________________ 66
Autostart of Database in Windows _________________________________________ 66
Automatically Starting Databases in Unix ____________________________________ 66
Page 6 Oracle DBA Code Examples

Quiescing a Database ______________________________________________71
Suspending a Database _____________________________________________71
Dropping a Database _______________________________________________71
Initialization Files__________________________________________________71
Managing Initialization Files ______________________________________________ 71
Managing Parameters in SPFILE ___________________________________________ 72
Alert and Trace Files _______________________________________________72
Monitoring Alert and Trace Files ___________________________________________ 72
Managing Oracle Database Physical Structure ________________ 74
Managing Control Files______________________________________________74
Obtaining Control File information__________________________________________ 74
Creating Additional Copies, Renaming, and Relocating Control Files _______________ 74
Creating New Control Files _______________________________________________ 74
Backing Up Control Files _________________________________________________ 75
Manage the Size of Control Files ___________________________________________ 75
Multiplexing the Control File ______________________________________________ 76
Maintaining Online Redo Log Files _____________________________________76
Forcing Log Switches and Checkpoints ______________________________________ 76
Adding Online Redo Log File Groups ________________________________________ 76
Adding Online Redo Log File Members ______________________________________ 76
Dropping Online Redo Log File Groups ______________________________________ 76
Dropping Online Redo Log File Members_____________________________________ 76
Relocating and Renaming Redo Log Members_________________________________ 76
Verifying Blocks in Redo Log Files __________________________________________ 77
Clearing a Redo Log File _________________________________________________ 77
Viewing Redo Log Information_____________________________________________ 77
Managing Archived Redo Logs ________________________________________77
Obtaining Information about Archive Log ____________________________________ 77
Changing the Database Archiving Mode _____________________________________ 78
Specifying Archive Destinations and their Options _____________________________ 78
Specifying the Minimum Number of Successful Destinations _____________________ 79
Controlling Archiving to a Destination_______________________________________ 79
Controlling Trace Output Generated by the Archivelog Process ___________________ 79
Managing Tablespaces ______________________________________________79
Obtaining Tablespace Information__________________________________________ 79
Page 7 Oracle DBA Code Examples

Creating a Locally Managed Tablespace _____________________________________ 83
Specifying Segment Space Management_____________________________________ 83
Adding Space to Tablespace ______________________________________________ 83
Specifying Nonstandard Block Sizes for Tablespaces ___________________________ 83
Using Bigfile Tablespace (BFT) ____________________________________________ 83
Using Temporary Tablespace______________________________________________ 84
Renaming a Tempfile____________________________________________________ 84
Shrinking Temporary Tablespace __________________________________________ 84
Using Default Temporary Tablespace _______________________________________ 85
Using Temporary Tablespace Groups _______________________________________ 85
Suppressing Redo Generation for a Tablespace _______________________________ 85
Controlling Tablespaces Availability_________________________________________ 85
Using Read-Only Tablespaces _____________________________________________ 85
Renaming Tablespaces __________________________________________________ 85
Default Permanent Tabelspace ____________________________________________ 85
Dropping Tablespaces ___________________________________________________ 86
Managing the SYSAUX Tablespace _________________________________________ 86
Diagnosing and Repairing Locally Managed Tablespace Problems _________________ 86
Verifying the Integrity of Segments Created in ASSM Tablespaces. ________________ 86
Checking Consistency of Segment Extent Map with Tablespace File Bitmaps_________ 87
Verifying the Integrity of ASSM Tablespaces__________________________________ 88
Marking the Segment Corrupt or Valid ______________________________________ 89
Dropping a Corrupted Segment____________________________________________ 89
Dumping a Segment Header and Bitmap Blocks_______________________________ 90
Marking a DBA Range in Bitmap as Free or Used ______________________________ 90
Rebuilding the Appropriate Bitmap _________________________________________ 91
Rebuilding Quotas for Given Tablespace _____________________________________ 91
Migrating from a Dictionary-Managed to a Locally Managed Tablespace ____________ 91
Fixing the State of the Segments in A Tablespace _____________________________ 91
Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap) _____ 91
Scenario 2: Dropping a Corrupted Segment __________________________________ 92
Scenario 3: Fixing Bitmap Where Overlap is Reported __________________________ 92
Scenario 4: Correcting Media Corruption of Bitmap Blocks_______________________ 92
Transporting Tablespaces Between Databases ________________________________ 92
Managing Alert Thresholds __________________________________________94
Getting the Current Threshold Setting ______________________________________ 94
Setting Tablespace Alert Thresholds ________________________________________ 95
Restoring a Tablespace to Database Default Thresholds_________________________ 96
Page 8 Oracle DBA Code Examples

Modifying Database Default Thresholds _____________________________________ 97
Viewing Alerts _________________________________________________________ 97
Managing Datafiles and Tempfiles _____________________________________98
Creating Datafiles ______________________________________________________ 98
Enabling and Disabling Automatic Extension for a Datafile_______________________ 98
Manually Resizing a Datafile ______________________________________________ 98
Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode _________________ 98
Taking Datafiles Offline in NOARCHIVELOG Mode______________________________ 98
Renaming and Relocating Datafiles in a Single Tablespace_______________________ 99
Dropping Datafiles ______________________________________________________ 99
Copying a File on a Local File System_______________________________________ 99
Transferring a File to a Different Database __________________________________ 100
Dumping a Data Block__________________________________________________ 100
Managing Undo Tablespaces ________________________________________101
Obtaining Information on Undo___________________________________________ 101
Enabling Automatic Undo Management_____________________________________ 102
Creating an Undo Tablespace ____________________________________________ 102
Setting Startup Undo Tablespace _________________________________________ 102
Tuning Undo Retention _________________________________________________ 102
Using Undo Advisor ____________________________________________________ 103
Setting the Undo Retention Period ________________________________________ 103
Enabling Retention Guarantee____________________________________________ 103
Dropping an Undo Tablespace____________________________________________ 103
To Drop a Corrupt UNDO Tablespace ______________________________________ 104
Using Oracle Managed Files (OMF) ___________________________________104
Managing Schema Objects ______________________________ 106
Chaching Small Tables in Memory____________________________________106
Creating Virtual Columns___________________________________________106
Creating Partitioned Tables _________________________________________106
Partition Maintenance Operations ____________________________________111
Setting Deferred Segment Creation___________________________________112
Creating Multiple Tables and Views in a Single Operation__________________112
Collecting Object Statistics _________________________________________113
Collecting Index Statistics _______________________________________________ 113
Collecting Table Statistics _______________________________________________ 113
Page 9 Oracle DBA Code Examples

Collecting Schema Statistics _____________________________________________ 114
Validating Tables, Indexes, Clusters, and Materialized Views _______________115
Listing Chained and Migrated Rows of Tables and Clusters_________________115
Truncating Tables or Clusters _______________________________________116
Enabling and Disabling Triggers _____________________________________116
Managing Integrity Constraints ______________________________________116
Setting Constraint States and Deferability __________________________________ 116
Modifying, Renaming, or Dropping Existing Integrity Constraints ________________ 117
Reporting Constraint Exceptions __________________________________________ 117
Obtaining Information on Constraints ______________________________________ 118
Renaming Schema Objects _________________________________________118
Managing Object Dependencies______________________________________118
Manually Recompiling Views Procedures and Packages ________________________ 118
Switching to a Different Schema _____________________________________118
Using DBMS_METADATA to Display Information About Schema Objects ______118
Specifying Storage Parameters at Object Creation _______________________118
Managing Resumable Space Allocation ________________________________119
Enabling Resumable Space Allocation ______________________________________ 119
Detecting Suspended Statements _________________________________________ 119
Obtaining Information about Suspended Statements __________________________ 121
Reclaiming Wasted Space __________________________________________121
Displaying Information About Space Usage for Schema Objects _________________ 121
Segment Advisor ______________________________________________________ 124
Shrinking Database Segments Online ______________________________________ 126
Deallocating Unused Space ______________________________________________ 126
Capacity Planning for Database Objects _______________________________127
Estimating the Space Use of a Table_______________________________________ 127
Obtaining Object Growth Trends __________________________________________ 128
Using the SQL Access Advisor _______________________________________129
Estimating the Space Use of a Table_______________________________________ 129
Managing Tables______________________________________ 134
Obtaining Information about Tables __________________________________134
Creating Tables with some Options ___________________________________134
Page 10 Oracle DBA Code Examples

DML Error Logging ________________________________________________135
Enabling Direct-Path INSERT________________________________________135
Automatically Collecting Statistics on Tables____________________________136
Altering Tables___________________________________________________136
Performing Online Redefinition with DBMS_REDEFINITION ________________137
Redefining a Table_____________________________________________________ 137
Redefining a Single Partition _____________________________________________ 139
Migrating BasicFile LOBs to SecureFiles ____________________________________ 140
Using Flashback Drop and Managing the Recycle Bin _____________________141
Managing Index-Organized Tables ___________________________________141
Managing External Tables __________________________________________142
Managing Indexes ____________________________________ 145
Using Indexes ___________________________________________________145
Using Bitmap Join Indexes (BJI) _____________________________________146
Partitioned Indexes _______________________________________________147
Managing Materialized Views ____________________________ 148
Obtaining Information about Materialized Views______________________________ 148
Monitoring the Progress of a Materialized View Refresh ________________________ 148
Materialized View Typical Refresh Errors____________________________________ 152
Using Materialized Views ________________________________________________ 152
Using Query Rewriting__________________________________________________ 155
ReWrite Hints_________________________________________________________ 157
Using EXPLAIN_MVIEW Procedure: Viewing Materialized View Capabilities _________ 157
Using DBMS_ADVISOR.TUNE_MVIEW______________________________________ 157
Registering a User-defined Table as Materialized View_________________________ 158
Managing Clusters and Hash Clusters______________________ 159
Managing Views, Sequences, and Synonyms ________________ 161
Managing Transactions_________________________________ 162
Implementing Oracles Concurrency Control ____________________________162
Oracle Isolaction Levels_________________________________________________ 162
Oracle Lock Types _____________________________________________________ 162
Page 11 Oracle DBA Code Examples

Identifying Blocking Sessions ____________________________________________ 163
Using Autonomous Transaction ______________________________________163
Managing Long Transactions with Workspace Manager____________________164
Repairing Corrupted Data_______________________________ 172
Options for Repairing Data Block Corruption____________________________172
Detecting Corruptions Methods ______________________________________172
Using dbv (DBVerify) Utility_________________________________________172
Setting the Initialization Parameters for Detecting Corruption ______________172
Verifying Block Integrity in Real Time: DB_BLOCK_CHECKING __________________ 172
Verifying Block Integrity in Real Time: DB_BLOCK_CHECKSUM__________________ 173
Detecting lost write: DB_LOST_WRITE_PROTECT_____________________________ 173
Settubg the DB_ULTRA_SAFE Parameter (In Oracle 11g) ______________________ 173
Using ANALYZE Command__________________________________________173
Using EXP to Detect Corruption______________________________________173
Using DBMS_REPAIR ______________________________________________174
DBMS_REPAIR Limitations and Restrictions _________________________________ 174
Evaluate the Costs and Benefits of Using DBMS_REPAIR _______________________ 174
Detect and Report Corruptions using DBMS_REPAIR __________________________ 175
Managing Automated Database Maintenance Tasks___________ 177
Predefined Automated Maintenance Tasks _____________________________177
Predefined Maintenance Windows ____________________________________177
Obtaining Information about Predefined Maintenance Tasks________________177
Enabling and Disabling Maintenance Tasks _____________________________178
Configuring Maintenance Windows ___________________________________178
Managing Resources___________________________________ 180
Obtaining Information on Database Resource Manager ___________________191
Monitoring Oracle Database Resource Manager _________________________193
Using Oracle Scheduler_________________________________ 195
Using Jobs ______________________________________________________195
Using Programs __________________________________________________202
Page 12 Oracle DBA Code Examples

Using Schedules__________________________________________________203
Using Job Classes ________________________________________________204
Using Windows___________________________________________________205
Using Window Groups _____________________________________________206
Monitoring Job State with Email Notifications ___________________________207
Using File Watchers _______________________________________________209
Using Events Raised by the Scheduler_________________________________212
Using Events Raised by an Application (Events-Based Jobs)________________214
Using Chains ____________________________________________________217
Allocating Resources Among Jobs ____________________________________221
Administering Oracle Scheduler______________________________________221
Configuring Oracle Scheduler ____________________________________________ 221
Monitoring and Managing the Scheduler ____________________________________ 222
Enabling, Using and Disabling Remote External Jobs __________________________ 223
Import/Export and the Scheduler _________________________________________ 225
Scheduler Privileges____________________________________________________ 225
Scheduler Data Dictionary Views__________________________________________ 225
Using the UTL_FILE Package _____________________________________________ 226
Data Loading and Transforming Tools _____________________ 228
Using Database Links __________________________________ 229
Managing Diagnostic Data ______________________________ 230
Setting the Automatic Diagnostic Repository Directory____________________230
Using adrci Tool __________________________________________________230
General usage of adrci__________________________________________________ 230
Using adrci to Package Incidents__________________________________________ 231
Managing Database Health Monitor ___________________________________231
Managing Data Recovery Advisor ____________________________________233
Using SQL Test Case Builder ________________________________________233
Patching Oracle Products _______________________________ 235
Using Oracle Opatch ______________________________________________235
Page 13 Oracle DBA Code Examples

Part 2 Oracle Database Net Services ___________________ 238
Connectivity Naming Methods ___________________________ 239
The Local Naming Method __________________________________________239
The Easy Connect Naming Method ___________________________________239
The External Naming Method________________________________________239
The Directory Naming Method _______________________________________240
Database Resident Connection Pooling (DRCP) __________________________240
Oracle and Java Database Connectivity ____________________ 242
Establishing Database Connectivity___________________________________242
Miscellaneous Connectivity Options _______________________ 244
Setting the Default Connect String ___________________________________244
Installing the Instant Client _________________________________________244
Setting Listener Options ___________________________________________244
Setting Access Controls ____________________________________________244
Changing Windows Hostname _______________________________________245
Part 3 Oracle Database Backup and Recovery ____________ 247
Backup Guidelines ____________________________________ 248
Causes of Unplanned Down Time ____________________________________248
Causes of Planned Down Time_______________________________________248
Oracles Solution to Down Time______________________________________249
Minimizing Unplanned Downtime Guidelines ____________________________249
SLA Sample _____________________________________________________250
Planning a Backup Strategy Guidelines ________________________________250
Examples of Backup Schedules for a Database_______________ 251
User-Managed Backups ________________________________ 252
Obtaining Database File Information__________________________________252
Making Whole Closed Database Backups ___________________________________ 252
Making a Whole Open Backup ____________________________________________ 252
Page 14 Oracle DBA Code Examples

Making Tablespace Backups _____________________________________________ 253
Obtaining Backup Status Information _________________________________253
Checking Datafiles Taken as Backup _________________________________253
Handling Crash Before User-Manged Backup Ends _______________________253
Backing up Control File ____________________________________________254
Backing Up Initialization Files _______________________________________254
User-Managed Complete Recovery ________________________ 255
User-Managed Recovery in NOARCHIVELOG Mode _______________________255
User-Managed Recovery in NOARCHIVELOG Mode Without Redo Log File _____255
User-Managed Complete Recovery in ARCHIVELOG Mode _________________255
Re-Creating Lost Datafiles Without Backup_____________________________256
User-Managed Incomplete Recovery ______________________ 257
Common Situations Requiring Incomplete Recovery______________________257
User-Managed Incomplete Recovery Steps _____________________________257
Recovering from Lost Control File by Re-Creating the Control File ___________257
Flash Recovery Area ___________________________________ 261
Obtaining Information on Flash Recovery Area __________________________261
Configuring Flash Recovery Area_____________________________________261
Backing Up the Flash Recovery Area __________________________________261
Moving the Flash Recovery Area _____________________________________262
Recovery Manager (RMAN)______________________________ 263
Using A Media Management Layer (MML) with RMAN _____________________263
Obtaining Information about and related to RMAN using Dictionary Views_____263
Starting RMAN ___________________________________________________265
Using rlwrap Utility with RMAN in Unix-Based Systems____________________266
Configuring the RMAN Environment __________________________________266
RMAN Channel Commands _________________________________________267
Duration in days of RMAN information in Control File _____________________268
Monitoring RMAN Jobs _____________________________________________268
Page 15 Oracle DBA Code Examples

Using RMAN BACKUP Command _____________________________________268
Backing Up Control File and SPFile ___________________________________269
Backing Up Archived RedLogs _______________________________________269
Backup in NOARCHIVELOG Mode_____________________________________270
Encrypting RMAN Backups__________________________________________270
Using Compression in RMAN Backups _________________________________270
Using Multiplexed Backup Sets ______________________________________270
Using Parallelization of Backup Sets __________________________________270
Using Duplexed Backup Sets (Backupset Copies) ________________________271
Making Image Copies______________________________________________271
Validating Backup ________________________________________________272
Incremental Backup_______________________________________________272
Tags for Backups and Image Copies __________________________________272
Creating Archival Backups __________________________________________272
Monitoring RMAN Backups __________________________________________273
RMAN Complete Recovery _______________________________________273
Validating Backup Files _________________________________________________ 273
Previewing Backup Files Required by a Restore ______________________________ 274
Identifying Datafiles Requiring Recovery____________________________________ 274
Performing Complete Recovery ___________________________________________ 274
Restoring whole Database from RMAN Backups On a Different Node______________ 275
Restoring whole Database from RMAN Backups from A 32 bit to 64 bit ____________ 278
RMAN Incomplete Recovery_________________________________________278
Simplified Recovery Through Resetlogs________________________________279
Recovering from Lost Control File using RMAN __________________________279
Block Media Recovery (BMR) ________________________________________280
Trial Recovery ___________________________________________________280
Handling Specific Errors During Recovery ______________________________280
Configuring Instance Crash Recovery Time (MTTR) ______________________282
Working with the Data Recovery Advisor in RMAN _______________________282
RMAN Maintenance _______________________________________________282
Cross Checking Backups and Copies _______________________________________ 282
Page 16 Oracle DBA Code Examples

Deleting Backups and Copies ____________________________________________ 283
Changing the Availability of RMAN Backups and Copies ________________________ 283
Exempting a Backup or Copy from the Retention Policy ________________________ 283
The CATALOG Command ________________________________________________ 284
The CHANGE UNCATALOG Command ____________________________________ 284
RMAN Catalog ___________________________________________________284
Creating a Recovery Catalog _____________________________________________ 284
RMAN Catalog Reporting ________________________________________________ 285
Upgrading a Recovery Catalog ___________________________________________ 285
Importing Recovery Catalogs ____________________________________________ 285
Moving a Recovery Catalog ______________________________________________ 286
Dropping a Recovery Catalog ____________________________________________ 286
Virtual Private Catalogs ____________________________________________286
Using RMAN Scripts _______________________________________________287
Duplicating (Cloning) a Database_________________________ 289
Database Duplication (Cloning) Methods_______________________________289
Database Duplication Techniques ____________________________________289
Database Duplication Prerequisites ___________________________________289
Duplicating an Active Database using RMAN____________________________289
Duplicating a Database without Recovery Catalog or Target Connection ______291
Manually Duplicating a Database_____________________________________293
Using Oracle Flashback Technology _______________________ 297
Flashback Options ____________________________________ 298
Preparing Your Database for Flashback ____________________ 299
Using Row Level Flashback Options _______________________ 300
Flashback Query _________________________________________________300
Flashback Versions Query __________________________________________300
Flashback Transaction Query________________________________________301
Flashback Transaction (Backout)_____________________________________301
Using Table Level Flashback Options ______________________ 303
Page 17 Oracle DBA Code Examples

Flashback Table __________________________________________________303
Flashback Drop __________________________________________________303
Flashback Data Archive ____________________________________________304
Using Flashback Database ______________________________ 308
When to use Flashback Database ____________________________________308
Flashback Database Considerations___________________________________308
Using Flashback Database __________________________________________308
Restore Points ___________________________________________________309
Part 4 Oracle Database Security _______________________ 311
Oracle Database Security Management ____________________ 312
Security Guidelines____________________________________ 313
Managing Users ______________________________________ 315
Database Authentication _______________________________ 317
Managin Passwords _______________________________________________317
External (OS) Authentication________________________________________317
Proxy Authentication ______________________________________________318
Logging In As a Different User_______________________________________318
Killing User Sessions from OS _______________________________________318
Controlling Database Access_____________________________ 320
System and Object Privileges _______________________________________320
Invoker Rights and Definer Rights____________________________________320
Roles __________________________________________________________320
Users, Roles, and Privileges Views____________________________________321
Fine-Grained Data Access (Virtual Private Database VPD) _________________322
Auditing Database ____________________________________ 325
Standard Auditing ________________________________________________325
Customizing Database Auditing with Triggers ___________________________326
Page 18 Oracle DBA Code Examples

Auditing the Database Using System Trigger ___________________________328
Using Fine Grained Auditing_________________________________________331
Using Data Encryption _________________________________ 334
Oracle Transparent Data Encryption (TDE) _____________________________334
Tablespace Encryption_____________________________________________335
Fine-Grained Access Control for UTL_* Packages ____________ 337
Creating ACL ____________________________________________________337
Access Control Lists Maintenance ____________________________________338
Query Your Access Control List ______________________________________339
Part 5 Oracle Database Performance Tuning _____________ 340
Managing Performance Statistics _________________________ 341
Managing OS Statistics ____________________________________________341
Managing Database Statistics _______________________________________345
System and Session Statistics____________________________________________ 345
Time Model Statistics___________________________________________________ 346
Wait Events __________________________________________________________ 347
Active Session History (ASH)_____________________________________________ 349
Segment Statistics_____________________________________________________ 351
Handling Important Oracle Wait Events _______________________________351
List of Idle Waits Events ___________________________________________353
Using Performance Monitor Tool in Windows____________________________355
Using OS Watcher for Windows ______________________________________355
Optimizing Performance in Windows Server ________________ 357
Optimizing Performance in Windows Server 2003________________________357
Tuning the Database Instance ___________________________ 358
Tuning the Shared Pool ____________________________________________358
Tuning the Buffer Cache ___________________________________________359
Tuning PGA _____________________________________________________361
Dumping the PGA ________________________________________________361
Page 19 Oracle DBA Code Examples

Using Server Result Cache__________________________________________362
Obtaining Information about Object Locks _____________________________364
Handling a Hanging Database _______________________________________365
Accurately Measuring Process Size ___________________________________365
Managing Automatic Workload Repository (AWR) ____________ 367
Managing Automated Maintenance Tasks___________________ 369
Using Automatic Database Diagnostic Monitor (ADDM)____________________369
Using Automatic SQL Tuning Advisor _________________________________371
Implementing Automatic Memory Management______________ 374
Configuring DB_nK_CACHE_SIZE _________________________ 376
Managing Optimizer Operations __________________________ 377
Setting the Optimizer Mode_________________________________________377
Defining Access Paths and Joins for the Query Optimizer __________________377
Gathering Optimizer Statistics_______________________________________381
Gathering Object Statistics ______________________________________________ 381
Gathering System Statistics _____________________________________________ 382
Changing Statistics Preferences______________________________________382
Managing Pending and Published Statistics _____________________________383
Managing Extended Statistics _______________________________________384
MultiColumn Statistics __________________________________________________ 384
Expression Statistics ___________________________________________________ 385
A Simple Approach to Tuning SQL Statements _______________ 386
Using Application Tracing Tools __________________________ 387
Using the SQL Trace Facility and TKPROF ______________________________387
Using the Event 10046 to Trace SQL Code _____________________________387
Tracing End to End Application ______________________________________388
Enabling and Disabling Statistic Gathering for End to End Tracing ___________389
Page 20 Oracle DBA Code Examples

Writing Efficient SQL __________________________________ 391
Improving SQL Processing Techniques_____________________ 394
Using SQL Tuning Advisor_______________________________ 395
Part 6 Oracle Automatic Storage Management (ASM) ______ 396
Managing Oracle ASM__________________________________ 397
Obtaining Information about ASM Instance_____________________________397
Creating an ASM Instance __________________________________________397
Managing Disk Groups and Disks in ASM_______________________________398
Fundementals of Managing Disk Groups and Disks____________________________ 398
Managing Disk Groups Attributes _________________________________________ 399
Monitoring Long-Running Operations _________________________________401
Migrating a Database to ASM________________________________________402
Moving a Tablespace to ASM ________________________________________402
Accessing an ASM instance from DB Console ___________________________403
Managing ASM Files _______________________________________________404
Using ASMCMD Utility _____________________________________________405
Using SYSASM Privilege and OSASM Group_____________________________407
Manually Upgrading Oracle AS from 10g to 11g _________________________408
Verifying Manually ASM Device ______________________________________408
Part 7 Oracle Real Application Cluster __________________ 410
Oracle RAC Possible Installation Configurations _____________ 411
Installing Oracle 10g R2 RAC on Enterprise Linux 4___________ 412
Installation Environment ___________________________________________412
Required Software ________________________________________________412
Used Hardware __________________________________________________412
Installation Plan__________________________________________________412
1. Preinstallation tasks _________________________________________________ 413
2. Oracle Clusterware installation _________________________________________ 420
Page 21 Oracle DBA Code Examples

3. Oracle Database 10g Software Installation________________________________ 424
4. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software____________ 425
5. Install EM Agent in cluster nodes (if required) _____________________________ 426
6. Configure Listeners __________________________________________________ 426
7. Perform ASM installation ______________________________________________ 427
8. Perform cluster database creation ______________________________________ 427
9. Postinstallation tasks_________________________________________________ 429
10. Useful Postinstallation Tasks __________________________________________ 430
Installing Oracle 11g R2 RAC on Enterprise Linux 5___________ 431
Main Changes in Oracle 11g Release 2 RAC ____________________________431
Installation Environment ___________________________________________431
Required Software ________________________________________________431
Used Hardware __________________________________________________431
Installation Plan__________________________________________________432
1. Preinstallation tasks _________________________________________________ 433
2. Oracle Grid Infrastructure installation____________________________________ 440
3. Oracle Grid Infrastructure Patching______________________________________ 442
4. Oracle Database 11g R2 Software Installation _____________________________ 442
5. Oracle Database 11g R2 Software Patching _______________________________ 443
6. Install EM Agent in cluster nodes (if required) _____________________________ 443
7. ASM Diskgroups Creation _____________________________________________ 443
8. RAC Database Creation _______________________________________________ 444
9. Postinstallation tasks_________________________________________________ 445
10. General Useful Postinstallation Tasks in Linux ____________________________ 446
Installing Oracle 10g R2 RAC on Windows __________________ 447
Installation Methods ______________________________________________447
Installation Environment ___________________________________________447
Required Software ________________________________________________447
Used Virtual Hardware_____________________________________________447
Installation Plan__________________________________________________448
1. Preinstallation tasks _________________________________________________ 448
2. Oracle Clusterware installation _________________________________________ 450
3. Apply Patch Set 3 (10.2.0.4) on Clusterware software_______________________ 452
4. Oracle ASM 10g Software Installation____________________________________ 453
Page 22 Oracle DBA Code Examples

5. Apply Patchset 3 (10.2.0.4) on ASM Software _____________________________ 454
6. Install EM Agent in cluster nodes (if required) _____________________________ 454
7. Configure Listeners __________________________________________________ 454
8. Create ASM Instance_________________________________________________ 455
9. Install Oracle RAC Database Home Software ______________________________ 456
10. Apply Patchset 3 (10.2.0.4) on Oracle RAC Software Home__________________ 457
11. Perform cluster database creation _____________________________________ 457
12. Useful Postinstallation Steps __________________________________________ 459
Cleaning Up Clusterware Installation on Windows____________ 460
Single Instance to RAC Conversion________________________ 462
The Tools to Convert a Single Instance DB to RAC _______________________462
Conversion Prerequisites for Oracle 10g R2 ____________________________462
Using rconfig Utitlity ______________________________________________462
Using DBCA _____________________________________________________463
Administering RAC Database ____________________________ 465
Administering Oracle Clusterware Components ______________ 466
Managing Cluserware Daemons and Processes __________________________466
Displaying Clusterware Processes _________________________________________ 466
Starting, Stopping, Enabling and Disabling crs Stack __________________________ 466
CSS Parameters__________________________________________________466
Administering Voting Disks in RAC ___________________________________466
Multiplexing Voting Disks________________________________________________ 466
Dynamically Adding and Removing Voting Disks after Installing RAC _____________ 467
Backing up Voting Disks ________________________________________________ 467
Recovering Voting Disks ________________________________________________ 467
Administering the Oracle Cluster Registry (OCR) ________________________467
Replacing the OCR_____________________________________________________ 468
Adding and Removing the OCR ___________________________________________ 468
Repairing the OCR _____________________________________________________ 468
Making Physical Backups of the OCR_______________________________________ 468
Recovering the OCR using the Physical Backups______________________________ 469
Making Logical Backups of the OCR (Exporting) ______________________________ 469
Making Logical Backups of the OCR (Importing)______________________________ 469
Page 23 Oracle DBA Code Examples

Diagnosing OCR Problems with the OCRDUMP and OCRCHECK Utilities____________ 470
Administering Storage _________________________________ 471
Datafile Access in Real Application Clusters _________________________________ 471
Redo Log File Storage in Real Application Clusters ____________________________ 471
Automatic Undo Management in Real Application Clusters ______________________ 471
Administering ASM Instances with SRVCTL in RAC _______________________472
Administering Cluster Databases _________________________ 473
Displaying Current Instance in SQL*Plus Prompt ________________________473
Starting and Stopping Instances and RAC Databases _____________________473
Starting Up and Shutting Down with SQL*Plus _______________________________ 473
Intermittent Windows Shutdown Issue in RAC Environments____________________ 473
Starting Up and Shutting Down with SRVCTL ________________________________ 473
Customizing How Oracle Clusterware Manages RAC Databases _____________474
Switching Between the Database Automatic and Manual Policies ____________474
Customizing Resource Parameters (like AUTO_START)____________________474
Handling Initialization Parameter Files in RAC___________________________475
Setting Server Parameter File Parameter Values for Real Application Clusters ______ 475
Parameters Used in RAC Databases _______________________________________ 475
Parameters that Must Have Identical Settings on All Instances __________________ 475
Parameters That Must Have Unique Settings on All Instances ___________________ 476
Parameters that Should Have Identical Settings on All Instances ________________ 476
ASM Instance Initialization Parameters and RAC _____________________________ 476
Dropping a RAC Database __________________________________________476
Workload Management in RAC ___________________________ 477
Types of Workload Distribution ______________________________________477
Connection Load Balancing _________________________________________477
Client-Side Load Balancing and Failover ____________________________________ 477
Server-Side Load Balancing______________________________________________ 477
Fast Application Notification (FAN) ___________________________________478
Using Fast Application Notification Callouts_____________________________478
Configuring the Server-Side ONS ____________________________________480
Administering Load Balancing Advisory________________________________480
Page 24 Oracle DBA Code Examples

Monitoring Load Balancing Advisory __________________________________481
Transparent Application Failover (TAF) ________________________________482
TAF Basic Configuration without FAN (From Client Side) _______________________ 482
TAF Basic Configuration with FAN (Server-Side)______________________________ 482
TAF Preconnect Configuration ____________________________________________ 482
Verifying TAF Configuration______________________________________________ 483
Enabling Distributed Transaction Processing for Services __________________483
Administering Services_________________________________ 484
Service Attributes ________________________________________________484
Administering Services with DBCA____________________________________484
Administering Services with PL/SQL __________________________________484
Administering Services with SRVCTL __________________________________486
Controlling the Preferred and Available Instances________________________486
Using Services with Client Applications ________________________________487
Services and the Scheduler _________________________________________487
Measuring Performance by Service Using the AWR_______________________488
Service Thresholds and Alerts _______________________________________490
Service Performance Views _________________________________________491
Restricted Session and Services _____________________________________491
Configuring Recovery Manager and Archiving _______________ 492
Backup Possible Distributions in RAC__________________________________492
RMAN Restore Scenarios for Real Application Clusters ____________________492
Cluster File System Restore Scheme_______________________________________ 492
Non-Cluster File System Restore Scheme ___________________________________ 492
RMAN and Oracle Net in Real Application Clusters _______________________492
Connecting to Specific Node ________________________________________492
Instance Recovery in Real Application Clusters __________________________493
Single Node Failure in Real Application Clusters ______________________________ 493
Multiple-Node Failures in Real Application Clusters____________________________ 493
Configuring the RMAN Snapshot Control File Location ____________________493
Configuring the RMAN Control File and SPFILE Autobackup Feature__________493
Page 25 Oracle DBA Code Examples

Configuring Channels for RMAN in Real Application Clusters________________493
Configuring Channels to use Automatic Workload Balancing ____________________ 493
Configuring Channels to Use a Specific Instance _____________________________ 493
Node Affinity Awareness of Fast Connections ___________________________494
Archived Redo Log File Conventions in RAC ____________________________494
Archive Redo Log Configuration Scenarios _____________________________494
Automatic Storage Management and CFS Archiving Scheme ____________________ 494
Non-Cluster File System Local Archiving Scheme _____________________________ 494
Changing the Archiving Mode in Real Application Clusters _________________495
Deleting Archived Redo Logs after a Successful Backup ___________________495
Monitoring the Archiver Processes____________________________________495
Log_Archive_Dest_1 Set To Default Even When DB_Recovery_File_Dest Is Set
(Bug 6373164) __________________________________________________495
Media Recovery in Real Application Clusters ____________________________497
Parallel Recovery in Real Application Clusters ___________________________497
Using a Flash Recovery Area in RAC __________________________________497
Managing Backup and Recovery __________________________ 498
Administrative Options_________________________________ 499
Using Enterprise Manager Grid Control to Discover Nodes and Instances______499
Additional Information About SQL*Plus in RAC __________________________499
How SQL*Plus Commands Affect Instances _________________________________ 499
Displaying Running Instances ____________________________________________ 499
Displaying Connect Identifier_____________________________________________ 499
Quiescing RAC Databases __________________________________________500
Quiesced State and Cold Backups _________________________________________ 500
Transparent Data Encryption and Wallets in RAC ________________________500
Administering System and Network Interfaces with oifcfg _________________500
Defining Network Interfaces with oifcfg ____________________________________ 500
Syntax and Commands for the oifcfg Command-Line Tool ______________________ 500
Changing Public or Interconnect IP Subnet Configuration__________________501
Changing VIP Addresses ___________________________________________501
Adding Nodes and Instances on UNIX-Based Systems_________ 503
Page 26 Oracle DBA Code Examples

Adding Nodes to a RAC Environment__________________________________503
Cloning Oracle Clusterware and RAC Software in Grid Environments _________503
Quick-Start Node and Instance Addition Procedures______________________504
Adding an Oracle Clusterware Home to a New Node __________________________ 504
Adding an Oracle Home with RAC to a New Node_____________________________ 505
Detailed Node and Instance Addition Procedure _________________________505
Step 1: Connecting New Nodes to the Cluster___________________________505
Step 2: Extending Clusterware and Oracle Software to New Nodes __________505
Step 3: Preparing Storage on New Nodes ______________________________505
Step 4: Adding Nodes at the Oracle RAC Database Layer__________________506
Step 5: Adding Database Instances to New Nodes _______________________506
Deleting Nodes and Instances on UNIX-Based Systems________ 507
Option 1: Quick-Start Node and Instance Deletion Procedures______________507
Deleting an Oracle Home with RAC from an Existing Node______________________ 507
Deleting an Oracle Clusterware Home from an Existing Node ___________________ 508
Option 2: Detailed Node and Instance Deletion Procedure _________________509
Step 1: Deleting DB Instances from Real Application Clusters Databases _____509
Using Enterprise Manager to Delete Database Instances from Existing Nodes_______ 509
Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes__ 509
Using DBCA in Silent Mode to Delete Instance from Existing Nodes_______________ 510
Step 2: Deleting Nodes from Real Application Clusters Databases ___________510
ASM Instance Clean-Up Procedures for Node Deletion ____________________511
Adding and Deleting Nodes and Instances on Windows-Based
Systems ____________________________________________ 512
Cloning Oracle Clusterware and RAC Software in Grid Environments _________513
Quick-Start Node and Database Instance Addition and Deletion Procedures ___513
Adding an Oracle Clusterware Home to a New Node __________________________ 513
Adding an Oracle Home with RAC to a New Node_____________________________ 513
Deleting an Oracle Home with RAC from an Existing Node______________________ 513
Deleting an Oracle Clusterware Home from an Existing Node ___________________ 513
Detailed Node and Database Instance Addition and Deletion Procedures ______513
Overview of Node Addition Procedures ________________________________513
Page 27 Oracle DBA Code Examples

Step 1: Connecting New Nodes to the Cluster___________________________513
Making Physical Connections_____________________________________________ 513
Installing the Operating System __________________________________________ 513
Verifying the Installation with the Cluster Verification Utility ____________________ 513
Checking the Installation________________________________________________ 513
Step 2: Extending Oracle Software to New Nodes at the Oracle Clusterware___513
Step 3: Preparing Storage on New Nodes ______________________________513
Raw Device Storage Preparation for New Nodes______________________________ 513
Step 4: Adding Nodes at the Oracle RAC Database Layer__________________513
Step 5: Adding Database Instances to New Nodes _______________________513
Using Enterprise Manager to Add Database Instances to New Nodes______________ 513
Using DBCA in Interactive Mode to Add Database Instances to New Nodes_________ 513
Using DBCA in Silent Mode to Add Database Instances to New Nodes _____________ 513
Connecting to iSQL*Plus after Adding a Node________________________________ 513
Adding Nodes that Already Have Clusterware and Oracle Software to a Cluster 514
Overview of Node Deletion Procedures ________________________________514
Step 1: Deleting Instances from Real Application Clusters Databases ________514
Using Enterprise Manager to Delete Database Instances from Existing Nodes_______ 514
Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes__ 514
Using DBCA in Silent Mode to Delete Instance from Existing Nodes_______________ 514
Step 2: Deleting Nodes from Real Application Clusters Databases ___________514
Step 3: ASM Instance Clean-Up Procedures for Node Deletion______________514
Monitoring Performance________________________________ 515
RAC Common Tuning Tips __________________________________________515
Instance Recovery and RAC_________________________________________515
Global Cache Wait Events __________________________________________515
Monitoring Performance in Enterprise Manager__________________________516
Using the Cluster Database Performance Page _______________________________ 516
Using the Cluster Database Instance Performance Page________________________ 516
Using the Cluster Performance Page _______________________________________ 517
Using the Cluster Interconnects Page ______________________________________ 517
Making Applications Highly Available Using Oracle Clusterware _ 518
Making an Application Highly Available Examples ________________________518
Page 28 Oracle DBA Code Examples

Example1: Making an Application Highly Available ____________________________ 518
Example2: Making an Application Highly Available ____________________________ 520
Managing Automatic Oracle Clusterware Resource Operations for Action Scripts ____ 522
Displaying Clusterware Application and Application Resource Status Information ____ 522
Unregistering Applications and Application Resources _________________________ 523
RAC Troubleshooting __________________________________ 524
Diagnosing the Oracle Clusterware High Availability Components ___________524
Debugging Recommnedation_____________________________________________ 524
Clusterware Log Files and the Unified Log Directory Structure___________________ 524
Dynamic Debugging____________________________________________________ 524
Component Level Debugging_____________________________________________ 524
Oracle Clusterware Shutdown and Startup __________________________________ 525
Enabling and Disabling Oracle Clusterware Daemons __________________________ 525
Diagnostics Collection Script _____________________________________________ 525
The Oracle Clusterware Alerts ____________________________________________ 525
Resource Debugging ___________________________________________________ 525
Checking the Health of the Clusterware ____________________________________ 525
Troubleshooting the Oracle Cluster Registry _________________________________ 525
Troubleshooting Hostname Changes and CSS________________________________ 525
Enabling Additional Tracing for Real Application Clusters High Availability__________ 526
Diagnosing Oracle Real Application Clusters Components ______________________ 526
Where to Find Files for Analyzing Errors ____________________________________ 526
Using Instance-Specific Alert Files in Real Application Clusters __________________ 526
Enabling Tracing for Java-Based Tools and Utilities in Real Application Clusters _____ 526
Resolving Pending Shutdown Issues _______________________________________ 526
Using the Cluster Verification Utility __________________________________526
Cluster Verify Locations_________________________________________________ 526
Cluster Verify Stages ___________________________________________________ 526
Cluster Verify Components ______________________________________________ 527
CVU Component Verification Examples _____________________________________ 527
Understanding CVU Commands, Help, Output, and Nodelist Shortcuts ____________ 528
Performing Various CVU Tests____________________________________________ 528
Known Issues for the Cluster Verification Utility ______________________________ 528
Part 8 Oracle RAC One Node __________________________ 529
Installing Oracle 11g R2 RAC One Node on Linux 5 ___________ 530
Page 29 Oracle DBA Code Examples

Installation Environment ___________________________________________530
Required Software ________________________________________________530
Used Hardware __________________________________________________530
Installation Plan__________________________________________________531
1. Preinstallation tasks _________________________________________________ 532
2. Oracle Grid Infrastructure installation____________________________________ 539
3. Oracle Grid Infrastructure Patching______________________________________ 542
4. Checking Oracle Grid Infrastructure Status _______________________________ 542
5. Oracle Database 11g R2 Software Installation _____________________________ 542
6. Oracle Database 11g R2 Software Patching _______________________________ 543
7. Install EM Agent in cluster nodes (if required) _____________________________ 544
8. ASM Diskgroups Creation _____________________________________________ 544
9. RAC Database Creation _______________________________________________ 545
10. Initialize the Database to RAC One Node (11.2.0.1 Only) ___________________ 547
11. Postinstallation tasks________________________________________________ 548
12. General Useful Postinstallation Tasks in Linux ____________________________ 548
Instance Relocation using Omotion (11.2.0.1)_______________ 549
Instance Relocation using Omotion (11.2.0.2)_______________ 550
Part 9 Oracle Warehousing___________________________ 551
Oracle Warehouse Builder (OWB) ________________________ 552
Oracle Warehouse Builder Architecture ________________________________552
Starting and Stoping the Service_____________________________________552
Configuring the Repository and Workspaces ____________________________552
Steps of Using Warehouse Builder____________________________________553
Mapping Operators _______________________________________________554
Part 10 Oracle Database Utilities _______________________ 556
Using SQL*Plus_______________________________________ 557
Using SQL*Plus Command-Line Options _______________________________557
Starting SQL*Plus Session__________________________________________557
Controlling User Privileges in SQL*Plus ________________________________557
Page 30 Oracle DBA Code Examples

Setting the SQL*Plus Environment with the SET Command ________________558
Setting SQL*Plus Preferances _______________________________________558
Logging SQL*Plus Errors ___________________________________________559
Key SQL*Plus "Working" Commands__________________________________559
Creating Command Files in SQL*Plus _________________________________559
Copying Tables with the COPY Command ______________________________559
Creating Web Pages Using SQL*Plus__________________________________560
Using SQL to Generate SQL_________________________________________560
Enabling AUTOTRACE for a User _____________________________________560
Using rlwrap Utility with SQL*Plus in Unix-Based Systems _________________561
Escaping Special Characters ________________________________________561
Using SQL*Loader Utility _______________________________ 563
Invoking SQL*Loader______________________________________________563
Using SQL*Loader Control File ______________________________________563
Loading Excel File into a Table using SQL*Loader________________________569
Loading Large Fields into a Table ____________________________________569
Using Direct Load Options __________________________________________570
Data Pump Export and Import ___________________________ 571
Data Pump Components ___________________________________________571
Data Pump Export Interfaces________________________________________571
Export Modes Parameters __________________________________________571
Required Rrivileges _______________________________________________571
Invoking Export Data Pump Examples_________________________________571
Export Filtering Parameters _________________________________________572
Export Remapping Parameters ______________________________________572
Sampling Export Data _____________________________________________573
Export Encryption Parameters _______________________________________573
Export Estimating Parameters _______________________________________573
Export Network Link Parameter______________________________________573
Export PARALELL Parameter ________________________________________574
Page 31 Oracle DBA Code Examples

Import Modes Parameters __________________________________________574
File- and Directory-Related Parameters________________________________574
Using TABLE_EXISTS_ACTION Parameter ______________________________574
Import Filtering Parameters_________________________________________574
Import Remapping Parameters ______________________________________574
Ignoring Nondeferred Constraints ____________________________________575
Import Network Link Parameter _____________________________________575
Import Flashback Parameters _______________________________________575
Import PARALELL Parameter ________________________________________576
Monitoring a Data Pump Jobs _______________________________________576
LogMiner____________________________________________ 577
Types of Supplemental Logging______________________________________577
Levels of Supplemental Logging _____________________________________577
Disabling Database-Level Supplemental Logging ________________________577
LogMiner Dictionary Options ________________________________________578
Redo Log File Options _____________________________________________578
OPTIONS possible values in DBMS_LOGMNR.START_LOGMNR: _____________578
Obtaining LogMiner Operational Information____________________________578
Examples of Using LogMiner ________________________________________579
Without Sepecifying the Redo Files ________________________________________ 579
Wit Sepecifying the Redo Files ___________________________________________ 580
Part 11 Miscellaneous Oracle Database Topics _____________ 582
Managing Oracle Database Control________________________ 583
Configuring and Using the Database Control ____________________________583
Implementing EM Database Control Auto Startup________________________583
Dropping and Recreating the Management Repository ____________________584
Installing Oracle 10g R5 (10.2) Enterprise Manager Grid Control for
Linux x86 ___________________________________________ 585
Installation Environment ___________________________________________585
Page 32 Oracle DBA Code Examples

Required Software ________________________________________________585
Used Hardware __________________________________________________585
Installation Steps_________________________________________________585
Remote Diagnostic Agent (RDA)__________________________ 593
Using Remote Diagnostic Agent (RDA) ________________________________593
Connect Oracle to SQL Server____________________________ 594
Configuring and Using the Database Control ____________________________594
Part 12 PL/SQL Samples ______________________________ 596
PL/SQL Basics _______________________________________ 597
PL/SQL Data Types _______________________________________________597
Controlling Compile-Time Displayed Warnings __________________________598
Catching Returned Errors __________________________________________599
Hiding Code _____________________________________________________599
Controlling Program Flow___________________________________________599
Using Cursors ________________________________________ 602
Using Records________________________________________ 606
Using Table Functions__________________________________ 608
Using Collections _____________________________________ 610
Using VARRAYS __________________________________________________610
Using Nested Tables ______________________________________________613
Using Associative Arrays ___________________________________________614
Using Collection API_______________________________________________616
Handling Errors_______________________________________ 621
Predefined Exceptions _____________________________________________621
Using User-Defined Exceptions ______________________________________621
Using RAISE_APPLICATION_ERROR __________________________________622
Page 33 Oracle DBA Code Examples

Autonomous Transactions ______________________________ 624
Some Stored Subprobrams Concepts ______________________ 625
Serially Reusable Packages _________________________________________625
Stored Subprograms and Roles ______________________________________626
Invokers vs. Definers Rights _______________________________________626
Pinning an Programunit in the Shared Pool _____________________________627
Using Triggers _______________________________________ 628
Restrictions on Triggers_________________________________________________ 628
Using DML Triggers _______________________________________________628
Using Instead-of Triggers __________________________________________629
Using System Triggers_____________________________________________630
Handling Mutating Tables in Triggers _________________________________634
Dropping and Disabling Triggers _____________________________________635
Using Dynamic SQL____________________________________ 636
Working with Native Dynamic SQL ___________________________________636
Using DBMS_SQL_________________________________________________639
Calling Java from PL/SQL _______________________________ 648
Configuring Oracle Database to Use External Routines ________ 649
Using Large Objects (LOBs) _____________________________ 652
Creating LOB ____________________________________________________652
Using SQL with Internal LOBs _______________________________________652
Using LOBs in PL/SQL _____________________________________________653
Performance Considerations ________________________________________662
Using Returning Clause _________________________________________________ 662
Using CONTEXT Index __________________________________________________ 663
Migrating from LONGs to LOBs ______________________________________664
PL/SQL Performance Tuning Tips_________________________ 665
Use PL/SQL Profiler _______________________________________________665
Page 34 Oracle DBA Code Examples

Use BULK COLLECT Clause _________________________________________666
Set PLSQL_OPTIMIZE_LEVEL and Subprogram Inlining ___________________670
Using Bind variables in Dynamic SQL _________________________________671
Use NOCOPY Keyword _____________________________________________672
Use Associative arrays_____________________________________________672
Use Server Result Cache ___________________________________________672
PL/SQL Miscellaneous Topics ____________________________ 673
Accessing V$ Views from PL/SQL_____________________________________673
Part 13 Appendixes__________________________________ 674
Program Units and Scripts Used in the Document ____________ 675
Return Parameter Value for Normal User ______________________________675
Applying Random Load on Database Sample 1 __________________________676
Setup _______________________________________________________________ 676
Using the Load Generator Scripts _________________________________________ 682
Applying Random Load on Database Sample 2 __________________________683
Setup _______________________________________________________________ 683
Using the Load Generator Scripts _________________________________________ 691
SQL Usage Samples ___________________________________ 693
Merge Command _________________________________________________693
Multitable Inserts_________________________________________________693
Parallel Insert ___________________________________________________694
Deleting Duplicate Rows in a Table ___________________________________694
Adding a Primary Key to a Table and then Filling it_______________________694
More DBA Scripts _____________________________________ 696
Compare Table Sizes in Two Databases _______________________________696
Using Linux for Oracle _________________________________ 697
Verifying the Kernel _______________________________________________697
Checking for a Tainted Kernel _______________________________________697
Page 35 Oracle DBA Code Examples

Supported Hardware ______________________________________________697
Using Oracle Relink Utility __________________________________________697
Certified and Supported File Systems _________________________________698
Enterprise Linux Runlevels__________________________________________698
Using /etc/oratab File and dbstart Utility_______________________________698
Automating Jobs _________________________________________________699
Using cron ___________________________________________________________ 699
Using anacron ________________________________________________________ 700
Using at command_____________________________________________________ 700
Using batch command __________________________________________________ 701
Task Scheduler _______________________________________________________ 701
Configuring Linux Memory for Oracle ______________________________________ 701
Using Linux Performance Monitoring Tools _____________________________701
About Linux Tools _____________________________________________________ 702
Using Linux Tools______________________________________________________ 702
Checking Some General Guideline on Truning Oracle in Linux ______________703
Troubleshooting Oracle Database in Linux _____________________________704
Using OS Watcher (OSW) _______________________________________________ 704
Using OS Watcher Graphs(OSWg)_________________________________________ 706
Using the On-Board Monitor (LTOM) _______________________________________ 706
Using strace__________________________________________________________ 707

Page 36 Oracle DBA Code Examples

Part 1 Oracle DBA Fundamentals
Page 37 Oracle DBA Code Examples

DBA: Best Practices
DBA: Best Practice Guidelines for Standalone and RAC Databases
Use SPFILE
Use temporary tablespaces
Register all instances with remote listeners
Use Database Resource Manager
Use resumable space allocation
Use Automatic Segment Space Management
Use locally managed tablespaces
Use Automatic Undo Management
Enable block checking
Enable Flashback Database
Enable ARCHIVELOG mode and use a flash recovery area
Use auto-tune checkpointing
Log checkpoints to the alert log
Multiplex production and standby redo logs
Set CONTROL_FILE_RECORD_KEEP_TIME long enough
Create two or more control files
Page 38 Oracle DBA Code Examples

Oracle Database Installation Consideration
Estimating Disk and Memoery Requirements
Make sure the storage vendor is listed in the Oracle Storage Compatibility Program
(OSCP).
Allocate swap space that is about two to three times your Oracle RAM allocation.
On Estimating the RAM:
o OS RAM: 20 percent of total RAM for MS-Windows, 10% of RAM for UNIX
o Each Oracle connection consumes two megabytes of RAM + sort_area_size +
hash_area_size
o If dynamic memory sizing is not used:
Shared_pool_size: If all the SQL statements that sent to ORACLE are using bind
variable adequately, then 300M is enough in most cases
Large_pool_size: For dedicated Oracle server: 20-30M
Java_pool_size=10M
Data buffer: All the rest RAM should be allocated to Data buffer.
Optimal Flexible Architecture
The OFA is a set of recommendations from Oracle Corporation aimed at simplifying
management of complex software and databases often running under multiple versions of
software.
OFA Guidelines
o Arrange at least four mount points that have names like /u01, /u02, /u03, and so
on.
o If the Oracle software owner is "oracle", make /u01/app/oracle your ORACLE_BASE
# mkdi r - p / u01/ app/ or acl e
# chown - R or acl e: oi nst al l / u01/ app/ or acl e
# chmod - R 775 / u01/ app/ or acl e
o Make Oracle_HOME $ORACLE_BASE/product/version/{db|client|companion}_[n].
Examples:
/ u01/ app/ or acl e/ pr oduct / 11. 1. 0/ db_1
/ u01/ app/ or acl e/ pr oduct / 11. 1. 0/ cl i ent _1
/ u01/ app/ or acl e/ pr oduct / 10. 1. 0. 2. 0/ db_1
o Install Flash Recovery Area in $ORACLE_BASE/flash_recovery_area in a mount point
different from db files.
o Administrative Files are to be created in ORACLE_BASE/admin/dbname
o Store Oracle DB files in the mounted points.
# mkdi r / mount _poi nt / or adat a
# chown or acl e: oi nst al l / mount _poi nt / or adat a
# chmod 775 / mount _poi nt / or adat a
/ u01/ or adat a/ pr od1/ cont r ol 01. ct l
/ u05/ or adat a/ pr od1/ cont r ol 02. ct l
/ u02/ or adat a/ pr od1/ r edo01. l og
/ u04/ or adat a/ pr od1/ r edo02. l og
data file has this format:
/ u20/ or adat a/ pr od/ syst em01. dbf
Page 39 Oracle DBA Code Examples

Oracle Products Installed with the 11.1 Release
The following products are installed by default with database server 11g:
o Oracle Application Express
o Oracle Warehouse Builder
o Oracle Configuration Manager: Tool that collects and uploads configuration
information to the Oracle configuration repository
o Oracle SQL Developer
o Oracle Database Vault: Tool that enables you to secure business data

Page 40 Oracle DBA Code Examples

Installing Oracle 10g R2 on Enterprise Linux 4
Installation Environment
Emulation software: VMWare Server 2 on for Windows
OS: Oracle Linux Enterprise 4.5 for x86: kernel 2.6.9
Required Software
Oracle Database 10g Release 2 for Linux x86 32-bit
Used Hardware
In the VMWare: create one virtual machine (or adb1) with the following specs:
o 2 GB RAM
o an ethernet card
o one local hardisk with 20 GB
Installation Plan
1. Preinstallation tasks:
o Hardware requirements
o Software requirements
o Environment configuration
2. Oracle Database 10g Software Installation
3. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software
4. Configure Listeners
5. Create Database
6. Postinstallation tasks

1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Give the ethernet card IP 192. 168. 4. 21 and the hostname or adb1. mydomai n. com.
Define a gateway. If it does not exist, make it same as the host IP address.
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Page 41 Oracle DBA Code Examples

Desktop
o X Window System
o Gnome
Applications
o Graphical Internet (optional)
Servers
o Do not select anything in this group.
Development
o Development Tools
System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
Miscellaneous
o Do not select anything in this group.
Complete the installation
Install further packages:
# to know distribution and version of Linux
cat /etc/issue
# t o know ker nel ver si on ( and i t s er r at a l evel )
uname - r

# f r omCD 3
r pm- Uvh l i bai o*
r pm- Uvh openmot i f 21- 2. 1. 30- 11. RHEL4. 6. i 386. r pm
r pm- Uvh openmot i f - 2. 2. 3- 10. 1. el 4. i 386. r pm

# t hose packages downl oaded f r omht t p: / / r pm. pbone. net
r pm- e compat - l i bst dc++- 296- 2. 96- 132. 7. 2
r pm- Uvh compat - l i bst dc++- 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - l i bst dc++- devel - 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - gcc- 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - gcc- c++- 7. 3- 2. 96. 128. i 386. r pm

# conf i r mt he r equi r ed packages ar e i nst al l ed:
r pm- qa| gr ep gcc-
r pm- qa| gr ep gl i bc-
r pm- qa| gr ep compat - db-
r pm- qa| gr ep compat - gcc-
r pm- qa| gr ep compat - gcc- c++-
r pm- qa| gr ep compat - l i bst dc++-
r pm- qa| gr ep compat - l i bst dc++- devel -
r pm- qa| gr ep cont r ol - cent er - 2. 8. 0
r pm- qa| gr ep openmot i f 21-
r pm- qa| gr ep set ar ch-

# SELI NUX must be di sabl ed
Page 42 Oracle DBA Code Examples

cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Check the hardware requirements
# Har dwar e Requi r ement s
# At l east 2 GB of physi cal memor y
gr ep MemTot al / pr oc/ memi nf o

# swap space: t wi ce t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o
# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 400 MB di sk space i n / t mp
df - k / t mp
# 4 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
df - h / dev/ shm/
# t o adj ust t he shar ed memor y f i l e syst emsi ze:
umount t mpf s
mount - t t mpf s shmf s - o si ze=1200m/ dev/ shm
Create the required network configuration:
# Net wor k names Resol ut i on
# conf i gur e / et c/ host s i f no domai n ser ver i s used
cat / et c/ host s
127. 0. 0. 1 l ocal host . l ocal domai n or adb1. mydomai n. com l ocal host
or adb1
Create and configure the required OS users and groups
# i nvent or y gr oup
gr oupadd - g 501 oi nst al l
gr oupadd - g 502 dba
# or acl e sof t war e owner user
/ usr / sbi n/ user add - u 200 - g oi nst al l - G dba or acl e
passwd or acl e
# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody

# The or acl e User Envi r onment
# i n / home/ or acl e/ . bash_pr of i l e
# expor t DI SPLAY i f r equi r ed
expor t ORACLE_BASE=/ u01/ app/ or acl e
i f [ $USER = " or acl e" ] ; t hen
Page 43 Oracle DBA Code Examples

i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i
expor t EDI TOR=vi
expor t ORACLE_HOME=$ORACLE_BASE/ pr oduct / 10. 2. 0/ db_1
expor t ORACLE_PATH=$ORACLE_BASE/ common/ or acl e/ sql : . : $ORACLE_HOME/ r dbms/ admi n
expor t ORACLE_SI D=or a10g
expor t NLS_LANG=AMERI CAN_AMERI CA. WE8I SO8859P1
expor t NLS_DATE_FORMAT=" mm/ dd/ yyyy hh24: mi : ss"
expor t PATH=. : ${PATH}: $HOME/ bi n: $ORACLE_HOME/ bi n: $ORA_CRS_HOME/ bi n
expor t PATH=${PATH}: / usr / bi n: / bi n: / usr / bi n/ X11: / usr / l ocal / bi n
expor t PATH=${PATH}: $ORACLE_BASE/ common/ or acl e/ bi n
expor t ORACLE_TERM=xt er m
expor t TNS_ADMI N=$ORACLE_HOME/ net wor k/ admi n
expor t ORA_NLS10=$ORACLE_HOME/ nl s/ dat a
expor t LD_LI BRARY_PATH=$ORACLE_HOME/ l i b
expor t LD_LI BRARY_PATH=${LD_LI BRARY_PATH}: $ORACLE_HOME/ or acm/ l i b
expor t LD_LI BRARY_PATH=${LD_LI BRARY_PATH}: / l i b: / usr / l i b: / usr / l ocal / l i b
expor t CLASSPATH=$ORACLE_HOME/ J RE
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ j l i b
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ r dbms/ j l i b
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ net wor k/ j l i b
expor t THREADS_FLAG=nat i ve
expor t TEMP=/ t mp
expor t TMPDI R=/ t mp

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf
or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536
or acl e sof t meml ock 3145728
or acl e har d meml ock 3145728
Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start, then
you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Conf i gur i ng ker nel par amet er s and shel l l i mi t s
# t hey can be t uned f or a pr oduct i on db
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf
ker nel . sem= 250 32000 100 128
# maxi mumsi ze may be gi ven t o SGA ( max 4GB)
# ker nel . shmmax = 536870912 ( 512 M)
# f ol l owi ng i s 1 GB
ker nel . shmmax =1073741824
net . i pv4. i p_l ocal _por t _r ange = 1024 65000
net . cor e. r mem_def aul t = 4194304
net . cor e. r mem_max = 4194304
Page 44 Oracle DBA Code Examples

net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 262144
# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p
Configure hangcheck-timer kernel module:
# check hangcheck- t i mer Modul e Conf i gur at i on
# wi t h t hi s modul e, i f t he ker nel hangs, t he machi ne wi l l r eboot
# ver i f y t he modul e i s l oaded
/ sbi n/ l smod | gr ep - i hang

# i f not l oaded, l oad i t
vi / et c/ modpr obe. conf
opt i ons hangcheck- t i mer hangcheck_t i ck=30 hangcheck_mar gi n=180
# execut e and add i n t he f i l e
vi / et c/ r c. l ocal
/ sbi n/ modpr obe hangcheck- t i mer
Create the required directories for the Oracle database software:
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

# i n t he exampl e above, / u01 shoul d be owned by t he r oot user
# and wr i t abl e by gr oup oi nst al l
cd /
chown - R or acl e: oi nst al l / u01
chmod - R 775 / u01/ or acl e
mkdi r - p / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
mkdi r / u01/ st age
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ or acl e
chown or acl e: oi nst al l / u01/ st age
As oracle, copy software installation into /u01/stage10g/db
Disable screensavers on host & guest machines.
o In Oracle Linux: Applications-> Preferences-> Screen Saver-> Mode: Disable Screen
Saver
o Do the same after logging off and logging on again as oracle user.
Restart the machine.
2. Oracle Database 10g Software Installation
- - st ar t OUI
su - or acl e
cd / u01/ st age10g/ db
. / r unI nst al l er

Fol l ow t he st eps.
I nst al l dat abase sof t war e onl y.
3. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software
# ext r act 10g Rel ease 2 ( 10. 2. 0. 4) Pat ch Set 3 f or Li nux x86 t o
Page 45 Oracle DBA Code Examples

/ u01/ st age10g/ pat ch10. 2. 0. 4/ Di sk1
mkdi r / u01/ st age10g/ pat ch10. 2. 0. 4

cd / u01/ st age10g/ pat ch10. 2. 0. 4/ Di sk1
. / r unI nst al l er
Sel ect pat h of ORACLE_HOME - >Next
4. Configure Listeners
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
. / net ca &
Add a new l i st ener

- - opt i onal l y, use net manager t o manual l y r egi st er t he dat abase:
. / net mgr
5. Create Database
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
. / dbca &
f ol l ow t he st eps t o cr eat e a cust omi zed dat abase of SI D " ora10g" and Gl obal
nmae " ora10g.oradb1" .
Do not use speci f i c t empl at es ( non- Cust om) .

The DBCA may pop up t he f ol l owi ng message i n t he end of db cr eat i on:
" Er r or secur i ng Dat abase cont r ol , Dat abase Cont r ol has been br ought up i n non-
secur e mode. To secur e t he Dat abase Cont r ol execut e t he f ol l owi ng commands:
. . . "

# check t he Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep
6. Postinstallation Tasks
Verify OEM:
# ver i f y t hat OEM i s wor ki ng
ht t p: / / or adb1: 1158/ em
# r est ar t t he dbconsol e i f r equi r ed
emct l st at us dbconsol e
emct l st op dbconsol e
emct l st ar t dbconsol e
Verify iSQL*Plus:
# i n t he br owser
ht t p: / / or adb1: 5560/ i sql pl us

# i f not r unni ng:
i sql pl usct l st ar t
Consider implementing automatic database startup. See: Automatically Starting Databases
Consider implementing automatic EM Database Control startup. See: Implementing EM
Database Control Auto Startup
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems
For easy Oracle Home access:
Page 46 Oracle DBA Code Examples

echo " al i as db=' cd $ORACLE_HOME' " >> / home/ or acl e/ . bashr c
Page 47 Oracle DBA Code Examples

Installing Oracle 11g R2 on Enterprise Linux 5
Note: for any installation, you should check the Release Notes documenation before taking
any practical step.
Installation Environment
Emulation software: VMWare Workstation 7 for Windows
OS: Red Hat Enterprise Linux 5.2 for x86
Required Software
Oracle Database 11g Release 2 for Linux x86 32-bit
Used Hardware
In the VMWare: create one virtual machine with the following specs:
o 2.0 GB RAM
o One ethernet cards: can be configured as bridged or host-only in VMware.
o One local hardisk with 32 GB on SCSI 0:0. It will be used for software installation.
o One local hardisk with 20 GB on SCSI 1:0. It will be used for Oracle Database data
files.
o One local hardisk with 20 GB on SCSI 1:1. It will be used for Oracle Database flash
recovery.
o CPU Count: 2 (optional)
Installation Plan
1. Preinstallation tasks:
o Hardware requirements
o Software requirements
o Environment configuration
2. Oracle Database 11g Software Installation
3. Apply Patchset
4. Configure Listeners
5. Create Database
6. Postinstallation tasks

1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Page 48 Oracle DBA Code Examples

Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Give the ethernet card IP 192. 168. 4. 100 and the hostname sr v100. mydomai n. com.
Define a gateway. If it does not exist, make it same as the host IP address.
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Applications
o Graphical Internet (optional)
o Editors (optional)
Development
o Development Libraries
o Development Tools
Servers
o Do not select anything in this group.
Base System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
X Window System
Complete the installation
RHEL 5 Bug: After the Installation compelets, RHEL 5.2 and below will hang on booting
when it reaches to "starting udev" line. To solve this problem, shutdown the Vmware
machine and change the CPU count and Core Count to only one. Implement the changes
below, then shutdown the machine, set CPU count back to 2 and startup the machine.
put the kernel command line parameters at the end of the "kernel" line:
vi / boot / gr ub/ gr ub. conf
add di vi der =10 cl ocksour ce=acpi _pm
For example: ker nel / vml i nuz- 2. 6. 18 . . cl ock=acpi _pmdi vi der =10
For Vmware machines, install VMWare tools.
Install further packages:
# t o know di st r i but i on and ver si on of Li nux ( Red Hat Ent . 5. 2 used)
cat / et c/ i ssue
# t o know ker nel ver si on ( and i t s er r at a l evel ) ( 2. 6. 18- 92 or newer )
uname - r

# t o l i st mi ssed packages:
r pm- q - - qf ' %{NAME}- %{VERSI ON}- %{RELEASE} ( %{ARCH}) \ n' bi nut i l s \
compat - l i bst dc++- 33 \
el f ut i l s- l i bel f \
el f ut i l s- l i bel f - devel \
gcc \
Page 49 Oracle DBA Code Examples

gcc- c++ \
gl i bc \
gl i bc- common \
gl i bc- devel \
gl i bc- header s \
ksh \
l i bai o \
l i bai o- devel \
l i bgcc \
l i bst dc++ \
l i bst dc++- devel \
make \
sysst at \
uni xODBC \
uni xODBC- devel

# f or mi ssed packages, i nst al l t hem:
r pm- Uvh l i bai o- devel - 0. 3. 106- 3. 2. i 386. r pm
r pm- Uvh uni xODBC*


# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Check the hardware requirements
# Har dwar e Requi r ement s ( i n cl ust er nodes)
# At l east 1. 0 GB of physi cal memor y
gr ep MemTot al / pr oc/ memi nf o

# swap space: same as t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o

# t o di spl ay swap and memor y i n one command:
f r ee

# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 1 GB di sk space i n / t mp
df - h / t mp
# 4 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
df - h / dev/ shm/
Page 50 Oracle DBA Code Examples

# t o adj ust t he shar ed memor y f i l e syst emsi ze:
umount t mpf s
mount - t t mpf s shmf s - o si ze=1200m/ dev/ shm
Create the required network configuration:
pi ng sr v100
pi ng sr v100. mydomai n. com

# Net wor k names Resol ut i on
# conf i gur e / et c/ host s i f no domai n ser ver i s used
cat / et c/ host s
127. 0. 0. 1 sr v100. mydomai n. com sr v100 l ocal host . l ocal domai n
l ocal host
Create and configure the required OS users and groups
# al l gr oup and user i ds on al l t he nodes must have i dent i cal i d
# Gr i d I nf r ast r uct ur e ( GI ) and t he Or acl e RDBMS home wi l l
# be i nst al l ed usi ng di f f er ent user s:
# or acl e i nvent or y gr oup
/ usr / sbi n/ gr oupadd - g 501 oi nst al l
/ usr / sbi n/ gr oupadd - g 502 dba
/ usr / sbi n/ user add - u 502 - g oi nst al l - G dba or acl e

# set passwor ds
passwd or acl e

# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody


# define the env variables for oracle user
vi /home/oracle/.bash_profile
# Oracle evn vars
export EDITOR=vi
export TMP=/tmp
export TMPDIR=$TMP
export ORACLE_HOSTNAME=srv100.mydomain.com
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1
export ORACLE_SID=ora11gr2
export ORACLE_TERM=xterm
export PATH=/usr/sbin:$PATH
export PATH=$ORACLE_HOME/bin:$PATH
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
export CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib


# shel l st ar t up f i l e
vi / et c/ pr of i l e
i f [ $USER = " or acl e" ] | | [ $USER = " gr i d" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i

Page 51 Oracle DBA Code Examples


# f or C shel l
vi / et c/ csh. l ogi n
i f ( $USER = " or acl e" | | $USER = " gr i d" ) t hen
l i mi t maxpr oc 16384
l i mi t descr i pt or s 65536
endi f
Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start, then
you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Conf i gur i ng ker nel par amet er s and shel l l i mi t s
# t hey can be t uned f or a pr oduct i on db
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf

# ker nel . shmmax not st at ed i n 11g R2 ( max: 4GB) ( 169706. 1)
ker nel . shmmni = 4096
ker nel . sem= 250 32000 100 128
f s. ai o- max- nr = 1048576
f s. f i l e- max = 6815744
net . i pv4. i p_l ocal _por t _r ange = 9000 65500
net . cor e. r mem_def aul t = 262144
net . cor e. r mem_max = 4194304
net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 1048576

# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf
or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536

vi / et c/ pam. d/ l ogi n
sessi on r equi r ed pam_l i mi t s. so
Create the required directories for the Oracle database software:
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

# Or acl e I nvent or y Di r ect or y
# as a r oot
mkdi r - p / u01/ app/ or aI nvent or y
chown - R or acl e: oi nst al l / u01/ app/ or aI nvent or y
chmod - R 775 / u01/ app/ or aI nvent or y

# Or acl e Base Di r ect or y
mkdi r - p / u01/ app/ or acl e
Page 52 Oracle DBA Code Examples

#needed t o ensur e t hat dbca i s abl e t o r un af t er t he r dbms i nst al l at i on
mkdi r - p / u01/ app/ or acl e/ cf gt ool l ogs
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ app/ or acl e

# Or acl e RDBMS Home Di r ect or y
mkdi r - p / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chown - R or acl e: oi nst al l / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chmod - R 775 / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1

# st agi ng ar ea t o hol d sof t war e i nst al l at i on
mkdi r - p / u01/ st age11g/ db
chown - R or acl e: oi nst al l / u01/ st age11g/ db
chmod - R 775 / u01/ st age11g/ db
Partition and mount the disks:
#def i ne t he di sks t o par t i t i on
f di sk - l | gr ep ' ^Di sk'

# as a r oot , f or t he di sks / dev/ sdb and / dev/ sdc
#par t i t i on t he di sks:
f di sk / dev/ sdb
# answer s: " n" , " p" , " 1" , " Ret ur n" , " Ret ur n" , " p" and " w"
Not e: i f t he f ol l owi ng message appear s af t er t he " w" command:
WARNI NG: Re- r eadi ng t he par t i t i on t abl e f ai l ed wi t h er r or 16: Devi ce or
r esour ce busy, t hen you can avoi d r est ar t i ng t he machi ne by t he f ol l owi ng
command: par t pr obe

# t o make sur e par t i ons ar e cr eat ed
l s - l X / dev/ sd*

# f or mat t he par i t i ons
mkf s. ext 3 / dev/ sdb1
mkf s. ext 3 / dev/ sdc1

# Mount t he new di sk
mkdi r / u02
mount / dev/ sdb1 / u02
mkdi r / u03
mount / dev/ sdc1 / u03
df - H

# Updat e / et c/ f st ab
vi / et c/ f st ab
/ dev/ sdb1 / u02 ext 3 def aul t s 1 2
/ dev/ sdc1 / u03 ext 3 def aul t s 1 2

# cr eat e f ol der f or t he db dat a
mkdi r - p / u02/ or adat a/
chown - R or acl e: oi nst al l / u02/ or adat a/
chmod - R 775 / u02/ or adat a/

# cr eat e f ol der f or t he f l ash ar ea
mkdi r - p / u03/ or af l ash/
chown - R or acl e: oi nst al l / u03/ or af l ash/
chmod - R 775 / u03/ or af l ash/
As oracle, copy software installation into /u01/stage11g/db
Page 53 Oracle DBA Code Examples

2. Oracle Database 11g Software Installation
- - st ar t OUI
su - or acl e
cd / u01/ st age11g/ db
. / r unI nst al l er

Fol l ow t he st eps.
I nst al l dat abase sof t war e onl y.
3. Apply Patchset

4. Configure Listeners
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
. / net ca &
Add a new l i st ener
Add Nami ng mt ehods: Local Nami ng, EZConnect
5. Create Database
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
. / dbca &
f ol l ow t he st eps t o cr eat e a dat abase wi t h si d: or a11gr 2

The DBCA may pop up t he f ol l owi ng message i n t he end of db cr eat i on:
" Er r or secur i ng Dat abase cont r ol , Dat abase Cont r ol has been br ought up i n non-
secur e mode. To secur e t he Dat abase Cont r ol execut e t he f ol l owi ng commands:
. . . "
6. Postinstallation Tasks
Verify OEM:
# ver i f y t hat OEM i s wor ki ng
ht t ps: / / sr v100. mydomai n. com: 1158/ em
# r est ar t t he dbconsol e i f r equi r ed
emct l st at us dbconsol e
emct l st op dbconsol e
emct l st ar t dbconsol e

# check Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep
Consider implementing automatic database startup. See: Automatically Starting Databases
Consider implementing automatic EM Database Control startup. See: Implementing EM
Database Control Auto Startup
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems
For easy Oracle Home access:
echo " al i as db=' cd $ORACLE_HOME' " >> / home/ or acl e/ . bashr c
Page 54 Oracle DBA Code Examples

Installing Oracle 11g R2 on Enterprise Linux 5.5 with
ASM
Note: for any installation, you should check the Release Notes documenation before taking
any practical step.
Installation Environment
Emulation software: VMWare Workstation 7 for Windows
OS: Oracle Enterprise Linux 5.5 for x86 64-bit
Required Software
Oracle Database 11g Release 2 for Linux x86 64-bit
Oracle Database 11g Release 2 Grid Infrastructure (11.2.0.1.0) for Linux x86 64-bit
Used Hardware
In the VMWare: create one virtual machine with the following specs:
o 2.5 GB RAM
o One ethernet card configured as bridged or host-only in VMware
o CPU Count: 2
o Disk1: 34 GB on SCSI 0:0 used to install the OS and software
o Disk2: of 12 GB. It will be used for +Data. Set it on controller SCSI 1:1
o Disk3: of 6 GB. It will be used for +Flash. Set it on controller SCSI 1:2
Installation Plan
1. Preinstallation tasks
Hardware requirements
Software requirements
Environment configuration
2. Oracle Grid Infrastructure installation
3. Oracle Grid Infrastructure Patching
4. Oracle Database 11g R2 Software Installation
5. Oracle Database 11g R2 Software Patching
6. Install EM Agent in cluster nodes (if required)
7. ASM Diskgroups Creation
8. Database Creation
9. Complete postinstallation tasks
Page 55 Oracle DBA Code Examples

10. Useful postinstallation tasks

1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Configure the swap area in the local hardisk to have 6 GB disk space.
o Give the ethernet card IP 192.168.4.105 the hostname sr v07
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Applications
o Graphical Internet (optional)
o Editors (optional)
Development
o Development Libraries
o Development Tools
Servers
o Do not select anything in this group.
Base System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
X Window System
Complete the installation
Install further packages:
# t o know di st r i but i on and ver si on of Li nux
cat / et c/ i ssue
# t o know ker nel ver si on ( and i t s er r at a l evel ) ( 2. 6. 18- 194. el 5)
uname - r

# t o l i st mi ssed packages:
r pm- q - - qf ' %{NAME}- %{VERSI ON}- %{RELEASE} ( %{ARCH}) \ n' bi nut i l s \
compat - l i bst dc++- 33 \
el f ut i l s- l i bel f \
el f ut i l s- l i bel f - devel \
gcc \
gcc- c++ \
gl i bc \
gl i bc- common \
gl i bc- devel \
Page 56 Oracle DBA Code Examples

gl i bc- header s \
ksh \
l i bai o \
l i bai o- devel \
l i bgcc \
l i bst dc++ \
l i bst dc++- devel \
make \
sysst at \
uni xODBC \
uni xODBC- devel

# f or mi ssed packages, i nst al l t hem:
r pm- Uvh el f ut i l s- l i bel f - 0. 137- 3. el 5. i 386. r pm
r pm- i vh el f ut i l s- l i bel f - devel - st at i c- 0. 137- 3. el 5. i 386. r pmel f ut i l s- l i bel f -
devel - 0. 137- 3. el 5. i 386. r pm
r pm- Uvh ker nel - header s- 2. 6. 18- 194. el 5. x86_64. r pm
r pm- Uvh gl i bc- header s- 2. 5- 49. x86_64. r pm
r pm- Uvh gl i bc- devel - 2. 5- 49. i 386. r pm
r pm- Uvh gl i bc- devel - 2. 5- 49. x86_64. r pm
r pm- Uvh l i bgomp- 4. 4. 0- 6. el 5. x86_64. r pm
r pm- Uvh gcc- 4. 1. 2- 48. el 5. x86_64. r pm
r pm- Uvh gcc- c++- 4. 1. 2- 48. el 5. x86_64. r pm
r pm- Uvh l i bst dc++- devel - 4. 1. 2- 48. el 5. x86_64. r pm
r pm- Uvh gcc- c++- 4. 1. 2- 48. el 5. x86_64. r pm
r pm- Uvh l i bai o- devel - 0. 3. 106- 5. i 386. r pm
r pm- Uvh l i bai o- devel - 0. 3. 106- 5. x86_64. r pm
r pm- Uvh uni xODBC- 2. 2. 11- 7. 1. i 386. r pm
r pm- Uvh uni xODBC- 2. 2. 11- 7. 1. x86_64. r pm
r pm- Uvh uni xODBC- devel - 2. 2. 11- 7. 1. i 386. r pm
r pm- Uvh uni xODBC- devel - 2. 2. 11- 7. 1. x86_64. r pm


# Or acl e ASM Li bar ay and dr i ver s can be downl oaded f r omher e
# t o know t he ker nel ver i on: uname - r m
# I n t hi s case we need:
# l i br ar y and t ool s
r pm- Uvh or acl easm- suppor t - 2. 1. 3- 1. el 5. x86_64. r pm
r pm- Uvh or acl easm- 2. 6. 18- 194. el 5- 2. 0. 5- 1. el 5. x86_64. r pm
r pm- Uvh or acl easml i b- 2. 0. 4- 1. el 5. x86_64. r pm

# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Check the hardware requirements
# Har dwar e Requi r ement s ( i n cl ust er nodes)
# At l east 1. 5 GB of physi cal memor y but pr act i cal l y 1. 5 i s not f i ne
gr ep MemTot al / pr oc/ memi nf o

# swap space: same as t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o

# t o di spl ay swap and memor y i n one command:
f r ee
Page 57 Oracle DBA Code Examples


# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 1 GB di sk space i n / t mp
df - h / t mp
# 8 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
df - h / dev/ shm/
# t o adj ust t he shar ed memor y f i l e syst emsi ze:
umount t mpf s
mount - t t mpf s shmf s - o si ze=1200m/ dev/ shm
Create the required network configuration:
pi ng sr v07

# Net wor k names Resol ut i on
cat / et c/ host s
127. 0. 0. 1 sr v07 l ocal host . l ocal domai n l ocal host

Create and configure the required OS users and groups
Note: When I tried using differenct OS users and groups for Grid Infrastrucutre and ASM,
I got error later in DBCA.
# Gr i d I nf r ast r uct ur e ( GI ) and t he Or acl e RDBMS home wi l l
# be i nst al l ed usi ng di f f er ent user s:
/ usr / sbi n/ gr oupadd - g 501 oi nst al l
/ usr / sbi n/ gr oupadd - g 502 dba
/ usr / sbi n/ gr oupadd - g 504 asmadmi n
/ usr / sbi n/ user add - u 502 - g oi nst al l - G dba, asmadmi n or acl e

# set passwor ds
passwd or acl e

# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody

# define the env variables for oracle user
vi /home/oracle/.bash_profile

# Oracle Settings
export EDITOR=vi
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR
ORACLE_HOSTNAME=srv07; export ORACLE_HOSTNAME
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
Page 58 Oracle DBA Code Examples

ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1; export ORACLE_HOME
ORACLE_SID=oradb; export ORACLE_SID
ORACLE_TERM=xterm; export ORACLE_TERM
PATH=/usr/sbin:$PATH; export PATH
PATH=$ORACLE_HOME/bin:$PATH; export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/jdk/jre/lib/:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib;
export CLASSPATH

# shel l st ar t up f i l e
vi / et c/ pr of i l e
i f [ $USER = " or acl e" ] | | [ $USER = " gr i d" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i

# f or C shel l
vi / et c/ csh. l ogi n
i f ( $USER = " or acl e" | | $USER = " gr i d" ) t hen
l i mi t maxpr oc 16384
l i mi t descr i pt or s 65536
endi f
Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start,
then you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Ker nel Par amet er s
# t o t une t hme, r ef er t o met al i nk document 169706. 1
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf

ker nel . shmmni = 4096
ker nel . sem= 250 32000 100 128
f s. ai o- max- nr = 1048576
f s. f i l e- max = 6815744
net . i pv4. i p_l ocal _por t _r ange = 9000 65500
net . cor e. r mem_def aul t = 262144
net . cor e. r mem_max = 4194304
net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 1048576

# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf

or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536
Page 59 Oracle DBA Code Examples


vi / et c/ pam. d/ l ogi n
sessi on r equi r ed pam_l i mi t s. so
Create partitions in the disks:
Note: On a real life storage, you would create a single whole-disk partition with exactly 1 MB
offset on each LUN to be used as ASM Disk. In fdisk: u (to change units from cylinder to
sectors), n, p, 1, 2048, w.
# as a r oot , f or t he di sks / dev/ sdb . . / dev/ sdd
# conf i r mt hey ar e seen:
l s / dev/ sd*
#par t i t i on t he di sks:
f di sk / dev/ sdb
# answer s: " n" , " p" , " 1" , " Ret ur n" , " Ret ur n" , " p" and " w"
Not e: i f t he f ol l owi ng message appear s af t er t he " w" command:
WARNI NG: Re- r eadi ng t he par t i t i on t abl e f ai l ed wi t h er r or 16: Devi ce or
r esour ce busy, t hen you can avoi d r est ar t i ng t he machi ne by t he f ol l owi ng
command: par t pr obe

# t o make sur e par t i ons ar e cr eat ed
l s - l X / dev/ sd*
Configure ASM drivers:
# as r oot ( t o be done i n al l nodes)
or acl easmconf i gur e - i

Def aul t user t o own t he dr i ver i nt er f ace [ ] : oracle
Def aul t gr oup t o own t he dr i ver i nt er f ace [ ] : asmadmin
St ar t Or acl e ASM l i br ar y dr i ver on boot ( y/ n) [ n] : y
Fi x per mi ssi ons of Or acl e ASM di sks on boot ( y/ n) [ y] : y
Wr i t i ng Or acl e ASM l i br ar y dr i ver conf i gur at i on: done

# Load t he ker nel modul e usi ng t he f ol l owi ng command:
/ usr / sbi n/ or acl easmi ni t
# I f you have any pr obl ems, make sur e you have t he cor r ect
# ver si on of t he dr i ver ( may r equi r e I nt er net connect i on) :
/ usr / sbi n/ or acl easmupdat e- dr i ver

# mar k t he shar ed di sks: ( one node)
/ usr / sbi n/ or acl easmcr eat edi sk DI SK1 / dev/ sdb1
/ usr / sbi n/ or acl easmcr eat edi sk DI SK2 / dev/ sdc1

# check t he di sks ar e mar ked and seen:
/ usr / sbi n/ or acl easml i st di sks

#I f you need t o unmar k a di sk t hat was used i n a cr eat edi sk command:
/ usr / sbi n/ or acl easmdel et edi sk DI SK1
/ usr / sbi n/ or acl easmdel et edi sk DI SK2
Create the required directories for the Oracle software:
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

Page 60 Oracle DBA Code Examples

# Or acl e I nvent or y Di r ect or y
# as a r oot
mkdi r - p / u01/ app/ or aI nvent or y
chown - R or acl e: oi nst al l / u01/ app/ or aI nvent or y
chmod - R 775 / u01/ app/ or aI nvent or y

# Gr i d I nf r ast r uct ur e Home Di r ect or y
mkdi r - p / u01/ 11. 2. 0/ gr i d
chown - R or acl e: oi nst al l / u01/ 11. 2. 0/ gr i d
chmod - R 775 / u01/ 11. 2. 0/ gr i d

# Or acl e Base Di r ect or y
mkdi r - p / u01/ app/ or acl e
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ app/ or acl e

#needed t o ensur e t hat dbca i s abl e t o r un af t er t he r dbms i nst al l at i on
mkdi r / u01/ app/ or acl e/ cf gt ool l ogs
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ app/ or acl e

# Or acl e RDBMS Home Di r ect or y
mkdi r - p / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chown - R or acl e: oi nst al l / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chmod - R 775 / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
2. Oracle Grid Infrastructure installation
# sof t war e st agi ng f ol der
mkdi r - p / u01/ app/ st age/ or a11gr 2gr i di nf r a
chown - R or acl e: oi nst al l / u01/ app/ st age/ or a11gr 2gr i di nf r a
chmod - R 775 / u01/ app/ st age/ or a11gr 2gr i di nf r a

mkdi r - p / u01/ app/ st age/ or a11gr 2db
chown - R or acl e: oi nst al l / u01/ app/ st age/ or a11gr 2db
chmod - R 775 / u01/ app/ st age/ or a11gr 2db

# as or acl e: copy Gr i d sof t war e f i l es t o / u01/ app/ st age/ or a11gr 2db

# as r oot :
chmod - R 775 / u01/ app/ st age/ or a11gr 2gr i di nf r a

# l unch OUI f r omt he cl ust er war e ( as or acl e)
cd / u01/ app/ st age/ or a11gr 2gr i di nf r a
. / r unI nst al l er

I nst al l at i on Opt i on
>Sel ect r adi o but t on ' I nst al l and Conf i gur e Gr i d I nf r ast r uct ur e f or a
St andal one Ser ver '
>Next

Pr oduct Language
>Accept ' Engl i sh' as l anguage'
>Next
Cr eat ASM Di sk Gr oup
>Di sk Gr oup Name: Dat a ( 12GB di sk: DI SK1)
>Redundancy: ext er nal
>Next
Page 61 Oracle DBA Code Examples

NOTE: I f you see an empt y scr een f or you candi dat e di sks i t i s l i kel y t hat
ASMLi b has not been pr oper l y conf i gur ed or i nst al l ed. Tr y r econf i gur e t hem.
I f you ar e sur e t hat ASMLi b has been pr oper l y conf i gur ed cl i ck on ' Change
Di scover y Pat h' and pr ovi de t he cor r ect dest i nat i on.

ASM Passwor d
>Speci f y and conf or mt he passwor d you want t o use
>Next

Pr i vi l eged OS Gr oups
>Assi gn t he cor r ect OS gr oups f or OS aut hent i cat i on ( most l y def aul t i s OK)
>Next

I nst al l at i on Locat i on
>ORACLE_BASE: / u01/ app/ or acl e
Sof t war e l ocat i on: / u01/ 11. 2. 0/ gr i d
>Next

Cr eat e I nvent or y
>Speci f y t he l ocat i ons: / u01/ app/ or aI nvent or y
>Next

Per f or mPr er equi si t e Checks
>Check t hat st at us of al l checks i s Succeeded
>Next

Summar y
>Fi ni sh

Execut e Conf i gur at i on Scr i pt s
>Run t he scr i pt s as i nst r uct ed i n t he scr een
>OK

>Next

Message: The i nst al l at i on of t he Gr i d I nf r ast r uct ur e was successf ul l .
>Cl ose
3. Oracle Grid Infrastructure Patching
Appl y pat ch set , i f t her e i s any.
4. Oracle Database 11g R2 Software Installation
# as or acl e: copy DB sof t war e f i l es i nt o / u01/ app/ st age/ or a11gr 2db

# as r oot :
chmod - R 775 / u01/ app/ st age/ or a11gr 2db

- - st ar t OUI
su - or acl e
cd / u01/ app/ st age/ or a11gr 2db
. / r unI nst al l er

Fol l ow t he st eps.
I nst al l dat abase sof t war e onl y.

When execut i ng r oot . sh, sel ect " y" f or ovewr i t i ng quest i ons.
Page 62 Oracle DBA Code Examples

5. Oracle Database 11g R2 Software Patching

6. Install EM Agent in cluster nodes (if required)

7. ASM Diskgroups Creation
# as gr i d user : st ar t t he ASM Conf i gur at i on Assi st ant ( ASMCA)
su - or acl e
cd / u01/ 11. 2. 0/ gr i d/ bi n
. / asmca

>Di sk Gr oups t ab
>Cr eat e but t on
>Di sk Gr oup Name: FLASH
>Redundancy: Ext er nal
>DI SK2
>OK
>Exi t
>Yes
8. Database Creation
# as or acl e
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n
. / dbca

f ol l ow t he st eps t o cr eat e a dat abase wi t h si d: or adb

The DBCA may pop up t he f ol l owi ng message i n t he end of db cr eat i on:
" Er r or secur i ng Dat abase cont r ol , Dat abase Cont r ol has been br ought up i n non-
secur e mode. To secur e t he Dat abase Cont r ol execut e t he f ol l owi ng commands:
. . . "

# check Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep
9. Postinstallation tasks
# backup t he r oot . sh scr i pt
cp / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ r oot . sh ~/ r oot . sh. bak

cont >>
10. General Useful Postinstallation Tasks in Linux
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems
/ * Make cr s_st at - t mor e r eadabl e */
/ * copy t he f ol l owi ng scr i pt i nt o ~/ scr i pt s/ cr st at . sh */
#! / usr / bi n/ ksh
#
# Sampl e 10g CRS r esour ce st at us quer y scr i pt
#
Page 63 Oracle DBA Code Examples

# Descr i pt i on:
# - Ret ur ns f or mat t ed ver si on of cr s_st at - t , i n t abul ar
# f or mat , wi t h t he compl et e r sc names and f i l t er i ng keywor ds
# - The ar gument , $RSC_KEY, i s opt i onal and i f passed t o t he scr i pt , wi l l
# l i mi t t he out put t o HA r esour ces whose names mat ch $RSC_KEY.
# Requi r ement s:
# - $ORA_CRS_HOME shoul d be set i n your envi r onment
# suggest ed scr i p name: cr st at . sh

RSC_KEY=$1
QSTAT=- u
AWK=/ usr / bi n/ awk # i f not avai l abl e use / usr / bi n/ awk

# Tabl e header : echo " "
$AWK \
' BEGI N {pr i nt f " %- 45s %- 10s %- 18s\ n" , " HA Resour ce" , " Tar get " , " St at e" ;
pr i nt f " %- 45s %- 10s %- 18s\ n" , " - - - - - - - - - - - " , " - - - - - - " , " - - - - - " ; }'

# Tabl e body:
$ORA_CRS_HOME/ bi n/ cr s_st at $QSTAT | $AWK \
' BEGI N { FS=" =" ; st at e = 0; }
$1~/ NAME/ && $2~/ ' $RSC_KEY' / {appname = $2; st at e=1};
st at e == 0 {next ; }
$1~/ TARGET/ && st at e == 1 {appt ar get = $2; st at e=2; }
$1~/ STATE/ && st at e == 2 {appst at e = $2; st at e=3; }
st at e == 3 {pr i nt f " %- 45s %- 10s %- 18s\ n" , appname, appt ar get , appst at e;
st at e=0; }'


# t hen add t he f ol l owi ng i n t he . bashr c of or acl e user
# i f t he f i l e was saved i n ~/ scr i pt s/ cr st at . sh
al i as cr st at =' ~/ scr i pt s/ cr st at . sh'

/ * Easy Acces t o cr s and db homes */
# i t i s common t o access bi n di r ect or i es i n cl ust er war e and db homes

# add t he f ol l owi ng t o . bashr c of or acl e user
al i as db=' cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n'

# add t he f ol l owi ng t o . bashr c of gr i d user
al i as cr s=' cd / u01/ app/ or acl e/ cr s/ bi n'
Page 64 Oracle DBA Code Examples

Managing Oracle Database Instance
Product Release Number
Oracle Database Release Number Format
SELECT * FROM PRODUCT_COMPONENT_VERSI ON;
SELECT * FROM V$VERSI ON
1.2.3.4.5
1 Major database release number
2 Maintenance release number
3 application server release number
4 component specific release number
5 platform specific release number
Obtaining License Information
- - Number of user s and CPU/ Pr ocessor s
sel ect L. SESSI ONS_MAX, L. SESSI ONS_WARNI NG, L. SESSI ONS_CURRENT,
L. SESSI ONS_HI GHWATER,
L. USERS_MAX, L. CPU_COUNT_CURRENT, L. CPU_SOCKET_COUNT_CURRENT,
L. CPU_COUNT_HI GHWATER,
L. CPU_CORE_COUNT_CURRENT, L. CPU_CORE_COUNT_HI GHWATER,
L. CPU_SOCKET_COUNT_HI GHWATER
f r omv$l i cense l ;

- - Dat abase Edi t i on
sel ect banner f r omv$ver si on wher e BANNER l i ke ' %Edi t i on%' ;

- - Or acl e Par t i t i oni ng i nst al l ed
sel ect decode( count ( *) , 0, ' No' , ' Yes' )
f r omdba_par t _t abl es
wher e owner not i n ( ' SYSMAN' , ' SH' , ' SYS' , ' SYSTEM' ) and r ownum= 1;

- - Or acl e Spat i al i nst al l ed:
sel ect decode( count ( *) , 0, ' No' , ' Yes' )
f r omal l _sdo_geom_met adat a wher e r ownum= 1;

- - Or acl e RAC i nst al l ed:
sel ect decode( count ( *) , 0, ' No' , ' Yes' )
f r omv$act i ve_i nst ances wher e r ownum<= 2;
Managing the Instance Architecture
Obtaining Information about the Instance Processes
ps ef | gr ep or a

sel ect name, descr i pt i on f r om V$BGPROCESS or der by 1;
Page 65 Oracle DBA Code Examples

Obtaining Information about the SGA
sel ect val ue f r omv$par amet er wher e upper ( name) =' MEMORY_TARGET' ;
sel ect val ue/ 1024/ 1024 mb
f r omv$par amet er wher e upper ( name) = ' SGA_MAX_SI ZE'

- - si ze t aken by a memor y component
sel ect pool , r ound( sum( BYTES) / 1024/ 1024) MB
f r omV$SGASTAT
gr oup by pool

sel ect name , val ue/ 1024/ 1024 MB
f r omv$par amet er
wher e upper ( name) i n (
' DB_CACHE_SI ZE' , ' DB_RECYCLE_CACHE_SI ZE' , ' DB_KEEP_CACHE_SI ZE' , '
DB_2k_CACHE_SI ZE' , ' DB_8k_CACHE_SI ZE' , ' DB_16k_CACHE_SI ZE' )

- - 10g
SELECT COMPONENT , CURRENT_SI ZE/ 1024/ 1024 MB
FROM V$SGA_DYNAMI C_COMPONENTS
WHERE CURRENT_SI ZE <>0

- - Or acl e 11g
SELECT COMPONENT, ROUND( CURRENT_SI ZE/ 1024/ 1024) CURRENT_SI ZE ,
ROUND( MI N_SI ZE/ 1024/ 1024) MI N, ROUND( MAX_SI ZE/ 1024/ 1024) MAX
FROM V$MEMORY_DYNAMI C_COMPONENTS;
- - To know how Or acl e has modi f i ed t he memor y ar ea si zes by t i me
sel ect START_TI ME, END_TI ME, STATUS, COMPONENT, OPER_TYPE, OPER_MODE,
PARAMETER, I NI TI AL_SI ZE/ 1024/ 1024 I NI TI AL_SI ZE_MB,
TARGET_SI ZE/ 1024/ 1024 TARGET_SI ZE_MB, FI NAL_SI ZE/ 1024/ 1024 FI NAL_SI ZE_MB
f r omV$MEMORY_RESI ZE_OPS
or der by START_TI ME, END_TI ME
Clearing the Buffer Cache
ALTER SYSTEM FLUSH SHARED_POOL;
ALTER SYSTEM FLUSH BUFFER_CACHE ;
Database Administration Authentication
Using Operating System Authentication
Following are the steps to create an Oracle administrator using OS authenticaion. Creating
normal user who is capable of using OS authentication is a bit different. See External (OS)
Authentication.
1. Create an operating system account for the user.
2. Add the account to the OSDBA or OSOPER operating system defined groups.
Unix User Groups: dba, oper
Windows: ORA_DBA, ORA_OPER
3. login to OS as the created user
4. In SQL*Plus
CONNECT / AS SYSDBA
CONNECT / AS SYSOPER
Page 66 Oracle DBA Code Examples

Using Password File Authentication
5. Create the password file
6. orapwd FILE=filename PASSWORD=password ENTRIES=max_users
7. alter system set REMOTE_LOGIN_PASSWORDFILE = EXCLUSIVE scope=SPFILE;
8. CONN / AS SYSDBA
9. GRANT SYSDBA TO GRANTEDUSER
10. CONN GRANTEDUSER/USERPASSWORD AS SYSDBA
Identifying Users SYSDBA or SYSOPER Users
SELECT * FROM V$PWFI LE_USERS
Data Dictionary and Dynamic Performance Views
Data Dictionary Creation
sql . bsq creates base tables
cat al og. sql creates data dictionary views
cat pr oc. sql runs scripts required for server-side PL/SQL
they run as SYSDBA
they are located in \rdbms\admin
Startup and Shutdown
Startup Levels
STARTUP [ FORCE] [ RESTRI CT] [ PFI LE=f i l ename] [ OPEN [ RECOVER] [ dat abase] | MOUNT
| NOMOUNT]
ALTER DATABASE { MOUNT | OPEN }
ALTER DATABASE OPEN [ READ WRI TE| READ ONLY]
ALTER SYSTEM ENABLE | DI SABLE RESTRI CTED SESSI ON;
Shutdown Levels
SHUTDOWN [ NORMAL | TRANSACTI ONAL | I MMEDI ATE | ABORT ]
Autostart of Database in Windows
As a service or name OracleServiceSID. You can manage the service using ORADIM utility.
You can control the shutdown type of the database when you shutdown its corresponding
service by editing the registry entry ORA_<SID>_SHUTDOWNTYPE in Oracle home entry.
Automatically Starting Databases in Unix
For Oracle 10.1, refer to Note 222813.1
/ * Exampl e 1 */
# compat i bl e wi t h Not e 281912. 1 ( and Not e 760051. 1)
#( 1) l ogi n as r oot
#( 2) Set i t t o Y i n / et c/ or at ab
mydb: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1: Y
Page 67 Oracle DBA Code Examples


#( 3) Cr eat e dbor a scr i pt i n t he di r ect or y / et c/ i ni t . d
# f i x ORA_HOME and ORA_OWNER val ues as r equi r ed
vi / et c/ i ni t . d/ dbor a

#! / bi n/ bash
#
# descr i pt i on: St ar t / St op t he Dat abases. .
#
# chkconf i g: 2345 99 10
#
# pr ocessname: or acl e
# conf i g: / et c/ or at ab
# pi df i l e: / var / r un/ or acl e. pi d

# Sour ce f unct i on l i br ar y.
. / et c/ i ni t . d/ f unct i ons

RETVAL=0
ORA_OWNER=" or acl e"
ORA_HOME=" / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1"

pr og=" or acl e"

st ar t ( ) {
echo - n $" St ar t i ng $pr og: "
su - $ORA_OWNER - c " $ORA_HOME/ bi n/ dbst ar t "
su - $ORA_OWNER - c " $ORA_HOME/ bi n/ l snr ct l st ar t "
RETVAL=$?
echo
[ $RETVAL - eq 0 ] && t ouch / var / l ock/ subsys/ dbor a
r et ur n $RETVAL
}

st op( ) {
echo - n $" St oppi ng $pr og: "
su - $ORA_OWNER - c " $ORA_HOME/ bi n/ dbshut "
su - $ORA_OWNER - c " $ORA_HOME/ bi n/ l snr ct l st op"
RETVAL=$?
echo
[ $RETVAL - eq 0 ] && r m- r / var / l ock/ subsys/ dbor a
r et ur n $RETVAL
}

r est ar t ( ) {
st op
st ar t
}

Page 68 Oracle DBA Code Examples

case " $1" i n
st ar t )
st ar t
; ;
st op)
st op
; ;
r est ar t )
r est ar t
; ;
*)
echo $" Usage: $0 {st ar t | st op| r est ar t }"
exi t 1
esac

exi t $?


#( 4) as r oot :
chgr p dba / et c/ i ni t . d/ dbor a
chmod 750 / et c/ i ni t . d/ dbor a

cd / sbi n
chkconf i g - - add dbor a
chkconf i g - - l i st | gr ep or a

# t o t est , r est ar t or :
/ et c/ i ni t . d/ dbor a st ar t

/ * Exampl e 2 */
- - have been t est ed on an Or acl e 10g Db on Li nux 4
#( 1) l ogi n as r oot
#( 2) Set i t t o Y i n / et c/ or at ab
mydb: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1: Y

#( 3) Cr eat e dbor a scr i pt i n t he di r ect or y / et c/ i ni t . d
# f i x ORACLE_HOME val ue as r equi r ed

#! / bi n/ sh
#
# / et c/ r c. d/ i ni t . d/ dbor a
# Descr i pt i on: St ar t s and st ops t he Or acl e dat abase and l i st ener s
#
case " $1" i n
st ar t )
echo - n " St ar t i ng Or acl e Dat abases: "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : St ar t i ng Or acl e Dat abases as par t of syst emup. "
>> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
su - or acl e - c dbst ar t >> / var / l og/ or acl e
Page 69 Oracle DBA Code Examples

echo " Done. "
echo - n " St ar t i ng Or acl e Li st ener s: "
su - or acl e - c " l snr ct l st ar t " >> / var / l og/ or acl e
echo " Done. "
echo " "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : Fi ni shed. " >> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
t ouch / var / l ock/ subsys/ or acl e
; ;
st op)
echo - n " Shut t i ng Down Or acl e Li st ener s: "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : Shut t i ng Down Or acl e Dat abases as par t of syst em
down. " >> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
su - or acl e - c " l snr ct l st op" >> / var / l og/ or acl e
echo " Done. "
r m- f / var / l ock/ subsys/ or acl e
echo - n " Shut t i ng Down Or acl e Dat abases: "
su - or acl e - c dbshut >> / var / l og/ or acl e
echo " Done. "
echo " "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : Fi ni shed. " >> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
; ;
r est ar t )
echo - n " Rest ar t i ng Or acl e Dat abases: "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : Rest ar t i ng Or acl e Dat abases as par t of syst emup. "
>> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
su - or acl e - c dbst op >> / var / l og/ or acl e
su - or acl e - c dbst ar t >> / var / l og/ or acl e
echo " Done. "
echo - n " Rest ar t i ng Or acl e Li st ener s: "
su - or acl e - c " l snr ct l st op" >> / var / l og/ or acl e
su - or acl e - c " l snr ct l st ar t " >> / var / l og/ or acl e
echo " Done. "
echo " "
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
dat e +" ! %T %a %D : Fi ni shed. " >> / var / l og/ or acl e
echo " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " >> / var / l og/ or acl e
t ouch / var / l ock/ subsys/ or acl e
; ;
*)
echo " Usage: or acl e {st ar t | st op| r est ar t }"
exi t
esac

# ( 4) set f i l e gr oup and per mi ssi ons
chgr p dba dbor a
chmod 750 dbor a

# ( 5) Cr eat e t he symbol i c l i nks: I n Li nux,
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c3. d/ K01dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c3. d/ S99dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c5. d/ K01dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c5. d/ S99dbor a
Page 70 Oracle DBA Code Examples


/ * Exampl e 3 */
#( 1) l ogi n as r oot
#( 2) Set i t t o Y i n / et c/ or at ab
mydb: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1: Y

#( 3) Cr eat e dbor a scr i pt i n t he di r ect or y / et c/ i ni t . d
# f i x ORACLE_HOME val ue as r equi r ed
vi / et c/ i ni t . d/ dbor a

#! / bi n/ bash
#
# or acl e I ni t f i l e f or st ar t i ng and st oppi ng
# Or acl e Dat abase. Scr i pt i s val i d f or 10g and 11g ver si ons.
#
# chkconf i g: 35 80 30
# descr i pt i on: Or acl e Dat abase st ar t up scr i pt

# Sour ce f unct i on l i br ar y.

. / et c/ r c. d/ i ni t . d/ f unct i ons

ORACLE_OWNER=" or acl e"
ORACLE_HOME=" / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1"

case " $1" i n
st ar t )
echo - n $" St ar t i ng Or acl e DB: "
su - $ORACLE_OWNER - c " $ORACLE_HOME/ bi n/ dbst ar t $ORACLE_HOME"
echo " OK"
echo - n " St ar t i ng Or acl e Li st ener s: "
su - $ORACLE_OWNER - c " $ORACLE_HOME/ bi n/ l snr ct l st ar t "
echo " OK"
; ;
st op)
echo - n $" St oppi ng Or acl e DB: "
su - $ORACLE_OWNER - c " $ORACLE_HOME/ bi n/ dbshut $ORACLE_HOME"
echo " OK"
echo - n " St oppi ng Or acl e Li st ener s: "
su - $ORACLE_OWNER - c " $ORACLE_HOME/ bi n/ l snr ct l st op"
echo " OK"
; ;
*)
echo $" Usage: $0 {st ar t | st op}"
esac

# ( 4) set f i l e gr oup and per mi ssi ons
chgr p dba / et c/ i ni t . d/ dbor a
chmod 750 / et c/ i ni t . d/ dbor a

# ( 5) Cr eat e t he symbol i c l i nks: I n Li nux,
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c3. d/ K01dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c3. d/ S99dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c5. d/ K01dbor a
l n - s / et c/ i ni t . d/ dbor a / et c/ r c. d/ r c5. d/ S99dbor a

Page 71 Oracle DBA Code Examples

# ( 6) conf i gur i ng execut i on f or speci f i c r unl evel s
chkconf i g - - add dbor a - - l evel 0356
Quiescing a Database
Users will remain logged in, and they can continue to execute their requests that are in
progress, while the database is in the quiesced state. The database, however, will block all
new transactional requests except those made by the users SYS and SYSTEM (not DBA
grantees).
ALTER SYSTEM QUI ESCE RESTRI CTED;
ALTER SYSTEM UNQUI ESCE;
SELECT i nst ance_name, st at us, shut down_pendi ng, act i ve_st at e FROM v$i nst ance;
Suspending a Database
All reads from and writes to the datafiles and control files are suspended.
ALTER SYSTEM SUSPEND;
ALTER SYSTEM RESUME;
SELECT i nst ance_name, st at us, shut down_pendi ng, act i ve_st at e FROM v$i nst ance;
Dropping a Database
Datafiles, redo log files, and control files are removed automatically. Alert log and
parameter file are not deleted.
CONNECT sys/ sys_passwd AS SYSDBA
SHUTDOWI MMEDI ATE
STARTUP RESTRI CT MOUNT
SELECT name FROM v$dat abase;
DROP DATABASE;
Initialization Files
Managing Initialization Files
During startup, in $ORACLE_HOME/dbs (for UNIX/Linux) Oracle will look for the correct
initialization file to use, in the following order:
o spfile$ORACLE_SID.ora
o spfile.ora
o init$ORACLE_SID.ora
# cur r ent l y used SPFi l es ( i f nul l , pf i l e was used)
sel ect * f r omv$par amet er wher e name = ' spf i l e'
# cr eat e pf i l e
CREATE SPFI LE=' / u01/ or acl e/ dbs/ t est _spf i l e. or a' FROM
PFI LE=' / u01/ or acl e/ dbs/ t est _i ni t . or a'
# use peci f i c spf i l e dur i ng st ar t up
STARTUP PFI LE = $ORACLE_HOME/ dbs/ i ni t DBA1. or a
Page 72 Oracle DBA Code Examples

# PFI LE can i ndi cat e t o use SPFI LE
SPFI LE = / dat abase/ st ar t up/ spf i l eDBA1. or a
In Oracle 11g
# wr i t e cur r ent val ues of i nst ance par amet er s
CREATE PFI LE FROM MEMORY;
CREATE SPFI LE FROM MEMORY;
Managing Parameters in SPFILE
- - di spl ay cur r ent val ue of a par amet er
sel ect * f r omv$par amet er wher e name = ' spf i l e'
- - par amet er val ues set i n SPFI LE
sel ect NAME, I SSPECI FI ED f r omV$SPPARAMETER wher e name l i ke ' %dest %' ;
- - i n SQL Pl us
show par amet er t ar get

- - set par amet er val ue
al t er syst emset par amet er =val ue scope=SPFI LE| MEMORY| BOTH

- - del et e a par amet er f r omSPFI Le
ALTER SYSTEM RESET undo_suppr ess_er r or s SCOPE=BOTH SI D=' node01' ;

- - Onl y sessi ons st ar t ed af t er t he st at ement i s execut ed ar e af f ect ed
- - t hi s opt i on i s a must f or t he par amet er s whose I SSYS_MODI FI ABLE col umn
- - i n V$PARAMETER i s DEFERRED. You cannot use i t , i f t he col umn val ue i s
FALSE
ALTER SYSTEM SET par amet er _name DEFERRED;

- - undocument ed par amet er s
SELECT
a. ksppi nmpar amet er , a. ksppdesc descr i pt i on,
b. ksppst vl sessi on_val ue, c. ksppst vl i nst ance_val ue
FROM x$ksppi a, x$ksppcv b, x$ksppsv c
WHERE
a. i ndx = b. i ndx
AND a. i ndx = c. i ndx
AND SUBSTR ( a. ksppi nm, 1, 1) = ' _'
ORDER BY a. ksppi nm;
Alert and Trace Files
Monitoring Alert and Trace Files
# t o obt ai n t he Locat i on of Tr ace Fi l es
col umn NAME f or mat a35
col umn VALUE f or mat a35
sel ect name, val ue f r omv$par amet er
Page 73 Oracle DBA Code Examples

wher e name i n ( ' backgr ound_dump_dest ' , ' user _dump_dest ' )

# t o set maxi mumsi ze of t r ace f i l es ( excl udi ng t he al er t f i l e)
# i n number of bl ock unl ess you sepci f y K or M
sel ect * f r omv$par amet er wher e upper ( name ) = ' MAX_DUMP_FI LE_SI ZE'
al t er sessi on set MAX_DUMP_FI LE_SI ZE=' 100M'
Page 74 Oracle DBA Code Examples

Managing Oracle Database Physical Structure
Managing Control Files
Obtaining Control File information
sel ect val ue f r omv$par amet er wher e upper ( name) = ' CONTROL_FI LES'
sel ect * f r omv$cont r ol f i l e;
sel ect * f r omv$cont r ol f i l e_r ecor d_sect i on
Creating Additional Copies, Renaming, and Relocating Control Files
1. Shut down the database.

2. Copy an existing control file to a new location, using operating system commands.

3. Edit the CONTROL_FILES parameter
CONTROL_FILES="D:\ORACLE\ORADATA\ORA11G2\CONTROL01.CTL","D:\ORACLE\ORADATA\ORA1
1G2\CONTROL02.CTL";
4. Restart the database.
Note: if you are using SPFILE, STARTUP NOMOUNT then use ALTER SYSTEM SET ..
SCOPE=SPFILE command.
Creating New Control Files
1. Make a list of all datafiles and redo log files of the database.
2. Shut down the database.
3. Back up all datafiles and redo log files of the database.
4. STARTUP NOMOUNT
5. Use the CREATE CONTROLFI LE statement:
CREATE CONTROLFI LE
SET DATABASE pr od
LOGFI LE GROUP 1 ( ' / u01/ or acl e/ pr od/ r edo01_01. l og' ,
' / u01/ or acl e/ pr od/ r edo01_02. l og' ) ,
GROUP 2 ( ' / u01/ or acl e/ pr od/ r edo02_01. l og' ,
' / u01/ or acl e/ pr od/ r edo02_02. l og' ) ,
GROUP 3 ( ' / u01/ or acl e/ pr od/ r edo03_01. l og' ,
' / u01/ or acl e/ pr od/ r edo03_02. l og' )
RESETLOGS | NORESETLOGS
DATAFI LE ' / u01/ or acl e/ pr od/ syst em01. dbf ' SI ZE 3M,
' / u01/ or acl e/ pr od/ r bs01. dbs' SI ZE 5M,
' / u01/ or acl e/ pr od/ user s01. dbs' SI ZE 5M,
' / u01/ or acl e/ pr od/ t emp01. dbs' SI ZE 5M
MAXLOGFI LES 50
MAXLOGMEMBERS 3
MAXLOGHI STORY 400
MAXDATAFI LES 200
MAXI NSTANCES 6
ARCHI VELOG;
Specify the RESETLOGS clause if you have lost any redo log groups in addition to control files.
In this case, you will need to recover from the loss of the redo logs (step 8). You must specify
the RESETLOGS clause if you have renamed the database. Otherwise, select the
NORESETLOGS clause.

Page 75 Oracle DBA Code Examples

Caution: The CREATE CONTROLFILE statement can potentially damage specified datafiles and
redo log files. Omitting a filename can cause loss of the data in that file, or loss of access to
the entire database.

6. Store a backup of the new control file on an offline storage device.
7. Edit the CONTROL_FILES initialization parameter
8. If you are renaming the database, edit the DB_NAME parameter in your instance parameter
file.
9. Recover the database if necessary.
If the new control file was created using the NORESETLOGS clause, you can recover the
database with complete, closed database recovery.
If the new control file was created using the RESETLOGS clause, you must specify USING
BACKUP CONTROL FILE in your RECOVER command.

10. If you did not perform recovery, open the database normally.
ALTER DATABASE OPEN;
If you specified RESETLOGS when creating the control file:
ALTER DATABASE OPEN RESETLOGS;

Handling Errors During CREATE CONTROLFILE
If Oracle Database sends you an error (usually error ORA-01173, ORA-01176, ORA-01177,
ORA-01215, or ORA-01216) when you attempt to mount and open the database after creating
a new control file, the most likely cause is that you omitted a file from the CREATE
CONTROLFILE statement or included one that should not have been listed.

Checking for Missing Files after Creating Control Files
Check the alert log to see if the database has detected inconsistencies between the data
dictionary and the control file.

If a datafile exists in the data dictionary but not in the new control file, the database creates
a placeholder entry in the control file under the name MISSINGnnnn, where nnnn is the file
number in decimal. MISSINGnnnn is flagged in the control file as being offline and requiring
media recovery.
o If the actual datafile corresponding to MISSINGnnnn is read-only or offline normal,
then you can make the datafile accessible by renaming MISSINGnnnn to the name
of the actual datafile.

o If MISSINGnnnn corresponds to a datafile that was not read-only or offline normal,
you must drop the tablespace containing the datafile.
Backing Up Control Files
- - copy of t he cont r ol f i l e:
ALTER DATABASE BACKUP CONTROLFI LE TO ' / or acl e/ backup/ cont r ol . bkp' ;

- - commands t o r e- cr eat e t he cont r ol f i l e:
ALTER DATABASE BACKUP CONTROLFI LE TO TRACE;
Show par amet er user _dump_dest

Manage the Size of Control Files
It is affected by MAXDATAFILES, MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, and
MAXINSTANCES parameters in the CREATE DATABASE statement. Also it is affected by
CONTROL_FILE_RECORD_KEEP_TIME
Page 76 Oracle DBA Code Examples

Multiplexing the Control File
1. Alter the SPFILE:
ALTER SYSTEM SET cont r ol _f i l es
=' $HOME/ ORADATA/ u01/ ct r l 01. ct l ' , ' $HOME/ ORADATA/ u02/ ct r l 02. ct l ' SCOPE=SPFI LE;
2. Shut down the database
3. Create additional control files:
cp $HOME/ ORADATA/ u01/ ct r l 01. ct l $HOME/ ORADATA/ u02/ ct r l 02. ct l
4. Start the database:
st ar t up
Maintaining Online Redo Log Files
Forcing Log Switches and Checkpoints
# For ci ng a l og swi t ch
ALTER SYSTEM SWI TCH LOGFI LE;
# f or ci ng checkpoi nt s i n seconds
FAST_START_MTTR_TARGET = 600
ALTER SYSTEM CHECKPOI NT;

Adding Online Redo Log File Groups
# GROUP n i s opt i onal
ALTER DATABASE ADD LOGFI LE GROUP 3
( ' / ORADATA/ u01/ l og3a. r do' , ' / ORADATA/ u02/ l og3b. r do' )
SI ZE 1M;
Adding Online Redo Log File Members
ALTER DATABASE ADD LOGFI LE MEMBER
' / ORADATA/ u04/ l og1c. r do' TO GROUP 1,
' / ORADATA/ u04/ l og2c. r do' TO GROUP 2,
' / ORADATA/ u04/ l og3c. r do' TO GROUP 3;
Dropping Online Redo Log File Groups
SELECT GROUP#, ARCHI VED, STATUS FROM V$LOG;
ALTER SYSTEM SWI TCH LOGFI LE;
ALTER DATABASE DROP LOGFI LE GROUP 3;
Dropping Online Redo Log File Members
ALTER DATABASE DROP LOGFI LE MEMBER ' $HOME/ ORADATA/ u04/ l og3c. r do' ;
Relocating and Renaming Redo Log Members
SHUTDOWN
Copy t he r edo l og f i l es t o t he new l ocat i on.
STARTUP MOUNT
Page 77 Oracle DBA Code Examples

ALTER DATABASE
RENAME FI LE ' / di ska/ l ogs/ l og1a. r do' , ' / di ska/ l ogs/ l og2a. r do'
TO ' / di skc/ l ogs/ l og1c. r do' , ' / di skc/ l ogs/ l og2c. r do' ;
ALTER DATABASE OPEN;
Verifying Blocks in Redo Log Files
# i t def aul t s t o TURE
al t er syst emset DB_BLOCK_CHECKSUM=t r ue ;
Clearing a Redo Log File
# i f DB st ops becuase l og f i l e i s cor r upt ed
ALTER DATABASE CLEAR LOGFI LE GROUP 2;
# t he r edo l og f i l e wi l l be avai l abl e even i f not ar chi ved
ALTER DATABASE CLEAR UNARCHI VED LOGFI LE GROUP 2;
Viewing Redo Log Information
SELECT * FROM V$LOG;
# STATUS: I NVALI D ( i naccessi bl e) , STALE ( i ncompl et e) , DELETED, Bl ank ( i n use)
SELECT * FROM V$LOGFI LE;
SELECT * FROM V$LOG G, V$LOGFI LE M wher e G. GROUP#=M. GROUP# or der by M. GROUP#
Managing Archived Redo Logs
Obtaining Information about Archive Log
- - i n SQL*Pl us
ARCHI VE LOG LI ST
- - t o know ar chi vel og mode of t he dat abase
sel ect LOG_MODE f r omV$DATABASE

- - hi st or i cal ar chi ved l og i nf or mat i on f r omt he cont r ol f i l e
sel ect
RECI D,
NAME,
DEST_I D,
THREAD#,
SEQUENCE#,
RESETLOGS_CHANGE#,
RESETLOGS_TI ME,
RESETLOGS_I D,
FI RST_CHANGE#,
FI RST_TI ME,
NEXT_CHANGE#,
NEXT_TI ME,
BLOCKS * BLOCK_SI ZE/ 1024/ 1024 MB ,
CREATOR,
ARCHI VED,
DELETED,
STATUS,
COMPLETI ON_TI ME,
Page 78 Oracle DBA Code Examples

END_OF_REDO,
BACKUP_COUNT,
ARCHI VAL_THREAD#,
I S_RECOVERY_DEST_FI LE,
COMPRESSED,
FAL,
BACKED_BY_VSS
f r omV$ARCHI VED_LOG;

- - i nf or mat i on about ar chi ve l og dest i nat i ons and t hei r st at us
sel ect * f r omV$ARCHI VE_DEST

- - i nf or mat i on about ARCn pr ocesses
sel ect * f r omV$ARCHI VE_PROCESSES

- - i nf or mat i on about any backup made on ar chi ved l og f i l es
sel ect * f r omV$BACKUP_REDOLOG

- - onl i ne gr oups and whi ch one t o be ar chi ved
sel ect * f r omV$LOG

- - l og hi st or y i nf or mat i on
sel ect * f r omV$LOG_HI STORY
Changing the Database Archiving Mode
sel ect l og_mode f r omv$dat abase ;

CONN / AS SYSDBA
SHUTDOWN
Back up t he dat abase
see Speci f yi ng Ar chi ve Dest i nat i ons ( next sect i on )
STARTUP MOUNT
ALTER DATABASE ARCHI VELOG; - - or NOARCHI VELOG
ALTER DATABASE OPEN;
SHUTDOWN I MMEDI ATE
Back up t he dat abase
Specifying Archive Destinations and their Options
- - t o l ocal dest i nat i ons
LOG_ARCHI VE_DEST_1 = ' LOCATI ON=/ di sk1/ ar chi ve'
LOG_ARCHI VE_DEST_1 = ' LOCATI ON=USE_DB_RECOVERY_FI LE_DEST'

- - def aul t i s OPTI ONAL, REOPEN i n seconds ( def aul t 300)
- - i f REOPEN i s omi t t ed, ARCn wi l l never open a dest i nat i on af t er a f ai l ur e
LOG_ARCHI VE_DEST_2 = ' LOCATI ON=/ di sk2/ ar chi ve MANDATORY REOPEN=600'
LOG_ARCHI VE_DEST_3 = ' LOCATI ON=/ di sk3/ ar chi ve OPTI ONAL'

- - t o a st andby db
LOG_ARCHI VE_DEST_4 = ' SERVI CE = st andby1'

- - cont r ol f i l e f or mat
Page 79 Oracle DBA Code Examples

LOG_ARCHI VE_FORMAT=t %t _s%s_r %r . ar c
Specifying the Minimum Number of Successful Destinations
al t er syst emset LOG_ARCHI VE_MI N_SUCCEED_DEST=1
Controlling Archiving to a Destination
al t er syst emset LOG_ARCHI VE_DEST_STATE_2 = DEFER
al t er syst emset LOG_ARCHI VE_DEST_STATE_2 = ENABLE
Controlling Trace Output Generated by the Archivelog Process
LOG_ARCHIVE_TRACE takes combination of:
0 Disable archivelog tracing. This is the default.
1 Track archival of redo log file.
2 Track archival status for each archivelog destination.
4 Track archival operational phase.
8 Track archivelog destination activity.
16 Track detailed archivelog destination activity.
32 Track archivelog destination parameter modifications.
64 Track ARCn process state activity.
128 Track FAL (fetch archived log) server related activities.
256 Supported in a future release.
512 Tracks asynchronous LGWR activity.
1024 RFS physical client tracking.
2048 ARCn/RFS heartbeat tracking.
4096 Track real-time apply

- - LOG_ARCHI VE_TRACE def aul t s t o 0
sel ect val ue f r omv$par amet er wher e upper ( name) =' LOG_ARCHI VE_TRACE' ;
- - dat abase must be mount ed but not open.
ALTER SYSTEM SET LOG_ARCHI VE_TRACE=12;

Managing Tablespaces
Obtaining Tablespace Information
- - t abl espace si ze usage r epor t ( f or l ar ge db ( >100GB) , i t t akes l ong t i me)
BREAK ON REPORT
COMPUTE SUM OF t bsp_si ze ON REPORT
comput e SUM OF used ON REPORT
comput e SUM OF f r ee ON REPORT
COL t bspname FORMAT a20 HEADI NG ' Tabl espace Name'
COL t bsp_si ze FORMAT 999, 999 HEADI NG ' Si ze| ( MB) '
COL used FORMAT 999, 999 HEADI NG ' Used| ( MB) '
COL f r ee FORMAT 999, 999 HEADI NG ' Fr ee| ( MB) '
COL pct _used FORMAT 999 HEADI NG' %Used'

SELECT df . t abl espace_name t bspname,
sum( df . byt es) / 1024/ 1024 t bsp_si ze,
nvl ( sum( e. used_byt es) / 1024/ 1024, 0) used,
nvl ( sum( f . f r ee_byt es) / 1024/ 1024, 0) f r ee,
nvl ( ( sum( e. used_byt es) *100) / sum( df . byt es) , 0) pct _used
FROM DBA_DATA_FI LES df ,
Page 80 Oracle DBA Code Examples

( SELECT f i l e_i d,
SUM( nvl ( byt es, 0) ) used_byt es
FROM dba_ext ent s
GROUP BY f i l e_i d) e,
( SELECT MAX( byt es) f r ee_byt es, f i l e_i d
FROM dba_f r ee_space
GROUP BY f i l e_i d) f
WHERE e. f i l e_i d( +) = df . f i l e_i d
AND df . f i l e_i d = f . f i l e_i d( +)
GROUP BY df . t abl espace_name
ORDER BY 5 DESC

- - f or a speci f i c t abl espace:
SELECT df . t abl espace_name t bspname,
sum( df . byt es) / 1024/ 1024 t bsp_si ze,
nvl ( sum( e. used_byt es) / 1024/ 1024, 0) used,
nvl ( sum( f . f r ee_byt es) / 1024/ 1024, 0) f r ee,
nvl ( ( sum( e. used_byt es) *100) / sum( df . byt es) , 0) pct _used
FROM DBA_DATA_FI LES df ,
( SELECT f i l e_i d,
SUM( nvl ( byt es, 0) ) used_byt es
FROM dba_ext ent s
WHERE TABLESPACE_NAME=' REC_DATA'
GROUP BY f i l e_i d) e,
( SELECT MAX( byt es) f r ee_byt es, f i l e_i d
FROM dba_f r ee_space
WHERE TABLESPACE_NAME=' REC_DATA'
GROUP BY f i l e_i d) f
WHERE e. f i l e_i d( +) = df . f i l e_i d
AND df . f i l e_i d = f . f i l e_i d( +)
AND TABLESPACE_NAME=' REC_DATA'
GROUP BY df . t abl espace_name;
- - *************************************************************

- - t abl espace si zes ( wi t hout get t i ng used and f r ee space) ( qui ck r esponse) :
SELECT DF. TABLESPACE_NAME TBSPNAME,
ROUND( SUM( DF. BYTES) / 1024/ 1024/ 1024, 2) GB,
COUNT( FI LE_NAME) DATAFI LES
FROM DBA_DATA_FI LES DF
GROUP BY ROLLUP( DF. TABLESPACE_NAME )
ORDER BY 1


-- free space in temp tablespaces:
sel ect sum( f r ee_bl ocks)
f r omgv$sor t _segment
wher e t abl espace_name = ' USER_TEMP' ;


-- tablespace info from control file
sel ect TS#, NAME, I NCLUDED_I N_DATABASE_BACKUP,
BI GFI LE, FLASHBACK_ON, ENCRYPT_I N_BACKUP
f r om V$TABLESPACE;


-- descriptions of tablespaces
sel ect TABLESPACE_NAME, BLOCK_SI ZE, I NI TI AL_EXTENT,
NEXT_EXTENT NEXT_EXTENT_SI ZE, MI N_EXTENTS, MAX_EXTENTS,
Page 81 Oracle DBA Code Examples

PCT_I NCREASE, MI N_EXTLEN, STATUS,
CONTENTS, LOGGI NG, FORCE_LOGGI NG,
EXTENT_MANAGEMENT, ALLOCATI ON_TYPE, PLUGGED_I N,
SEGMENT_SPACE_MANAGEMENT, DEF_TAB_COMPRESSI ON, RETENTI ON
f r omDBA_TABLESPACES


-- segments contained in tablespaces
sel ect OWNER, SEGMENT_NAME, PARTI TI ON_NAME, SEGMENT_TYPE, S. TABLESPACE_NAME,
HEADER_FI LE, HEADER_BLOCK, S. BYTES/ 1024/ 1024 SEGMENT_SI ZE_MB,
D. BLOCKS SEGMENT_BLOCKS, EXTENTS, S. I NI TI AL_EXTENT, S. NEXT_EXTENT
NEXT_EXTENT_SI ZE, S. MI N_EXTENTS, S. MAX_EXTENTS, S. PCT_I NCREASE,
FREELI STS, FREELI ST_GROUPS, D. RELATI VE_FNO, D. FI LE_NAME
f r omDBA_SEGMENTS S, DBA_TABLESPACES T, DBA_DATA_FI LES D
wher e S. TABLESPACE_NAME = T. TABLESPACE_NAME AND T. TABLESPACE_NAME =
D. TABLESPACE_NAME
AND S. RELATI VE_FNO = D. RELATI VE_FNO
AND T. TABLESPACE_NAME NOT I N ( ' SYSAUX' , ' SYSTEM' )
or der BY S. TABLESPACE_NAME

-- extents contained by tablespaces
SELECT EXTENT_I D, E. BLOCK_I D, E. BYTES/ 1024 EXTENT_SI ZE_KB,
E. OWNER, E. SEGMENT_NAME, E. PARTI TI ON_NAME,
E. SEGMENT_TYPE, D. FI LE_NAME, S. TABLESPACE_NAME, HEADER_FI LE,
HEADER_BLOCK SEG_HEADER_BLOCK, S. BYTES/ 1024/ 1024 SEGMENT_SI ZE_MB, D. BLOCKS
SEGMENT_BLOCKS, EXTENTS SEG_EXTENTS
FROM DBA_EXTENTS E, DBA_SEGMENTS S, DBA_DATA_FI LES D
WHERE E. OWNER=S. OWNER AND E. SEGMENT_NAME = S. SEGMENT_NAME
AND NVL( E. PARTI TI ON_NAME, ' 0' ) = NVL( S. PARTI TI ON_NAME, ' 0' )
AND E. SEGMENT_TYPE = S. SEGMENT_TYPE
AND E. FI LE_I D = D. FI LE_I D
AND S. TABLESPACE_NAME NOT I N ( ' SYSAUX' , ' SYSTEM' )
ORDER BY E. SEGMENT_NAME, E. OWNER, E. PARTI TI ON_NAME, E. EXTENT_I D


-- free extents within tablespaces
SELECT F. TABLESPACE_NAME, F. FI LE_I D, F. BLOCK_I D,
F. BYTES/ 1024/ 1024 FREE_MB, D. FI LE_NAME
FROM DBA_FREE_SPACE F, DBA_DATA_FI LES D
WHERE F. FI LE_I D = D. FI LE_I D
UNI ON
SELECT F. TABLESPACE_NAME, TO_NUMBER( ' ' ) AS FI LE_I D, TO_NUMBER( ' ' ) AS BLOCK_I D,
SUM( F. BYTES/ 1024/ 1024) FREE_MB, TO_CHAR( ' ' ) AS FI LE_NAME
FROM DBA_FREE_SPACE F
GROUP BY F. TABLESPACE_NAME, TO_NUMBER( ' ' ) , TO_NUMBER( ' ' ) , TO_CHAR( ' ' )
ORDER BY TABLESPACE_NAME


-- data files (from control file)
SELECT FI LE#, T. NAME TABLESPACE_NAME, D. NAME FI LENAME,
CREATI ON_CHANGE#, CREATI ON_TI ME, RFI LE#, STATUS,
ENABLED, CHECKPOI NT_CHANGE#, CHECKPOI NT_TI ME,
UNRECOVERABLE_CHANGE#, UNRECOVERABLE_TI ME, LAST_CHANGE#,
LAST_TI ME, OFFLI NE_CHANGE#, ONLI NE_CHANGE#,
ONLI NE_TI ME, BYTES/ 1024/ 1024 FI LESI ZE_MB, BLOCKS,
CREATE_BYTES, BLOCK_SI ZE,
PLUGGED_I N, BLOCK1_OFFSET, AUX_NAME
FROM V$DATAFILE D, V$TABLESPACE T
WHERE D. TS# = T. TS#
ORDER BY TABLESPACE_NAME, D. RFI LE#


-- data files
Page 82 Oracle DBA Code Examples

sel ect FI LE_NAME, FI LE_I D, T. TABLESPACE_NAME,
F. STATUS FI LE_STATUS,
RELATI VE_FNO,
AUTOEXTENSI BLE,
ROUND( BYTES/ 1024/ 1024, 2) FI LESI ZE_MB,
ROUND( MAXBYTES/ 1024/ 1024, 2) MAXSI ZE_MB,
ROUND( ( I NCREMENT_BY*T. BLOCK_SI ZE) / 1024/ 1024, 2) AUTOEXTENSI ON_SI ZE_MB,
ROUND( USER_BYTES/ 1024/ 1024, 2) AVAI LABLE_FOR_DATA_MB - - r emai ni ng si ze used
f r omDBA_DATA_FILES F, DBA_TABLESPACES T - - f or st or i ng met adat a
wher e F. TABLESPACE_NAME = T. TABLESPACE_NAME
or der BY TABLESPACE_NAME, F. RELATI VE_FNO


-- tempfiles included in tablespaces
sel ect M. NAME TEMPFI LE, FI LE#, T. NAME TABLESPACE_NAME,
CREATI ON_TI ME, M. TS#, RFI LE#,
STATUS, ENABLED, BYTES,
BLOCKS, CREATE_BYTES, BLOCK_SI ZE
f r om V$TEMPFILE M, V$TABLESPACE T
wher e M. TS# = T. TS#
or der by T. NAME

sel ect FI LE_NAME, FI LE_I D, T. TABLESPACE_NAME,
F. STATUS FI LE_STATUS,
RELATI VE_FNO,
AUTOEXTENSI BLE,
ROUND( BYTES/ 1024/ 1024, 2) FI LESI ZE_MB,
ROUND( MAXBYTES/ 1024/ 1024, 2) MAXSI ZE_MB,
ROUND( ( I NCREMENT_BY*T. BLOCK_SI ZE) / 1024/ 1024, 2) AUTOEXTENSI ON_SI ZE_MB
f r omDBA_TEMP_FI LES F, DBA_TABLESPACES
wher e F. TABLESPACE_NAME = T. TABLESPACE_NAME
or der BY TABLESPACE_NAME, F. RELATI VE_FNO


-- extents in all locally managed temporary tablespaces
SELECT E. TABLESPACE_NAME, E. FI LE_I D,
BLOCK_I D BEGI N_BLOCK#,
ROUND( E. BYTES/ 1024, 2) EXTENT_SI ZE_KB,
E. BLOCKS, OWNER
FROM V$TEMP_EXTENT_MAP E


-- tablespace groups
sel ect GROUP_NAME, TABLESPACE_NAME
f r omDBA_TABLESPACE_GROUPS
or der BY TABLESPACE_NAME

-- user qoutas
SELECT
USERNAME, TABLESPACE_NAME, BYTES/ 1024 SI ZE_KB,
DECODE( MAX_BYTES, - 1, - 1, MAX_BYTES/ 1024/ 1024) MAX_MB
FROM DBA_TS_QUOTAS
ORDER BY USERNAME


-- diskspace usage by USER
sel ect owner , r ound( sum( byt es) / 1024/ 1024, 2) space_i n_mb
f r omdba_segment s
gr oup by owner
WHERE OWNER NOT I N ( ' SYSTEM' , ' SYSMAN' ,
' SYS' , ' WKSYS' , ' WK_TEST' , ' WMSYS' , ' XDB' , ' OUTLN' , ' PERFSTAT' , ' OLAPSYS' , ' ORDSYS' , ' M
DSYS' , ' EXFSYS' , ' DMSYS' , ' CTXSYS' , ' REPTEST' , ' SCOTT' , ' RMAN' )
Page 83 Oracle DBA Code Examples

or der by r ound( sum( byt es) / 1024/ 1024, 2) desc;


-- user temporary usage
- - SEGTYPE: SORT, HASH, DATA, I NDEX, LOB_DATA, LOB_I NDEX
SELECT USERNAME, SESSI ON_NUM SESSI ON_SN,
SQLADDR, SQLHASH, SQL_I D,
TABLESPACE,
SEGTYPE, SEGFI LE# I NI T_EXTENT_FI LE#, SEGBLK#
I NI T_EXTENT_BLK#, EXTENTS, BLOCKS, SEGRFNO#
FROM V$TEMPSEG_USAGE
Creating a Locally Managed Tablespace
CREATE TABLESPACE l mt bsb DATAFI LE ' / u02/ or acl e/ dat a/ l mt bsb01. dbf ' SI ZE 50M
EXTENT MANAGEMENT AUTOALLOCATE;
CREATE TABLESPACE l mt bsb DATAFI LE ' / u02/ or acl e/ dat a/ l mt bsb01. dbf ' SI ZE 50M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K; - - def aul t 1MB

- - cr eat i ng a t abl espace i n an ASM di skgr oup
CREATE TABLESPACE sampl e DATAFI LE ' +dgr oup1' ;
CREATE TABLESPACE sat bs DATAFI LE ' +DATA' si ze 50m;
Specifying Segment Space Management
CREATE TABLESPACE l mt bsb DATAFI LE ' / u02/ or acl e/ dat a/ l mt bsb01. dbf ' SI ZE 50M
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO; - - t hough i t ' s t he def aul t
- - t he ot her opt i on i s MANUAL
Adding Space to Tablespace
ALTER TABLESPACE t est 01 ADD DATAFI LE ' . . ' SI ZE 1000M;
ALTER DATABASE DATAFI LE ' ' RESI ZE 500m;
Specifying Nonstandard Block Sizes for Tablespaces
- - must be 2KB, 4KB, 8KB, 16KB, or 32KB.
- - r equi r ement
set DB_CACHE_SI ZE, DB_nK_CACHE_SI ZE
sel ect val ue/ 1024 KB f r omv$par amet er wher e name=' db_bl ock_si ze' ;
CREATE TABLESPACE l mt bsb DATAFI LE ' / u02/ or acl e/ dat a/ l mt bsb01. dbf ' SI ZE 50M
EXTENT MANAGEMENT LOCAL UNI FORM SI ZE 128K BLOCKSIZE 8K;
Using Bigfile Tablespace (BFT)
Oracle recommends that you change the extent allocation policy from AUTOALLOCATE,
which is the default, to UNIFORM and set a very high extent size.
sel ect TABLESPACE_NAME, BI GFI LE f r omDBA_TABLESPACES or der by BI GFI LE;
- - use Bi gFi l e t abl espaces onl y wi t h ASM or RAI D vol ume manager .
- - i t can t ake up t o 4G bl ocks. wi t h 8K bl ocks = 32 t er abyt e dat af i l e
CREATE BIGFILE TABLESPACE bi gt bs - - t he ot her opt i on SMALLFI LE
DATAFI LE ' / u02/ or acl e/ dat a/ bi gt bs01. dbf ' SI ZE 50G - - T i s accept abl e
EXTENT MANAGEMENT LOCAL UNI FORM SI ZE 65536K; - - def aul t 1m
ALTER TABLESPACE bi gt bs RESIZE 80G;
Page 84 Oracle DBA Code Examples

ALTER TABLESPACE bi gt bs AUTOEXTEND ON NEXT 20G;
- - wi t h t hi s si t t i ng, by def aul t al l t bs cr eat ed l at er wi l l be BFT
CREATE DATABASE SET DEFAULT BI GFI LE tablespace - - t he ot her opt i on SMALLFI LE
ALTER TABLESPACE SET DEFAULT BI GFI LE TABLESPACE;
SELECT pr oper t y_val ue FROM dat abase_pr oper t i es
WHERE pr oper t y_name=' DEFAULT_TBS_TYPE' ;

Using Temporary Tablespace
Oracle recommends creating temporary tablespaces with multiples-of-64KB extent sizes.
For large data warehousing, make it 1MB.
sel ect * f r omV$TEMPFI LE;
sel ect * f r omDBA_TEMP_FI LES;

CREATE TEMPORARY TABLESPACE l mt emp TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp01. dbf '
SI ZE 20M REUSE
EXTENT MANAGEMENT LOCAL UNI FORM SI ZE 16M; - - def aul t i s 1M ( AUTOALLOCATE not
al l owed)

CREATE BIGFILE TABLESPACE bi gt bs
TEMPFI LE ' / u02/ or acl e/ dat a/ bi gt bs01. dbf ' SI ZE 50G
ALTER TABLESPACE l mt emp ADD TEMPFILE ' / u02/ or acl e/ dat a/ l mt emp02. dbf ' SI ZE 18M
REUSE;

- - doesn' t appl y on def aul t t empor ar y t abl espace
ALTER TABLESPACE l mt emp TEMPFI LE OFFLI NE;
ALTER TABLESPACE l mt emp TEMPFI LE ONLI NE;
ALTER DATABASE TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp02. dbf ' OFFLINE;
ALTER DATABASE TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp02. dbf ' ONLINE;
ALTER DATABASE TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp02. dbf ' RESIZE 18M;

- - t he t abl espace i sn' t dr opped
ALTER DATABASE TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp02. dbf ' DROP I NCLUDI NG
DATAFI LES;
Renaming a Tempfile
ALTER DATABASE TEMPFI LE ' C: \ ORACLE\ ORADATA\ ORCL\ TEMP02. DBF' OFFLI NE;
r en C: \ ORACLE\ ORADATA\ ORCL\ TEMP02. DBF TEMP03. DBF
ALTER DATABASE RENAME FI LE ' C: \ ORACLE\ ORADATA\ ORCL\ TEMP02. DBF' TO
' C: \ ORACLE\ ORADATA\ ORCL\ TEMP03. DBF' ;
ALTER DATABASE TEMPFI LE ' C: \ ORACLE\ ORADATA\ ORCL\ TEMP03. DBF' ONLI NE;
Shrinking Temporary Tablespace
ALTER TABLESPACE t emp SHRI NK SPACE KEEP 1000M;
ALTER TABLESPACE t emp SHRI NK SPACE TEMPFI LE t empf i l e
' / u01/ app/ or acl e/ or adat a/ pr od1/ t emp02. dbf ' KEEP 100m;
SELECT f i l e#, name, byt es/ 1024/ 1024 mb FROM v$t empf i l e;
Page 85 Oracle DBA Code Examples

Using Default Temporary Tablespace
ALTER DATABASE DEFAULT TEMPORARY TABLESPACE t empt bs02; - - can be t emp t bs gr p
SELECT PROPERTY_NAME, PROPERTY_VALUE
FROM dat abase_pr oper t i es
WHERE pr oper t y_name=' DEFAULT_TEMP_TABLESPACE' ;
Using Temporary Tablespace Groups
CREATE TEMPORARY TABLESPACE l mt emp2 TEMPFI LE ' / u02/ or acl e/ dat a/ l mt emp201. dbf '
SI ZE 50M TABLESPACE GROUP group1;
ALTER TABLESPACE l mt emp TABLESPACE GROUP group2;
- - r emove i t f r oma gr oup
ALTER TABLESPACE l mt emp3 TABLESPACE GROUP '';
- - Assi gni ng a Tabl espace Gr oup as t he Def aul t Tempor ar y Tabl espace
ALTER DATABASE mydb DEFAULT TEMPORARY TABLESPACE group2;
sel ect GROUP_NAME, TABLESPACE_NAME
f r omDBA_TABLESPACE_GROUPS
or der BY TABLESPACE_NAME
Suppressing Redo Generation for a Tablespace
CREATE TABLESPACE . . NOLOGGI NG;
Controlling Tablespaces Availability
- - NORMAL, TEMPORARY, I MMEDI ATE ( not possi bl e i n NOARCHI VELOG)
ALTER TABLESPACE user s OFFLINE NORMAL;
- - medi a r ecover y r equi r ed i f i t was of f l i ne usi ng TEMPORARY or I MMEDI ATE
ALTER TABLESPACE user s ONLINE;
Using Read-Only Tablespaces
- - backup t he t abl espace af t er maki ng i t r ead onl y
- - i t wai t s f or al l t r ansact i ons st ar t ed bef or e
ALTER TABLESPACE f l i ght s READ ONLY;
- - t o l i st bl ocki ng t r ansact i ons:
SELECT SQL_TEXT, SADDR
FROM V$SQLAREA, V$SESSI ON
WHERE V$SQLAREA. ADDRESS = V$SESSI ON. SQL_ADDRESS
AND SQL_TEXT LI KE ' al t er t abl espace%' ;
- - al l t r ansact i ons on t op of SADDR r et uned by pr evi ous st at ement
- - ar e bl ocki ng t r ansact i ons
SELECT T. SES_ADDR, T. START_SCNB, S. USERNAME, S. MACHI NE
FROM V$TRANSACTI ON T, V$SESSI ON S
WHERE T. SES_ADDR = S. SADDR
ORDER BY START_SCNB;
- - back t o r ead wr i t e
ALTER TABLESPACE flights READ WRITE;
Renaming Tablespaces
ALTER TABLESPACE user s RENAME TO user st s;
Default Permanent Tabelspace
SELECT pr oper t y_val ue FROM dat abase_pr oper t i es WHERE
Page 86 Oracle DBA Code Examples

pr oper t y_name=' DEFAULT_PERMANENT_TABLESPACE' ;
ALTER DATABASE DEFAULT TABLESPACE user s;
Dropping Tablespaces
DROP TABLESPACE user s I NCLUDI NG CONTENTS;
DROP TABLESPACE t est 01 CASCADE CONSTRAI NTS;
DROP TABLESPACE user s I NCLUDI NG CONTENTS CASCADE CONSTRAI NTS;
DROP TABLESPACE user s I NCLUDI NG CONTENTS AND DATAFI LES;
Managing the SYSAUX Tablespace
A typical system with an average of 30 concurrent active sessions may require approximately
200 to 300 MB of space for its AWR data.
- - t o moni t or i s occupant s
- - t o know whi ch pr ocedur e t o use t o move an occupant
SELECT OCCUPANT_NAME , OCCUPANT_DESC , SCHEMA_NAME , MOVE_PROCEDURE
, MOVE_PROCEDURE_DESC , SPACE_USAGE_KBYTES FROM V$SYSAUX_OCCUPANTS
Diagnosing and Repairing Locally Managed Tablespace Problems
Verifying the Integrity of Segments Created in ASSM Tablespaces.
Use DBMS_SPACE_ADMIN.ASSM_SEGMENT_VERIFY.
If ASSM is disabled, use SEGMENT_VERIFY.
After execution, check sid_ora_process_ID.trc in USER_DUMP_DEST.
The parameter verify_option takes one of the following constants:
o SEGMENT_VERIFY_DEEP (9)
o SEGMENT_VERIFY_BASIC (10) default
o SEGMENT_VERIFY_SPECIFIC (11) then the attrib parameter is considered.
attrib takes one of the following constants:
o HWM_CHECK (12) checks whether high water mark information is accurate.
o BMB_CHECK (13) checks whether space bitmap blocks have correct backpointers to
the segment header.
o SEG_DICT_CHECK (14) checks whether dictionary information for segment is
accurate.
o EXTENT_TS_BITMAP_CHECK (15) checks whether extent maps are consistent with file
level bitmaps.
o DB_BACKPOINTER_CHECK (16) checks whether datablocks have correct backpointers
to the space metadata blocks.
o EXTENT_SEGMENT_BITMAP_CHECK (17) checks whether extent map in the segment
match with the bitnaps in the segment.
o BITMAPS_CHECK (18) checks whether space bitmap blocks are accurate.
decl ar e
v_segname var char 2( 100) : = ' EMPLOYEES' ;
v_segowner var char 2( 100) : =' HR' ;
v_segt ype var char 2( 100) : =' TABLE' ;
v_t bs var char 2( 100) ;
Page 87 Oracle DBA Code Examples

begi n

sel ect t abl espace_name
i nt o v_t bs
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner
and segment _t ype=v_segt ype;

DBMS_SPACE_ADMIN.ASSM_SEGMENT_VERIFY (
segment _owner =>v_segowner ,
segment _name =>v_segname,
segment _t ype =>v_segt ype,
par t i t i on_name =>' ' ,
ver i f y_opt i on => DBMS_SPACE_ADMI N. SEGMENT_VERI FY_DEEP
) ;
end;
/

- - Check si d_or a_pr ocess_I D. t r c i n USER_DUMP_DEST
sel ect val ue f r omv$par amet er wher e upper ( name) =' USER_DUMP_DEST'

decl ar e
v_segname var char 2( 100) : = ' EMPLOYEES' ;
v_segowner var char 2( 100) : =' HR' ;
v_segt ype var char 2( 100) : =' TABLE' ;
v_t bs var char 2( 100) ;
begi n

sel ect t abl espace_name
i nt o v_t bs
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner
and segment _t ype=v_segt ype;

DBMS_SPACE_ADMIN.ASSM_SEGMENT_VERIFY (
segment _owner =>v_segowner ,
segment _name =>v_segname,
segment _t ype =>v_segt ype,
par t i t i on_name =>' ' ,
ver i f y_opt i on => DBMS_SPACE_ADMI N. SEGMENT_VERI FY_SPECI FI C,
at t r i b => DBMS_SPACE_ADMI N. BMB_CHECK
) ;
end;
/

- - Check si d_or a_pr ocess_I D. t r c i n USER_DUMP_DEST
sel ect val ue f r omv$par amet er wher e upper ( name) =' USER_DUMP_DEST'
Checking Consistency of Segment Extent Map with Tablespace File Bitmaps
Use ASSM_SEGMENT_VERIFY to segment residing in a tablespace with automatic segment
space management enabled and SEGMENT_VERIFY when it is disabled.
After execution, check sid_ora_process_ID.trc in USER_DUMP_DEST.
conn sys as sysdba
decl ar e
v_segname var char 2( 100) : = ' EMPLOYEES' ;
v_segowner var char 2( 100) : =' HR' ;
Page 88 Oracle DBA Code Examples

v_t bs var char 2( 100) ;
v_f no number ;
v_r f no number ;
v_hdr number ;
begi n
- - r et r ei ve t abl espace name, absol ut e f i l e number
sel ect t abl espace_name, header _f i l e, header _bl ock
i nt o v_t bs, v_f no, v_hdr
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner ;

sel ect r el at i ve_f no
i nt o v_r f no
f r omdba_dat a_f i l es wher e t abl espace_name = v_t bs and f i l e_i d=v_f no;

DBMS_SPACE_ADMIN.SEGMENT_VERIFY(
t abl espace_name =>v_t bs,
header _r el at i ve_f i l e =>v_r f no,
header _bl ock =>v_hdr ,
ver i f y_opt i on =>dbms_space_admi n. SEGMENT_VERI FY_EXTENTS_GLOBAL - -
def aul t SEGMENT_VERI FY_EXTENTS
) ;
end;
/
- - Check si d_or a_pr ocess_I D. t r c i n USER_DUMP_DEST
sel ect val ue f r omv$par amet er wher e upper ( name) =' USER_DUMP_DEST'
Verifying the Integrity of ASSM Tablespaces
Use DBMS_SPACE_ADMIN.ASSM_TABLESPACE_VERIFY
If ASSM is disabled, use TABLESPACE_VERIFY
After execution, check sid_ora_process_ID.trc in USER_DUMP_DEST.
The parameter ts_option takes one of the following constants:
o TS_VERIFY_BITMAPS (19) (Default) The bitmaps are verified against the extents. This
will detect bits that are marked used or free wrongly and will also detect multiple
allocation of extents. The file metadata will be validated against file$ and control file.
o TS_VERIFY_DEEP (20) verifies the file bitmaps as well perform checks on all the
segments.
o TS_SEGMENTS (21) This option is used to invoke SEGMENT_VERIFY on all the
segments in the tablespace.
segment_option: when the TABLESPACE_VERIFY_SEGMENTS or
TABLESPACE_VERIFY_DEEP is selected, the SEGMENT_OPTION can be specified optionally.
When TS_VERIFY_SEGMENTS is specified, segment_option can be one of the following:
o SEGMENT_VERIFY_BASIC (9)
o SEGMENT_VERIFY_DEEP (10)
The value of segment_option is NULL when TS_VERIFY_DEEP or TS_VERIFY_BASIC is
specified.
After execution, check sid_ora_process_ID.trc in USER_DUMP_DEST
conn sys as sysdba

sel ect name f r omv$t abl espace or der by name;

begi n
Page 89 Oracle DBA Code Examples

DBMS_SPACE_ADMI N. ASSM_TABLESPACE_VERIFY(
t abl espace_name =>' EXAMPLE' ,
t s_opt i on => DBMS_SPACE_ADMI N. TS_VERI FY_DEEP,
segment _opt i on =>NULL) ;
end;
/

- - Check si d_or a_pr ocess_I D. t r c i n USER_DUMP_DEST
sel ect val ue f r omv$par amet er wher e upper ( name) =' USER_DUMP_DEST'
Marking the Segment Corrupt or Valid
corrupt_option takes one of the following:
o SEGMENT_MARK_CORRUPT (default)
o SEGMENT_MARK_VALID
conn sys as sysdba

decl ar e
v_segname var char 2( 100) : = ' EMPLOYEES' ;
v_segowner var char 2( 100) : =' HR' ;
v_t bs var char 2( 100) ;
v_f no number ;
v_r f no number ;
v_hdr number ;
begi n
- - r et r ei ve t abl espace name, absol ut e f i l e number
sel ect t abl espace_name, header _f i l e, header _bl ock
i nt o v_t bs, v_f no, v_hdr
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner ;

sel ect r el at i ve_f no
i nt o v_r f no
f r omdba_dat a_f i l es
wher e t abl espace_name = v_t bs and f i l e_i d=v_f no;

DBMS_SPACE_ADMI N. SEGMENT_CORRUPT (
t abl espace_name =>v_t bs,
header _r el at i ve_f i l e =>v_r f no,
header _bl ock =>v_hdr ,
cor r upt _opt i on =>DBMS_SPACE_ADMI N. SEGMENT_MARK_CORRUPT) ;
end;
Dropping a Corrupted Segment
Use SEGMENT_DROP_CORRUPT to drop a segment currently marked corrupt (without
reclaiming space). The space for the segment is not released, and it must be fixed by
using the TABLESPACE_FIX_BITMAPS Procedure or the TABLESPACE_REBUILD_BITMAPS
Procedure.
If the segment state is valid, the procedure returns ORA-03211 error.
conn sys as sysdba

decl ar e
v_segname var char 2( 100) : = ' EMP' ;
v_segowner var char 2( 100) : =' HR' ;
v_t bs var char 2( 100) ;
v_f no number ;
Page 90 Oracle DBA Code Examples

v_r f no number ;
v_hdr number ;
begi n
- - r et r ei ve t abl espace name, absol ut e f i l e number
sel ect t abl espace_name, header _f i l e, header _bl ock
i nt o v_t bs, v_f no, v_hdr
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner ;

sel ect r el at i ve_f no
i nt o v_r f no
f r omdba_dat a_f i l es
wher e t abl espace_name = v_t bs and f i l e_i d=v_f no;

DBMS_SPACE_ADMI N. SEGMENT_DROP_CORRUPT(
t abl espace_name =>v_t bs,
header _r el at i ve_f i l e =>v_r f no,
header _bl ock => v_hdr ) ;
end;
Dumping a Segment Header and Bitmap Blocks
Use DBMS_SPACE_ADMIN.SEGMENT_DUMP
The dump file named sid_ora_process_id.trc is generated in the location specified in the
USER_DUMP_DEST
conn sys as sysdba
decl ar e
v_segname var char 2( 100) : = ' NAMES' ;
v_segowner var char 2( 100) : =' HR' ;
v_t bs var char 2( 100) ;
v_f no number ;
v_r f no number ;
v_hdr number ;
begi n
- - r et r ei ve t abl espace name, absol ut e f i l e number
sel ect t abl espace_name, header _f i l e, header _bl ock
i nt o v_t bs, v_f no, v_hdr
f r om dba_segment s
wher e segment _name=v_segname and owner =v_segowner ;

sel ect r el at i ve_f no
i nt o v_r f no
f r omdba_dat a_f i l es
wher e t abl espace_name = v_t bs and f i l e_i d=v_f no;

DBMS_SPACE_ADMIN.SEGMENT_DUMP(
t abl espace_name =>v_t bs,
header _r el at i ve_f i l e =>v_r f no,
header _bl ock =>v_hdr ,
dump_opt i on => DBMS_SPACE_ADMI N. SEGMENT_DUMP_EXTENT_MAP) ;
end;
Marking a DBA Range in Bitmap as Free or Used
The procedure TABLESPACE_FIX_BITMAPS marks the appropriate DBA range (extent) as
free or used in bitmap.
The BEGIN and END blocks should be in extent boundary and should be extent multiple.
fix_option takes one of the following
Page 91 Oracle DBA Code Examples

o TABLESPACE_EXTENT_MAKE_FREE
o TABLESPACE_EXTENT_MAKE_USED
conn sys as sysdba
DBMS_SPACE_ADMI N. TABLESPACE_FIX_BITMAPS (
t abl espace_name =>' EXAMPLE' ,
dbar ange_r el at i ve_f i l e =>4,
dbar ange_begi n_bl ock =>33,
dbar ange_end_bl ock =>83,
f i x_opt i on =>DBMS_SPACE_ADMI N. TABLESPACE_EXTENT_MAKE_FREE) ;
Rebuilding the Appropriate Bitmap
conn sys
begi n
DBMS_SPACE_ADMI N. TABLESPACE_REBUI LD_BI TMAPS (
t abl espace_name =>' EXAMPLE' ,
bi t map_r el at i ve_f i l e =>NULL, - - al l f i l es
bi t map_bl ock =>NULL) ; - - Bl ock number of bi t map bl ock t o r ebui l d
- - NULL = al l bl ocks
end;
Rebuilding Quotas for Given Tablespace
conn sys
exec DBMS_SPACE_ADMI N. TABLESPACE_REBUI LD_QUOTAS( ' USERS' ) ;
Migrating from a Dictionary-Managed to a Locally Managed Tablespace
- - Thi s oper at i on i s done onl i ne, but space management oper at i ons ar e bl ocked
- - ASSM won' t be act i ve on mi gr at ed obj ect s
conn sys
EXEC DBMS_SPACE_ADMI N. TABLESPACE_MI GRATE_TO_LOCAL ( ' USERS' ) ;

- - anot her way r equi r i ng t abl e l ock ( bet t er )
ALTER TABLE emp MOVE TABLESPACE t bsp_new;
ALTER I NDEX emp_pk_i dx REBUI LD TABLESPACE t bsp_i dx_new;

Fixing the State of the Segments in A Tablespace
Use TABLESPACE_FIX_SEGMENT_STATES to fix the state of the segments in a tablespace in
which migration was aborted.
conn sys
EXECUTE DBMS_SPACE_ADMI N. TABLESPACE_FI X_SEGMENT_STATES( ' TS1' )
Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap)
The TABLESPACE_VERIFY procedure discovers that a segment has allocated blocks that are
marked free in the bitmap, but no overlap between segments is reported.
In this scenario, perform the following tasks:
1. Call the SEGMENT_DUMP procedure to dump the ranges that the administrator allocated to
the segment.
2. For each range, call the TABLESPACE_FIX_BITMAPS procedure with the
TABLESPACE_EXTENT_MAKE_USED option to mark the space as used.
Page 92 Oracle DBA Code Examples

3. Call TABLESPACE_REBUILD_QUOTAS to fix up quotas.
Scenario 2: Dropping a Corrupted Segment
You cannot drop a segment because the bitmap has segment blocks marked "free". The
system has automatically marked the segment corrupted. In this scenario, perform the
following tasks:
1. Call the SEGMENT_VERIFY procedure with the SEGMENT_VERIFY_EXTENTS_GLOBAL option.
If no overlaps are reported, then proceed with steps 2 through 5.
2. Call the SEGMENT_DUMP procedure to dump the DBA ranges allocated to the segment.
3. For each range, call TABLESPACE_FIX_BITMAPS with the
TABLESPACE_EXTENT_MAKE_FREE option to mark the space as free.
4. Call SEGMENT_DROP_CORRUPT to drop the SEG$ entry.
5. Call TABLESPACE_REBUILD_QUOTAS to fix up quotas.
Scenario 3: Fixing Bitmap Where Overlap is Reported
The TABLESPACE_VERIFY procedure reports some overlapping. Some of the real data must be
sacrificed based on previous internal errors. After choosing the object to be sacrificed, in this
case say, table t1, perform the following tasks:
1. Make a list of all objects that t1 overlaps.
2. Drop table t1. If necessary, follow up by calling the SEGMENT_DROP_CORRUPT procedure.
3. Call the SEGMENT_VERIFY procedure on all objects that t1 overlapped. If necessary, call
the TABLESPACE_FIX_BITMAPS procedure to mark appropriate bitmap blocks as used.
4. Rerun the TABLESPACE_VERIFY procedure to verify the problem is resolved.
Scenario 4: Correcting Media Corruption of Bitmap Blocks
A set of bitmap blocks has media corruption. In this scenario, perform the following tasks:
1. Call the TABLESPACE_REBUILD_BITMAPS procedure, either on all bitmap
blocks, or on a single block if only one is corrupt.
2. Call the TABLESPACE_REBUILD_QUOTAS procedure to rebuild quotas.
3. Call the TABLESPACE_VERIFY procedure to verify that the bitmaps are consistent.


Transporting Tablespaces Between Databases
Limitations on Transportable Tablespace Use
The source and target database must use the same character set and national character
set.
Objects with underlying objects (such as materialized views) or contained objects (such as
partitioned tables) are not transportable unless all of the underlying or contained objects
are in the tablespace set.
You cannot transport the SYSTEM tablespace or objects owned by the user SYS. This
means that you cannot use TTS for PL/SQL, triggers, or views. These would have to be
moved with export.
You cannot transport a table with a materialized view unless the mview is in the transport
set you create.
You cannot transport a partition of a table without transporting the entire table.

Page 93 Oracle DBA Code Examples

1. Check endian format of both platforms.
For cross-platform transport, check the endian format of both platforms by querying the
V$TRANSPORTABLE_PLATFORMview.
You can find out your own platform name:
sel ect pl at f or m_name f r omv$dat abase

2. Pick a self-contained set of tablespaces.
The following statement can be used to determine whether tablespaces sales_1 and sales_2
are self-contained, with referential integrity constraints taken into consideration:
DBMS_TTS. TRANSPORT_SET_CHECK( TS_LI ST =>' sal es_1, sal es_2' , I NCL_CONSTRAI NTS
=>TRUE, FULL_CHECK =>TRUE)
Note: You must have been granted the EXECUTE_CATALOG_ROLE role (initially signed to SYS)
to execute this procedure.
You can see all violations by selecting from the TRANSPORT_SET_VI OLATI ONS view. If the set
of tablespaces is self-contained, this view is empty.
3. Generate a transportable tablespace set.
3.1.Make all tablespaces in the set you are copying read-only.
3.2.Export the metadata describing the objects in the tablespace(s)
EXPDP syst em/ passwor d DUMPFI LE=expdat . dmp DI RECTORY=dpump_di r
TRANSPORT_TABLESPACES = sal es_1, sal es_2
TRANSPORT_FULL_CHECK=Y
3.3.If you want to convert the tablespaces in the source database, use the RMAN
RMAN TARGET /
CONVERT TABLESPACE sal es_1, sal es_2
TO PLATFORM ' Mi cr osof t Wi ndows NT'
FORMAT ' / t emp/ %U'
4. Transport the tablespace set.
Transport both the datafiles and the export file of the tablespaces to a place accessible to
the target database.
5. Convert tablespace set, if required, in the destination database.
Use RMAN as f ol l ows:
RMAN> CONVERT DATAFI LE
' / hq/ f i nance/ wor k/ t r u/ t bs_31. f ' ,
' / hq/ f i nance/ wor k/ t r u/ t bs_32. f ' ,
' / hq/ f i nance/ wor k/ t r u/ t bs_41. f '
TO PLATFORM=" Sol ar i s[ t m] OE ( 32- bi t ) "
FROM PLATFORM=" HP TRu64 UNI X"
DBFI LE_NAME_CONVERT=
" / hq/ f i nance/ wor k/ t r u/ " , " / hq/ f i nance/ dbs/ t r u"
PARALLELI SM=5
Note: The source and destination platforms are optional.
Note: By default, Oracle places the converted files in the Flash Recovery Area, without
changing the datafile names.
Note: If you have CLOB data on a small-endian system in an Oracle database version before
10g and with a varying-width character set and you are transporting to a database in a big-
endian system, the CLOB data must be converted in the destination database. RMAN does
not handle the conversion during the CONVERT phase. However, Oracle database
automatically handles the conversion while accessing the CLOB data.
If you want to eliminate this run-time conversion cost from this automatic conversion, you
can issue the CREATE TABLE AS SELECT command before accessing the data.
6. Plug in the tablespace.
Page 94 Oracle DBA Code Examples

I MPDP syst em/ passwor d DUMPFI LE=expdat . dmp DI RECTORY=dpump_di r
TRANSPORT_DATAFI LES=
/ sal esdb/ sal es_101. dbf ,
/ sal esdb/ sal es_201. dbf
REMAP_SCHEMA=( dcr anney: smi t h) REMAP_SCHEMA=( j f ee: wi l l i ams)
If required, put the tablespace into READ WRI TE mode.
Using Transportable Tablespaces: Scenarios
Transporting and Attaching Partitions for Data Warehousing
1. In a staging database, you create a new tablespace and make it contain the table you
want to transport. It should have the same columns as the destination partitioned table.
2. Create an index on the same columns as the local index in the partitioned table.
3. Transport the tablespace to the data warehouse.
4. In the data warehouse, add a partition to the table.
ALTER TABLE sal es ADD PARTI TI ON j ul 98 VALUES LESS THAN ( 1998, 8, 1)
5. Attach the transported table to the partitioned table by exchanging it with the new
partition:
ALTER TABLE sal es EXCHANGE PARTI TI ON j ul 98 WI TH TABLE j ul _sal es
I NCLUDI NG I NDEXES WI THOUT VALI DATI ON
Publishing Structured Data on CDs
A data provider can load a tablespace with data to be published, generate the transportable
set, and copy the transportable set to a CD. When customers receive this CD, they can plug
it into an existing database without having to copy the datafiles from the CD to disk storage.
Note: In this case, it is highly recommended to set the READ_ONLY_OPEN_DELAYED
initialization parameter to TRUE.
Moving Databases Across Platforms Using Transportable Tablespaces
You can use the transportable tablespace feature to migrate a database to a different
platform.
However, you cannot transport the SYSTEM tablespace. Therefore, objects such as
sequences, PL/SQL packages, and other objects that depend on the SYSTEM tablespace are
not transported. You must either create these objects manually on the destination database,
or use Data Pump to transport the objects that are not moved by transportable tablespace.

Managing Alert Thresholds
Getting the Current Threshold Setting
List of supported metrics can be found in the documentation "PL/SQL Packages and Types
Reference": 10g, 11g or link or from the query below:
SELECT METRI C_I D, METRI C_NAME, METRI C_UNI T,
GROUP_I D, GROUP_NAME
FROM V$METRI CNAME
ORDER BY METRI C_NAME

- - cur r ent t hr eshol d set t i ngs
sel ect * f r omDBA_THRESHOLDS;

set ser ver out put on
DECLARE
V_WOPERATOR BI NARY_I NTEGER;
V_WVALUE VARCHAR2( 50) ;
Page 95 Oracle DBA Code Examples

V_COPERATOR BI NARY_I NTEGER;
V_CVALUE VARCHAR2( 50) ;
V_OBS_PERI OD BI NARY_I NTEGER;
V_CON_PERI OD BI NARY_I NTEGER;
FUNCTI ON GET_OPERATOR_NAME( P_OPER I N BI NARY_I NTEGER) RETURN VARCHAR2
I S
BEGI N
I F P_OPER =0 THEN
RETURN ' GT' ;
ELSI F P_OPER =1 THEN
RETURN ' EQ' ;
ELSI F P_OPER =2 THEN
RETURN ' LT' ;
ELSI F P_OPER =3 THEN
RETURN ' LE' ;
ELSI F P_OPER =4 THEN
RETURN ' GE' ;
ELSI F P_OPER =5 THEN
RETURN ' OPERATOR_CONTAI NS' ;
ELSI F P_OPER =6 THEN
RETURN ' NE' ;
ELSI F P_OPER =7 THEN
RETURN ' OPERATOR_DO_NOT_CHECK' ;
END I F;
END GET_OPERATOR_NAME;
BEGI N
DBMS_SERVER_ALERT. GET_THRESHOLD(
met r i cs_i d =>DBMS_SERVER_ALERT. TABLESPACE_PCT_FULL,
war ni ng_oper at or =>V_WOPERATOR ,
war ni ng_val ue =>V_WVALUE,
cr i t i cal _oper at or =>V_COPERATOR,
cr i t i cal _val ue =>V_CVALUE,
obser vat i on_per i od =>V_OBS_PERI OD,
consecut i ve_occur r ences =>V_CON_PERI OD,
i nst ance_name =>NULL,
obj ect _t ype => DBMS_SERVER_ALERT. OBJ ECT_TYPE_TABLESPACE,
obj ect _name =>NULL) ;
DBMS_OUTPUT. PUT_LI NE( ' War ni ng Op. : ' | | GET_OPERATOR_NAME( V_WOPERATOR) ) ;
DBMS_OUTPUT. PUT_LI NE( ' War ni ng Val : ' | | V_WVALUE) ;
DBMS_OUTPUT. PUT_LI NE( ' Cr i t i cal Op. : ' | | GET_OPERATOR_NAME( V_COPERATOR) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Cr i t i cal Val : ' | | V_CVALUE) ;
EXCEPTI ON
WHEN OTHERS THEN
I F SQLCODE=' - 13799' THEN
DBMS_OUTPUT. PUT_LI NE( ' No t hr eshol d was f ound wi t h t he speci f i ed t hr eshol d
key. ( ORA- 13799) ' ) ;
ELSE
RAI SE;
END I F;
END;
/
Setting Tablespace Alert Thresholds
warning_operator takes one of the following (not all applicable for all metrics):
o OPERATOR_EQ GE GT LE LT NE
o OPERATOR_CONTAINS
Page 96 Oracle DBA Code Examples

o OPERATOR_DO_NOT_CHECK (disables the alert for the specified metric)
- - set t he f r ee- space- r emai ni ng t hr eshol ds i n t he USERS t abl espace t o 10 MB
( war ni ng)
- - and 2 MB ( cr i t i cal ) , and di sabl e t he per cent - f ul l t hr eshol ds.
BEGI N
DBMS_SERVER_ALERT. SET_THRESHOLD(
met r i cs_i d => DBMS_SERVER_ALERT. TABLESPACE_BYT_FREE, - - Tabl espace FREE
space i n KB
war ni ng_oper at or => DBMS_SERVER_ALERT. OPERATOR_LT, - - GT i s not appl i cabl e
her e
war ni ng_val ue => ' 10240' ,
cr i t i cal _oper at or => DBMS_SERVER_ALERT. OPERATOR_LT,
cr i t i cal _val ue => ' 2048' ,
obser vat i on_per i od => 1, - - comput at i on per i od ( 1- 60 mi n)
consecut i ve_occur r ences => 1, - - vi ol at i on t i mes bef or e al er t
i nst ance_name => NULL, - - NULL= ' dat abase_wi de' . Passed val ue i s not checked
obj ect _t ype => DBMS_SERVER_ALERT. OBJ ECT_TYPE_TABLESPACE,
obj ect _name => ' USERS' ) ; - - i f NULL - > Al l Tabl espaces

DBMS_SERVER_ALERT. SET_THRESHOLD(
met r i cs_i d => DBMS_SERVER_ALERT. TABLESPACE_PCT_FULL, - - t abl espace USAGE by
%
war ni ng_oper at or => DBMS_SERVER_ALERT. OPERATOR_DO_NOT_CHECK,
war ni ng_val ue => ' 0' ,
cr i t i cal _oper at or => DBMS_SERVER_ALERT. OPERATOR_DO_NOT_CHECK,
cr i t i cal _val ue => ' 0' ,
obser vat i on_per i od => 1,
consecut i ve_occur r ences => 1,
i nst ance_name => NULL,
obj ect _t ype => DBMS_SERVER_ALERT. OBJ ECT_TYPE_TABLESPACE,
obj ect _name => ' USERS' ) ;
END;
/

SELECT *
FROM dba_t hr eshol ds
wher e obj ect _name = ' USERS' and obj ect _t ype=' TABLESPACE' ;
Restoring a Tablespace to Database Default Thresholds
You can restore the metric threshold values to revert to the database defaults by setting
them to NULL in the DBMS_SERVER_ALERT.SET_THRESHOLD.
BEGI N
DBMS_SERVER_ALERT. SET_THRESHOLD(
met r i cs_i d => DBMS_SERVER_ALERT. TABLESPACE_PCT_FULL, - - t abl espace USAGE by
%
war ni ng_oper at or => NULL, - - do not use ' '
war ni ng_val ue => NULL,
cr i t i cal _oper at or => NULL,
cr i t i cal _val ue => NULL,
obser vat i on_per i od => 1,
consecut i ve_occur r ences => 1,
i nst ance_name => NULL,
obj ect _t ype => DBMS_SERVER_ALERT. OBJ ECT_TYPE_TABLESPACE,
obj ect _name => ' USERS' ) ;
END;
/
Page 97 Oracle DBA Code Examples


SELECT *
FROM dba_t hr eshol ds
wher e obj ect _name = ' USERS' and obj ect _t ype=' TABLESPACE' ;
Modifying Database Default Thresholds
set the object_name to NULL
BEGI N
DBMS_SERVER_ALERT. SET_THRESHOLD(
met r i cs_i d => DBMS_SERVER_ALERT. TABLESPACE_PCT_FULL, - - r edo wi t h
TABLESPACE_BYT_FREE
war ni ng_oper at or => DBMS_SERVER_ALERT. OPERATOR_GT,
war ni ng_val ue => ' 80' ,
cr i t i cal _oper at or => DBMS_SERVER_ALERT. OPERATOR_GT,
cr i t i cal _val ue => ' 92' ,
obser vat i on_per i od => 1,
consecut i ve_occur r ences => 1,
i nst ance_name => NULL,
obj ect _t ype => DBMS_SERVER_ALERT. OBJ ECT_TYPE_TABLESPACE,
obj ect _name => NULL) ;
END;
/

SELECT *
FROM dba_t hr eshol ds
wher e obj ect _name = ' USERS' and obj ect _t ype=' TABLESPACE' ;
Viewing Alerts
- - out st andi ng al er t s ( t o be cl ear ed)
SELECT
SEQUENCE_I D, OWNER,
OBJ ECT_NAME, OBJ ECT_TYPE, SUBOBJ ECT_NAME,
REASON_I D, REASON, TI ME_SUGGESTED,
SUGGESTED_ACTI ON, ADVI SOR_NAME, METRI C_VALUE,
MESSAGE_TYPE, MESSAGE_GROUP, MESSAGE_LEVEL,
HOSTI NG_CLI ENT_I D, MODULE_I D, PROCESS_I D,
HOST_I D, HOST_NW_ADDR, I NSTANCE_NAME,
I NSTANCE_NUMBER, USER_I D, EXECUTI ON_CONTEXT_I D, CREATI ON_TI ME
FROM DBA_OUTSTANDI NG_ALERTS

- - hi st or y of al er t s t hat have been cl ear ed
SELECT
SEQUENCE_I D, OWNER,
OBJ ECT_NAME, SUBOBJ ECT_NAME, OBJ ECT_TYPE,
REASON_I D, REASON, TI ME_SUGGESTED,
SUGGESTED_ACTI ON, ADVI SOR_NAME, METRI C_VALUE,
MESSAGE_TYPE, MESSAGE_GROUP, MESSAGE_LEVEL,
HOSTI NG_CLI ENT_I D, MODULE_I D, PROCESS_I D,
HOST_I D, HOST_NW_ADDR, I NSTANCE_NAME, I NSTANCE_NUMBER,
USER_I D, EXECUTI ON_CONTEXT_I D, CREATI ON_TI ME
FROM DBA_ALERT_HI STORY
ORDER BY SEQUENCE_I D

- - l i st of al l met r i cs
SELECT METRI C_I D, METRI C_NAME, METRI C_UNI T, GROUP_I D, GROUP_NAME
FROM V$METRI CNAME
Page 98 Oracle DBA Code Examples

ORDER BY METRI C_NAME

- - syst em- l evel met r i c val ues i n memor y
SELECT BEGI N_TI ME, END_TI ME, I NTSI ZE_CSEC,
GROUP_I D, ENTI TY_I D, ENTI TY_SEQUENCE,
METRI C_I D, METRI C_NAME, VALUE, METRI C_UNI T
FROM V$METRI C - al so V$METRI C_HI STORY
ORDER BY BEGI N_TI ME, VALUE DESC

- - al er t t ypes
sel ect
I NST_I D, REASON_I D, OBJ ECT_TYPE, TYPE, GROUP_NAME, SCOPE, I NTERNAL_METRI C_CATEGORY,
I NTERNAL_METRI C_NAME
f r omGV$ALERT_TYPES
or der by OBJ ECT_TYPE, TYPE
Managing Datafiles and Tempfiles
Creating Datafiles
CREATE TABLESPACE
CREATE TEMPORARY TABLESPACE ge 8- 9
ALTER TABLESPACE . . . ADD DATAFI LE
ALTER TABLESPACE . . . ADD TEMPFI LE ge 8- 9
CREATE DATABASE
ALTER DATABASE . . . CREATE DATAFI LE
Enabling and Disabling Automatic Extension for a Datafile
ALTER TABLESPACE user s
ADD DATAFI LE ' / u02/ or acl e/ r bdb1/ user s03. dbf ' SI ZE 10M
AUTOEXTEND ON
NEXT 512K
MAXSI ZE 250M;
Manually Resizing a Datafile
- - i f t her e i s space i n t he dat af i l e
ALTER DATABASE DATAFI LE ' / u02/ or acl e/ r bdb1/ st uf f 01. dbf ' RESI ZE 100M;
Br i ngi ng Dat af i l es Onl i ne or Taki ng Of f l i ne i n ARCHI VELOG Mode
ALTER DATABASE DATAFI LE ' / u02/ or acl e/ r bdb1/ st uf f 01. dbf ' ONLI NE;
ALTER DATABASE DATAFI LE ' / u02/ or acl e/ r bdb1/ st uf f 01. dbf ' OFFLI NE;
Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode
ALTER DATABASE DATAFI LE . . . {ONLI NE| OFFLI NE}
- - al l dat af i l es wi l l be af f ect ed i n t he f ol l owi ng code
- - t hi s i s di f f er ent f r omALTER TABLESPACE. . . ONLI NE| OFFLI NE whi ch cont r ol s
t abl espace avai l abi l i t y
ALTER TABLESPACE . . . DATAFI LE {ONLI NE| OFFLI NE}
ALTER TABLESPACE . . . TEMPFI LE {ONLI NE| OFFLI NE}
Taking Datafiles Offline in NOARCHIVELOG Mode
Use it when you want to drop the datafile.
Page 99 Oracle DBA Code Examples

- - dat af i l e cannot be br ought ONLI NE agai n
ALTER DATABASE DATAFI LE . . . OFFLI NE FOR DROP;
- - t he dat af i l e MUST t hen be dr opped
- - f or di ct i onar y managed t abl espace
ALTER TABLESPACE . . . DROP DATAFI LE
DROP TABLESPACE . . . I NCLUDI NG CONTENTS AND DATAFI LES
Renaming and Relocating Datafiles in a Single Tablespace
ALTER TABLESPACE user s OFFLI NE NORMAL;
Copy t he dat af i l es t o t hei r new l ocat i ons and r ename t hemusi ng t he oper at i ng
syst em.
ALTER TABLESPACE user s RENAME DATAFI LE
' / u02/ or acl e/ r bdb1/ user 1. dbf ' ,
' / u02/ or acl e/ r bdb1/ user 2. dbf '
TO
' / u02/ or acl e/ r bdb1/ user s01. dbf ' ,
' / u02/ or acl e/ r bdb1/ user s02. dbf ' ;
- - f or syst em, def aul t t empor ar y, or undo
- - ALTER TABLESPACE cannot be used because you cannot t ake t hemOFFLI NE
mount t he dat abase
ALTER DATABASE RENAME FI LE ' / u02/ or acl e/ r bdb1/ sor t 01. dbf ' ,
' / u02/ or acl e/ r bdb1/ user 3. dbf '
TO ' / u02/ or acl e/ r bdb1/ t emp01. dbf ' , ' / u02/ or acl e/ r bdb1/ user s03. dbf ;
Back up t he dat abase.
Dropping Datafiles
The following restrictions apply:
o The database must be open.
o The datafile must be empty, otherwise use drop the tablespace.
o You cannot drop datafiles in a read-only tablespace.
o You cannot drop datafiles in the SYSTEM tablespace.
o If a datafile in a locally managed tablespace is offline, it cannot be dropped.
ALTER TABLESPACE exampl e DROP DATAFI LE . . .
ALTER TABLESPACE l mt emp DROP TEMPFI LE
ALTER DATABASE TEMPFI LE . . DROP I NCLUDI NG DATAFI LES
Copying a File on a Local File System
The copied file must meet the following requirements:
o The size must be a multiple of 512 bytes.
o The size must be less than or equal to two terabytes.
Be aware not to coy a file that is being used by a process.
If you are copying a database datafile, make it READ ONLY before you start to copy.
CREATE DI RECTORY SOURCE_DI R AS ' / usr / admi n/ sour ce' ;
CREATE DI RECTORY DEST_DI R AS ' / usr / admi n/ dest i nat i on' ;
GRANT READ ON DI RECTORY sour ce_di r TO st r madmi n;
GRANT WRI TE ON DI RECTORY dest _di r TO st r madmi n;
CONNECT st r madmi n/ st r madmi npw
BEGI N
DBMS_FI LE_TRANSFER. COPY_FI LE(
sour ce_di r ect or y_obj ect => ' SOURCE_DI R' ,
sour ce_f i l e_name => ' db1. dat ' ,
Page 100 Oracle DBA Code Examples

dest i nat i on_di r ect or y_obj ect => ' DEST_DI R' ,
dest i nat i on_f i l e_name => ' db1_copy. dat ' ) ;
END;
Transferring a File to a Different Database
In order to transfer a file the other way around, you must replace the PUT_FILE
procedure with the GET_FILE procedure.
If you are copying a database datafile, make it READ ONLY before you start to copy.
You can monitor copying progress using V$SESSION_LONGOPS view.
CREATE DATABASE LI NK ODB
CONNECT TO syst emI DENTI FI ED BY syst em_passwd USI NG ' pr od1' ;

BEGI N
DBMS_FI LE_TRANSFER. PUT_FI LE(
SOURCE_DI RECTORY_OBJ ECT => ' SOURCE_DI R' ,
SOURCE_FI LE_NAME => ' mydat a1. dbf ' ,
DESTI NATI ON_DI RECTORY_OBJ ECT => ' DEST_DI R' ,
DESTI NATI ON_FI LE_NAME => ' mydat a2. dbf '
DESTI NATI ON_DATABASE => ' ODB. ACME. COM' ) ;
END;
/
BEGI N
DBMS_FI LE_TRANSFER. GET_FI LE(
SOURCE_DI RECTORY_OBJ ECT => ' SOURCE_DI R' ,
SOURCE_FI LE_NAME => ' TEST01. DBF' ,
SOURCE_DATABASE => ' ODB. ACME. COM' ,
DESTI NATI ON_DI RECTORY_OBJ ECT => ' DEST_DI R' ,
DESTI NATI ON_FI LE_NAME => ' TEST01. DBF' ) ;
END;
/
Dumping a Data Block
ALTER SYSTEM DUMP DATAFI LE 3 BLOCK 3281;

- - To dump a number of consecut i ve bl ocks: :
ALTER SYSTEM DUMP DATAFI LE 5 BLOCK MI N 42 BLOCK MAX 50;

sel ect val ue f r omv$par amet er wher e name=' user _dump_dest ' ;
/ u01/ app/ or acl e/ admi n/ pasu/ udump/ pasu_or a_29673. t r c



/ * t o dump i ndex bl ocks */
- - get obj ect i d of t he i ndex:
SELECT obj ect _i d FROM dba_obj ect s WHERE obj ect _name = ' MYI NDEX' ;

- - do a t r eedump of t he i ndex:
ALTER SESSI ON SET EVENTS ' i mmedi at e t r ace name t r eedump l evel 106315' ;

i ndex hei ght
di st i nct i ndex bl ocks i n t he l ower l evel |
RBA bl ock at posi t i on zer o | |
| | | |
br anch: 01c3588a 29579402 ( 0: nr ow: 222, l evel : 1)


number of ent r i es
l ead bl ock number ( st ar t s f r om- 1) | non- del et ed ent r i es
| | |
Page 101 Oracle DBA Code Examples

l eaf : 01c3588b 29579403 ( - 1: nr ow: 485 r r ow: 485)
l eaf : 01c3588c 29579404 ( 0: nr ow: 479 r r ow: 479)
l eaf : 01c3588d 29579405 ( 1: nr ow: 479 r r ow: 479)
l eaf : 01c3588e 29579406 ( 2: nr ow: 479 r r ow: 479)


- - def i ne t he RBA of t he bl ock t o dump t hen
- - get i t s f i l e# and bl ock#:
SELECT DBMS_UTI LI TY. DATA_BLOCK_ADDRESS_FI LE( 223456765) ,
DBMS_UTI LI TY. DATA_BLOCK_ADDRESS_BLOCK( 223456765)
FROM dual ;


- - dump t he header bl ock
ALTER SYSTEM DUMP DATAFI LE 7 BLOCK 328745;


- - al so, you can f i nd t he r oot bl ock ( i t i s t he bl ock f ol l owi ng t he header bl oc) :
SELECT header _f i l e, header _bl ock+1 FROM dba_segment s WHERE segment _name=' MYI NDEX' ;
Managing Undo Tablespaces
Obtaining Information on Undo
SHOWPARAMETER UNDO
NAME TYPE VALUE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
undo_management st r i ng AUTO
undo_r et ent i on i nt eger 900
undo_t abl espace st r i ng UNDOTBS01

-- undo usage in 10-min-intervals for last 7 days
sel ect TO_CHAR( BEGI N_TI ME, ' MM/ DD/ YYYY HH24: MI : SS' ) BEGI N_TI ME,
TO_CHAR( END_TI ME, ' MM/ DD/ YYYY HH24: MI : SS' ) END_TI ME,
UNDOBLKS UNDO_BLOCKS,
MAXQUERYLEN MAX_QUERY_LENGTH_I NSEC,
MAXQUERYI D LONGEST_QUERY_I D,
TXNCOUNT TOTAL_TRANSACTI ONS,
MAXCONCURRENCY
f r omV$UNDOSTAT
or der by BEGI N_TI ME DESC

-- stats history of V$UNDOSTAT
sel ect
TO_CHAR( BEGI N_TI ME, ' MM/ DD/ YYYY HH24: MI : SS' ) BEGI N_TI ME,
TO_CHAR( END_TI ME, ' MM/ DD/ YYYY HH24: MI : SS' ) END_TI ME,
I NSTANCE_NUMBER, SNAP_I D,
UNDOBLKS,
TXNCOUNT TOTAL_TRANSACTI ONS,
MAXQUERYLEN MAX_QUERY_LENGTH_I NSEC,
MAXQUERYSQLI D,
MAXCONCURRENCY,
SSOLDERRCNT ORA01555_CNT,
NOSPACEERRCNT NOSPACE_CNT,
ACTI VEBLKS, UNEXPI REDBLKS
f r omDBA_HI ST_UNDOSTAT


-- undo segments
sel ect SEGMENT_NAME, OWNER, STATUS f r omDBA_ROLLBACK_SEGS;


Page 102 Oracle DBA Code Examples

-- undo extents
sel ect
e. SEGMENT_NAME,
e. TABLESPACE_NAME,
e. EXTENT_I D,
e. FI LE_I D,
e. BLOCK_I D,
e. BYTES/ 1024 SI ZE_KB,
e. RELATI VE_FNO,
e. STATUS - - ACTI VE EXPI RED UNEXPI RED
f r omDBA_UNDO_EXTENTS e
or der by e. STATUS ASC

-- undo sizes by STATUS
sel ect
e. TABLESPACE_NAME,
e. STATUS,
t o_char ( sum( e. BYTES/ 1024) , ' 999, 999, 999, 999' ) SI ZE_KB
f r omDBA_UNDO_EXTENTS e
gr oup by e. TABLESPACE_NAME, e. STATUS
or der by e. STATUS


-- undo sizes consumed by active transactions by username
SELECT s. user name, sum( t . used_ubl k) used_undo_bl ocks
f r om v$sessi on s, v$t r ansact i on t
wher e s. saddr = t . ses_addr
and t . st at us=' ACTI VE'
gr oup by s. user name
or der by s. user name
Enabling Automatic Undo Management
sel ect val ue f r omv$par amet er wher e upper ( name) =' UNDO_MANAGEMENT' ;
al t er syst emset UNDO_MANAGEMENT=AUTO scope=spf i l e ;
Creating an Undo Tablespace
CREATE UNDO TABLESPACE undot bs2
DATAFI LE ' / u01/ or acl e/ r bdb1/ undo0201. dbf ' SI ZE 200M REUSE AUTOEXTEND ON;
Setting Startup Undo Tablespace
sel ect val ue f r omv$par amet er wher e upper ( name) =' UNDO_TABLESPACE' ;
- - i f t her e ar e mul t i pl e undo t abl espaces
- - af t er al l act i ve t r ansact i ons have commi t t ed, t he undo t abl espace aut omat i cal l y
- - goes f r omt he PENDI NG OFFLI NE mode t o t he OFFLI NE mode.
al t er syst emset UNDO_TABLESPACE=' UNDOTBS1' ;
- - t he f ol l owi ng swi t ches out cur r ent undo t abl espace t o t he next avai l abl e one
al t er syst emset UNDO_TABLESPACE = ' ' ;
Tuning Undo Retention
If the undo tablespace is configured with the AUTOEXTEND option, undo retention tuning
is slightly different. In this case, the database tunes the undo retention period to be
slightly longer than the longest-running query on the system at that time.
For a fixed size undo tablespace, the database tunes the undo retention period based on
85% of the tablespace size, or on the warning alert threshold percentage for space used,
whichever is lower.
If you want a fixed undo size, use the Undo Advisor to specify the proper undo size for
your requirement. You should estimate:
Page 103 Oracle DBA Code Examples

o The length of your expected longest running query
o The longest interval that you will require for flashback operations
- - det er mi ne t he cur r ent r et ent i on per i od
sel ect t o_char ( begi n_t i me, ' DD- MON- RR HH24: MI ' ) begi n_t i me,
t o_char ( end_t i me, ' DD- MON- RR HH24: MI ' ) end_t i me,
t uned_undor et ent i on
f r omv$undost at or der by end_t i me;

- - maxi mumquer y t i me
SELECT r ound( MAX( maxquer yl en) / 60) Mi nut es FROM v$undost at ;
Using Undo Advisor
Use OEM or PL/SQL
- - r et r ei ve avai l abl e AWR snaps
sel ect SNAP_I D, STARTUP_TI ME, BEGI N_I NTERVAL_TI ME, END_I NTERVAL_TI ME
f r omDBA_HI ST_SNAPSHOT
or der by SNAP_I D;

set ser ver out put on
DECLARE
t i d NUMBER; - - t ask I D
t name VARCHAR2( 30) ; - - t ask name
oi d NUMBER;
BEGI N
DBMS_ADVI SOR. CREATE_TASK( ' Undo Advi sor ' , t i d, t name, ' Undo Advi sor Task' ) ;
DBMS_ADVI SOR. CREATE_OBJ ECT( t name, ' UNDO_TBS' , nul l , nul l , nul l , nul l , oi d) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( t name, ' TARGET_OBJ ECTS' , oi d) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( t name, ' START_SNAPSHOT' , 52) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( t name, ' END_SNAPSHOT' , 56) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( t name, ' I NSTANCE' , 1) ;
DBMS_ADVI SOR. execut e_t ask( t name) ;
DBMS_OUTPUT. PUT_LI NE( t name) ;
end;
/

SELECT DBA_ADVI SOR_RECOMMENDATI ONS. GET_TASK_REPORT( ' TASKNAME' )
FROM DUAL;
Setting the Undo Retention Period
You must set UNDO_RETENTION parameter when:
o The undo tablespace has the AUTOEXTEND option enabled
o You want to set undo retention for LOBs
o You want retention guarantee
sel ect val ue f r omv$par amet er wher e upper ( name) =' UNDO_RETENTI ON' ;
al t er syst emset UNDO_RETENTI ON = 2400;
Enabling Retention Guarantee
Enabling retention guarantee can cause multiple DML operations to fail. Use with caution.
sel ect RETENTI ON f r omDBA_TABLESPACES wher e TABLESPACE_NAME=' UNDOTBS1' ;
cr eat e undo t abl espace undot bs01 . . RETENTI ON GUARANTEE;
al t er t abl espace undot bs1 RETENTI ON GUARANTEE;
al t er t abl espace undot bs1 RETENTI ON NOGUARANTEE;
Dropping an Undo Tablespace
DROP TABLESPACE undot bs_01;
Page 104 Oracle DBA Code Examples

To Drop a Corrupt UNDO Tablespace
An Undo tablespace containing a corrupted undo rollback segment may lead to one or more of
the following:
ORA-00376: file xx cannot be read at this time
SIMON process being hang waiting for the event "wait for a undo record" forever!
I dent i f y t he bad r ol l back segment ( s) ( Or acl e woul d r epor t i t anyway) :
- - l ooki ng f or NEEDS RECOVERY or PARTI ALLY AVAI LABLE
sel ect
segment _name, st at us
f r omdba_r ol l back_segs
wher e t abl espace_name=' undot bs_cor r upt '
and st at us not i n ( ' OFFLI NE' , ' ONLI NE' ) ;


- - Let ' s say i t ' s _SYSSMU9$


- - ( opt i onal l y) cr eat e a new undo t abl espace
- - and r epl ace i t wi t h t he cur r ent one
CREATE UNDO TABLESPACE undot bs2
DATAFI LE ' / u01/ or acl e/ r bdb1/ undo0201. dbf ' SI ZE 200M REUSE AUTOEXTEND ON;
al t er syst emset UNDO_TABLESPACE=' UNDOTBS2' ;

- - Next , cr eat e pf i l e and i n i t :
undo_management = MANUAL
_of f l i ne_r ol l back_segment s=_SYSSMU9$


- - shut down t he db

- - open i t usi ng t he pf i l e

- - dr op t he of f endi ng r ol l back segment
- - ( and t he undo t abl espace al t oget her i f t he ot her one was cr eat ed)
- - Not e: dat af i l es mi ght not act ual l y be del et ed, check t hem
dr op t abl espace . . i ncl udi ng cont ent s and dat af i l es


- - bounce t he db ( make i t st ar t usi ng t he spf i l e)
- - t hi s means i t wi l l go back t o usi ng t he aut omat i c undo
Using Oracle Managed Files (OMF)
OMF datafiles have to be created in one directory
set DB_CREATE_FI LE_DEST, DB_CREATE_ONLI NE_LOG_DEST_n, and DB_RECOVERY_FI LE_DEST

- - when OMF enabl ed
CREATE TABLESPACE f i nance01;
ALTER TABLESPACE f i nance01 ADD DATAFI LE 500M;
DROP TABLESPACE f i nance01; - - dbf aut o del et ed

- - cr eat e db wi t h OMF
db_name=mydb
DB_CREATE_FI LE_DEST = ' / u01/ app/ or acl e/ or adat a'
DB_RECOVERY_FI LE_DEST_SI ZE = 100M
DB_RECOVERY_FI LE_DEST = ' / u04/ app/ or acl e/ or adat a'
LOG_ARCHI VE_DEST_1 = ' LOCATI ON = USE_DB_RECOVERY_FI LE_DEST'
SQL> connect sys/ sys_passwd as sysdba
Connect ed t o an i dl e i nst ance.
Page 105 Oracle DBA Code Examples

SQL> STARTUP NOMOUNT PFI LE=' i ni t mydb. or a' ;
SQL> CREATE DATABASE mydb;

Page 106 Oracle DBA Code Examples

Managing Schema Objects
Chaching Small Tables in Memory
ALTER TABLE hr . count r i es CACHE;
Creating Virtual Columns
CREATE TABLE EMPLOYEES
( empno number PRI MARY KEY,
sal NUMBER ( 8, 2) NOT NULL,
annual _sal AS ( sal *12) ,
CONSTRAI NT MaxAnSal CHECK ( annual _sal BETWEEN 0 AND 2000000) ) ;
SELECT TABLE_NAME, COLUMN_NAME, DATA_DEFAULT
FROM DBA_TAB_COLUMNS
WHERE TABLE_NAME=' EMPLOYEES' AND COLUMN_NAME=' ANNUAL_SAL' ;

ALTER TABLE empl oyees ADD ( i ncome AS ( sal ar y*commi ssi on_pct ) ) ;
Creating Partitioned Tables
/ * r ange par t i t i ons */
CREATE TABLE st udent _hi st or y
( st udent _i d NUMBER( 10) ,
degr ee VARCHAR2( 3) ,
gr aduat i on_dat e DATE,
f i nal _gpa NUMBER)
PARTI TI ON BY RANGE ( gr aduat i on_dat e)
( PARTI TI ON p_1997 VALUES LESS THAN
( TO_DATE( ' 01- J UN- 1997' , ' DD- MON- YYYY' ) ) TABLESPACE t s1,
PARTI TI ON p_1998 VALUES LESS THAN
( TO_DATE( ' 01- J UN- 1998' , ' DD- MON- YYYY' ) ) TABLESPACE t s2,
PARTI TI ON p_1999 VALUES LESS THAN
( TO_DATE( ' 01- J UN- 1999' , ' DD- MON- YYYY' ) ) TABLESPACE t s3,
PARTI TI ON p_ot her VALUES LESS THAN ( maxval ue) TABLESPACE t s4) ;

CREATE TABLE sal es_dat a
( t i cket _no NUMBER,
sal e_year I NT NOT NULL,
sal e_mont h I NT NOT NULL,
sal e_day I NT NOT NULL)
PARTI TI ON BY RANGE ( sal e_year , sal e_mont h, sal e_day)
( PARTI TI ON sal es_q1 VALUES LESS THAN ( 2008, 04, 01) TABLESPACE t s1,
PARTI TI ON sal es_q2 VALUES LESS THAN ( 2008, 07, 01) TABLESPACE t s2,
PARTI TI ON sal es_q3 VALUES LESS THAN ( 2008, 10, 01) TABLESPACE t s3,
PARTI TI ON sal es_q4 VALUES LESS THAN ( 2009, 01, 01) TABLESPACE t s4) ;

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

/ * I nt er val Par t i t i oni ng */
- - You can t use a par t i t i oni ng key t hat i ncl udes mor e t han one col umn
- - syst emgener at ed par t i ons have names SYS_Pn
CREATE TABLE i nt er val _sal es
( pr od_i d NUMBER( 6) ,
cust _i d NUMBER,
t i me_i d DATE,
. . )
Page 107 Oracle DBA Code Examples

PARTI TI ON BY RANGE ( t i me_i d)
I NTERVAL( NUMTOYMI NTERVAL( 1, ' MONTH' ) )
STORE I N ( t s5, t s6, t s7) - - opt i onal
( PARTI TI ON t s1 VALUES LESS THAN ( TO_DATE( ' 1- 1- 2006' , ' DD- MM- YYYY' ) ) ,
PARTI TI ON t s2 VALUES LESS THAN ( TO_DATE( ' 1- 1- 2007' , ' DD- MM- YYYY' ) ) ,
PARTI TI ON t s3 VALUES LESS THAN ( TO_DATE( ' 1- 7- 2008' , ' DD- MM- YYYY' ) ) ,
PARTI TI ON t s4 VALUES LESS THAN ( TO_DATE( ' 1- 1- 2009' , ' DD- MM- YYYY' ) ) ) ;

SELECT TABLE_NAME, PARTI TI ON_NAME, PARTI TI ON_POSI TI ON, HI GH_VALUE
FROM Remot e DBA_TAB_PARTI TI ONS
WHERE TABLE_NAME=' POS_DATA'
ORDER BY PARTI TI ON_NAME;

cr eat e t abl e r es (
r es_i d number not nul l ,
r es_dat e dat e,
hot el _i d number ( 3) ,
guest _i d number )
par t i t i on by r ange ( r es_i d)
i nt er val ( 100) st or e i n ( user s)
( par t i t i on p1 val ues l ess t han ( 101) ) ;


- - sel ect i ng f r omt he gener at ed par t i t i on
- - cl assi c met hod
sel ect * f r omi nt er val _sal es par t i t i on f or ( SYS_P81) ;
- - t he ot her met hod ( expanded par t i t i on access synt ax)
sel ect * f r om
i nt er val _sal es par t i t i on f or ( t o_dat e( ' 15- AUG- 2009' , ' dd- mon- yyyy' ) ) ;
al t er t abl e r es t r uncat e par t i t i on f or ( 901) ;


- - a r ange par t i on can be conver t ed t o i nt er val par t i t i on
al t er t abl e pos_dat a_r ange set I NTERVAL( NUMTOYMI NTERVAL( 1, ' MONTH' ) ) ;

- - conver t an i nt er val par t i t i on t o r ange par t i t i on
al t er t abl e pos_dat a_r ange set I NTERVAL( ) ;

- - i nt er val can be modi f i ed
al t er t abl e pos_dat a set I NTERVAL( NUMTOYMI NTERVAL( 3, ' MONTH' ) ) ;

- - r ound r obi n t abl espaces can be modi f i ed
al t er t abl e pos_dat a set STORE I N( t abl espace1, t abl espace2, t abl espace3) ;

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

/ * Hash Par t i t i oni ng */
- - used when r ange di st r i but i on i s not pr edi ct abl e and f or hi gh car di nal i t y col umns
- - Updat es t hat woul d cause a r ecor d t o move acr oss par t i t i on boundar i es ar e not al l owed
CREATE TABLE sal es_dat a
( t i cket _no NUMBER,
sal e_year I NT NOT NULL,
sal e_mont h I NT NOT NULL,
sal e_day I NT NOT NULL )
PARTI TI ON BY HASH ( t i cket _no)
PARTI TI ONS 4
STORE I N ( t s1, t s2, t s3, t s4) ;

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

/ * Li st Par t i t i oni ng */
CREATE TABLE sal es_dat a
( t i cket _no NUMBER,
sal e_year I NT NOT NULL,
Page 108 Oracle DBA Code Examples

sal e_mont h I NT NOT NULL,
sal e_day I NT NOT NULL,
dest i nat i on_ci t y CHAR( 3) ,
st ar t _ci t y CHAR( 3) )
PARTI TI ON BY LI ST ( st ar t _ci t y)
( PARTI TI ON nor t heast _sal es val ues ( ' NYC' , ' BOS' , ' PEN' ) TABLESPACE t s1,
PARTI TI ON sout hwest _sal es val ues ( ' DFW' , ' ORL' , ' HOU' ) TABLESPACE t s2,
PARTI TI ON paci f i cwest _sal es val ues( ' SAN' , ' LOS' , ' WAS' ) TABLESPACE t s3,
PARTI TI ON sout heast _sal es val ues ( ' MI A' , ' CHA' , ' ATL' ) TABLESPACE t s4) ;

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

/ * Ref er ence Par t i t i oni ng */
- - put chi l d t abl e dat a i nt o par ent t abl e par t i t i ons
- - You can use al l par t i t i oni ng st r at egi es wi t h r ef er ence par t i t i oni ng, except i nt er val
par t i t i oni ng

CREATE TABLE or der s
( or der _i d NUMBER( 12) ,
or der _dat e DATE,
or der _mode VARCHAR2( 8) ,
cust omer _i d NUMBER( 6) ,
or der _st at us NUMBER( 2) ,
or der _t ot al NUMBER( 8, 2) ,
sal es_r ep_i d NUMBER( 6) ,
pr omot i on_i d NUMBER( 6) ,
CONSTRAI NT or der s_pk PRI MARY KEY( or der _i d) )
PARTI TI ON BY RANGE( or der _dat e)
( PARTI TI ON Q1_2005 VALUES LESS THAN ( TO_DATE( ' 01- APR- 2005' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON Q2_2005 VALUES LESS THAN ( TO_DATE( ' 01- J UL- 2005' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON Q3_2005 VALUES LESS THAN ( TO_DATE( ' 01- OCT- 2005' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON Q4_2005 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2006' , ' DD- MON- YYYY' ) )
) ;

CREATE TABLE or der _i t ems
( or der _i d NUMBER( 12) NOT NULL,
l i ne_i t em_i d NUMBER( 3) NOT NULL,
pr oduct _i d NUMBER( 6) NOT NULL,
uni t _pr i ce NUMBER( 8, 2) ,
quant i t y NUMBER( 8) ,
CONSTRAI NT or der _i t ems_f k
FOREI GN KEY( or der _i d) REFERENCES or der s( or der _i d)
)
PARTITION BY REFERENCE( or der _i t ems_f k) ;

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

/ * Vi r t ual Col umn- Based Par t i t i oni ng */
- - ENABLE ROWMOVEMENT cl ause ensur es r ow mi gr at i on among par t i t i ons when vi r t ual col umn
val ue changes
CREATE TABLE sal es
( pr od_i d NUMBER( 6) NOT NULL,
cust _i d NUMBER NOT NULL,
t i me_i d DATE NOT NULL,
channel _i d CHAR( 1) NOT NULL,
pr omo_i d NUMBER( 6) NOT NULL,
quant i t y_sol d NUMBER( 3) NOT NULL,
amount _sol d NUMBER( 10, 2) NOT NULL,
t ot al _amount AS ( quant i t y_sol d * amount _sol d)
)
PARTI TI ON BY RANGE ( t i me_i d) I NTERVAL ( NUMTOYMI NTERVAL( 1, ' MONTH' ) )
SUBPARTI TI ON BY RANGE( total_amount)
SUBPARTI TI ON TEMPLATE
( SUBPARTI TI ON p_smal l VALUES LESS THAN ( 1000) ,
Page 109 Oracle DBA Code Examples

SUBPARTI TI ON p_medi umVALUES LESS THAN ( 5000) ,
SUBPARTI TI ON p_l ar ge VALUES LESS THAN ( 10000) ,
SUBPARTI TI ON p_ext r eme VALUES LESS THAN ( MAXVALUE)
)
( PARTI TI ON sal es_bef or e_2007 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2007' , ' dd- MON- yyyy' ) ) )
ENABLE ROWMOVEMENT
PARALLEL;

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

/ * Vi r t ual Col umn- Based Par t i t i oni ng */
- - ENABLE ROWMOVEMENT cl ause ensur es r ow mi gr at i on among par t i t i ons when vi r t ual col umn
val ue changes
CREATE TABLE sal es
( pr od_i d NUMBER( 6) NOT NULL,
cust _i d NUMBER NOT NULL,
t i me_i d DATE NOT NULL,
channel _i d CHAR( 1) NOT NULL,
pr omo_i d NUMBER( 6) NOT NULL,
quant i t y_sol d NUMBER( 4) NOT NULL,
amount _sol d NUMBER( 4) NOT NULL,
t ot al _amount s AS (quantity_sold * amount_sold)
)
PARTI TI ON BY RANGE ( t i me_i d) I NTERVAL ( NUMTOYMI NTERVAL( 1, ' MONTH' ) )
SUBPARTI TI ON BY RANGE( total_amounts)
SUBPARTI TI ON TEMPLATE
( SUBPARTI TI ON p_smal l VALUES LESS THAN ( 1000) ,
SUBPARTI TI ON p_medi umVALUES LESS THAN ( 5000) ,
SUBPARTI TI ON p_l ar ge VALUES LESS THAN ( 10000) ,
SUBPARTI TI ON p_ext r eme VALUES LESS THAN ( MAXVALUE)
)
( PARTI TI ON sal es_bef or e_2007 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2007' , ' dd- MON- yyyy' ) ) )
ENABLE ROWMOVEMENT
PARALLEL;

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

/ * Syst emPar t i t i oni ng */
- - t he appl i cat i on deci ded wher e t o st or e t he dat a
CREATE TABLE docs
( I D NUMBER,
Name VARCHAR2( 255) ,
Desc VARCHAR2( 1000) )
PARTI TI ON BY SYSTEM
( PARTI TI ON docs_p1 TABLESPACE t s1,
PARTI TI ON docs_p2 TABLESPACE t s2,
PARTI TI ON docs_p3 TABLESPACE t s3,
PARTI TI ON docs_p4 TABLESPACE t s4 ) ;

- - PARTI TI ON must be st at ed
I NSERT I NTO docs PARTI TI ON ( t s1)
VALUES ( 1, ' Or acl e 11g New Feat ur es' , ' New f eat ur es i n Or acl e 11g Dat abase. ' ) ;
- - wi t h DELETE command, PARTI TI ON can be st at ed
DELETE FROM docs PARTI TI ON ( t s2) WHERE doc_i d=1002;
DELETE FROM docs PARTI TI ON ( t s2) ;
- - PARTI TI ON can be used i n quer i es t o t ar get speci f i c par t i t i ons
SELECT COUNT( *) FROM docs PARTI TI ON ( t s1)

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

/ * Range- Hash Par t i t i oni ng */

CREATE TABLE scout _gear
( equi pno NUMBER, equi pname VARCHAR( 32) , pr i ce NUMBER)
Page 110 Oracle DBA Code Examples

PARTI TI ON BY RANGE ( equi pno)
SUBPARTI TI ON BY HASH( equi pname)
SUBPARTI TI ONS 8 STORE I N ( t s1, t s2, t s3, t s4)
( PARTI TI ON p1 VALUES LESS THAN ( 1000) ,
PARTI TI ON p2 VALUES LESS THAN ( 2000) ,
PARTI TI ON p3 VALUES LESS THAN ( 3000) ,
PARTI TI ON p4 VALUES LESS THAN ( MAXVALUE) ) ;

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/ * Range- Li st Par t i t i oni ng */

CREATE TABLE r egi onal _sal es
( t i cket _no NUMBER,
sal e_year I NT NOT NULL,
sal e_mont h I NT NOT NULL,
sal e_day DATE,
dest i nat i on_ci t y CHAR( 3) ,
st ar t _ci t y CHAR( 3) )
PARTI TI ON BY RANGE( sal e_day)
SUBPARTI TI ON BY LI ST ( st ar t _ci t y)
( PARTI TI ON q1_2004 VALUES LESS THAN ( TO_DATE( ' 1- APR- 2004' , ' DD- MON- YYYY' ) )
TABLESPACE t s1
( SUBPARTI TI ON q12004_nor t heast _sal es VALUES ( ' NYC' , ' BOS' , ' PEN' ) ,
SUBPARTI TI ON q12004_sout hwest _sal es VALUES ( ' DFW' , ' ORL' , ' HOU' ) ,
SUBPARTI TI ON q12004_paci f i cwest _sal es VALUES ( ' SAN' , ' LOS' , ' WAS' ) ,
SUBPARTI TI ON q12004_sout heast _sal es VALUES ( ' MI A' , ' CHA' , ' ATL' )
) ,
PARTI TI ON q2_2004 VALUES LESS THAN ( TO_DATE( ' 1- J UL- 2004' , ' DD- MON- YYYY' ) )
TABLESPACE t s2
( SUBPARTI TI ON q22004_nor t heast _sal es VALUES ( ' NYC' , ' BOS' , ' PEN' ) ,
SUBPARTI TI ON q22004_sout hwest _sal es VALUES ( ' DFW' , ' ORL' , ' HOU' ) ,
SUBPARTI TI ON q22004_paci f i cwest _sal es VALUES ( ' SAN' , ' LOS' , ' WAS' ) ,
SUBPARTI TI ON q22004_sout heast _sal es VALUES ( ' MI A' , ' CHA' , ' ATL' )
) ,
PARTI TI ON q3_2004 VALUES LESS THAN ( TO_DATE( ' 1- OCT- 2004' , ' DD- MON- YYYY' ) )
TABLESPACE t s3
( SUBPARTI TI ON q32004_nor t heast _sal es VALUES ( ' NYC' , ' BOS' , ' PEN' ) ,
SUBPARTI TI ON q32004_sout hwest _sal es VALUES ( ' DFW' , ' ORL' , ' HOU' ) ,
SUBPARTI TI ON q32004_paci f i cwest _sal es VALUES ( ' SAN' , ' LOS' , ' WAS' ) ,
SUBPARTI TI ON q32004_sout heast _sal es VALUES ( ' MI A' , ' CHA' , ' ATL' )
) ,
PARTI TI ON q4_2004 VALUES LESS THAN ( TO_DATE( ' 1- J AN- 2005' , ' DD- MON- YYYY' ) )
TABLESPACE t s4
( SUBPARTI TI ON q42004_nor t heast _sal es VALUES ( ' NYC' , ' BOS' , ' PEN' ) ,
SUBPARTI TI ON q42004_sout hwest _sal es VALUES ( ' DFW' , ' ORL' , ' HOU' ) ,
SUBPARTI TI ON q42004_paci f i cwest _sal es VALUES ( ' SAN' , ' LOS' , ' WAS' ) ,
SUBPARTI TI ON q42004_sout heast _sal es VALUES ( ' MI A' , ' CHA' , ' ATL' )
)
) ;
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/ * I nt er val - Range Par t i t i oned Tabl es or Range- Range */

CREATE TABLE sal es
( pr od_i d NUMBER( 6) ,
cust _i d NUMBER,
t i me_i d DATE,
channel _i d CHAR( 1) ,
pr omo_i d NUMBER( 6) ,
quant i t y_sol d NUMBER( 3) ,
amount _sol d NUMBER( 10, 2)
)
PARTI TI ON BY RANGE ( t i me_i d) I NTERVAL ( NUMTODSI NTERVAL( 1, ' DAY' ) )
SUBPARTI TI ON BY RANGE( amount _sol d)
Page 111 Oracle DBA Code Examples

SUBPARTI TI ON TEMPLATE
( SUBPARTI TI ON p_l ow VALUES LESS THAN ( 1000) ,
SUBPARTI TI ON p_medi umVALUES LESS THAN ( 4000) ,
SUBPARTI TI ON p_hi gh VALUES LESS THAN ( 8000) ,
SUBPARTI TI ON p_ul t i mat e VALUES LESS THAN ( maxval ue) )
( PARTI TI ON bef or e_2000 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2000' , ' dd- MON- yyyy' ) ) ) ;

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

/ * I nt er val - Li st Par t i t i oned Tabl es */

CREATE TABLE sal es
( pr od_i d NUMBER( 6)
, cust _i d NUMBER
, t i me_i d DATE
, channel _i d CHAR( 1)
, pr omo_i d NUMBER( 6)
, quant i t y_sol d NUMBER( 3)
, amount _sol d NUMBER( 10, 2)
)
PARTI TI ON BY RANGE ( t i me_i d) I NTERVAL ( NUMTODSI NTERVAL( 1, ' DAY' ) )
SUBPARTI TI ON BY LI ST ( channel _i d)
SUBPARTI TI ON TEMPLATE
( SUBPARTI TI ON p_cat al og VALUES ( ' C' )
, SUBPARTI TI ON p_i nt er net VALUES ( ' I ' )
, SUBPARTI TI ON p_par t ner s VALUES ( ' P' )
, SUBPARTI TI ON p_di r ect _sal es VALUES ( ' S' )
, SUBPARTI TI ON p_t el e_sal es VALUES ( ' T' ) )
( PARTI TI ON bef or e_2000 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2000' , ' dd- MON- yyyy' ) ) ) ;
Partition Maintenance Operations
Range and list partitions cant be coalesced.
Hash partitions cant be dropped, split, or merged.
Only list partitions allow the modification of partitions by adding and dropping the partition
values.
- - Addi ng Par t i t i ons
ALTER TABLE t i cket _sal es
ADD PARTI TI ON sal es_quar t er 5 VALUES LESS THAN
( TO_DATE( ' 1- APR- 2005' , ' DD- MON- YYYY' ) ) TABLESPACE t s5;

- - Spl i t t i ng a Par t i t i on
ALTER TABLE t i cket _sal es
SPLI T PARTI TI ON t i cket _sal es01 AT ( 2000) I NTO
( PARTI TI ON t i cket _sal es01A, t i cket _sal es01B) ;

- - Mer gi ng Par t i t i ons
ALTER TABLE t i cket _sal es
MERGE PARTI TI ONS t i cket _sal es01, t i cket _sal es02 I NTO PARTI TI ON t i cket _sal es02;

- - Renami ng Par t i t i ons
ALTER TABLE RENAME PARTI TI ON f i ght _sal es01 TO quar t er l y_sal es01;

- - Exchangi ng Par t i t i ons
- - conver t a r egul ar nonpar t i t i oned t abl e i nt o a par t i t i on of a par t i t i oned t abl e
- - i t onl y r enames t he sour ce and dest i nat i on
ALTER TABLE t i cket _sal es
EXCHANGE PARTI TI ON t i cket _sal es02 WI TH t i cket _sal es03;

- - Dr oppi ng Par t i t i ons
Page 112 Oracle DBA Code Examples

- - use UPDATE GLOBAL I NDEXES keywor d i f dat a exi st s i n t he par t i t i on
ALTER TABLE t i cket _sal es DROP PARTI TI ON t i cket _sal es01;

- - Coal esci ng Par t i t i ons
- - appl i ed on hash- par t i t i oned and l i st - par t i t i oned
- - t o r educe number of par t i t i ons
ALTER TABLE t i cket _sal es COALESCE PARTI TI ON;
Setting Deferred Segment Creation
When the table (heap or partitioned) is created, no segment is assigned until a row is
inserted.
( Or acl e 11g)
- - db l evel :
show par amet er DEFERRED_SEGMENT_CREATI ON
al t er syst emset def er r ed_segment _cr eat i on=t r ue scope=bot h ;


- - t abl e l evel
cr eat e t abl e t est ( . . ) SEGMENT CREATI ON DEFERRED par t i t i on by . . ;
cr eat e t abl e t est ( . . ) SEGMENT CREATI ON I MMEDI ATE ;

- - ( 11. 2. 0. 2) I f you want t o cr eat e t he segment s f or obj ect s wher e
- - SEGMENT CREATI ON DEFERRED i s set wi t hout wai t i ng f or
- - i nser t i ng any r ows:

- - al l t he obj ect s i n a schema:
conn / as sysdba
begi n
DBMS_SPACE_ADMI N. MATERI ALI ZE_DEFERRED_SEGMENTS (
schema_name =>' SA' ) ;
end;

- - speci f i c t abl e:
begi n
DBMS_SPACE_ADMI N. MATERI ALI ZE_DEFERRED_SEGMENTS (
schema_name =>' SA' , t abl e_name=>' EMP' ) ;
end;

- - speci f i c par t i t i on
begi n
DBMS_SPACE_ADMI N. MATERI ALI ZE_DEFERRED_SEGMENTS (
schema_name =>' SA' , t abl e_name=>' EMP' ,
par t i t i on_name=>' PAR01' ) ;
end;
Creating Multiple Tables and Views in a Single Operation
If one included statement fails, non of the other statements will be executed.
CREATE SCHEMA AUTHORI ZATI ON scot t
CREATE TABLE dept (
dept no NUMBER( 3, 0) PRI MARY KEY,
dname VARCHAR2( 15) ,
l oc VARCHAR2( 25) )
CREATE TABLE emp (
empno NUMBER( 5, 0) PRI MARY KEY,
ename VARCHAR2( 15) NOT NULL,
j ob VARCHAR2( 10) ,
mgr NUMBER( 5, 0) ,
Page 113 Oracle DBA Code Examples

hi r edat e DATE DEFAULT ( sysdat e) ,
sal NUMBER( 7, 2) ,
commNUMBER( 7, 2) ,
dept no NUMBER( 3, 0) NOT NULL
CONSTRAI NT dept _f key REFERENCES dept )
CREATE VI EWsal es_st af f AS
SELECT empno, ename, sal , comm
FROM emp
WHERE dept no = 30
WI TH CHECK OPTI ON CONSTRAI NT sal es_st af f _cnst
GRANT SELECT ON sal es_st af f TO human_r esour ces;
Collecting Object Statistics
Collecting Index Statistics
granularity parameter takes:
o 'DEFAULT' - gathers global and partition-level statistics
o 'SUBPARTITION' - gathers subpartition-level statistics
o 'PARTITION' - gathers partition-level statistics
o 'GLOBAL' - gathers global statistics
o 'ALL' - gathers all (subpartition, partition, and global)
begi n
DBMS_STATS. GATHER_I NDEX_STATS (
ownname =>' HR' ,
i ndname =>' EMP_DEPARTMENT_I X' ,
par t name =>' ' , - - DEFAULT NULL
est i mat e_per cent => DBMS_STATS. AUTO_SAMPLE_SI ZE, - - 0. 1 t o 100 DEFAULT
t o_est i mat e_per cent _t ype ( GET_PARAM( ' ESTI MATE_PERCENT' ) )
st at t ab => nul l , - - DEFAULT NULL
st at i d => nul l , - - DEFAULT NULL
st at own => nul l , - - DEFAULT NULL
degr ee => nul l , - - par al l el i smNUMBER DEFAULT
t o_degr ee_t ype( get _par am( ' DEGREE' ) )
gr anul ar i t y => ' ALL' , - - DEFAULT GET_PARAM( ' GRANULARI TY' )
no_i nval i dat e => f al se, - - BOOLEAN DEFAULT t o_no_i nval i dat e_t ype
( GET_PARAM( ' NO_I NVALI DATE' ) ) ,
f or ce => f al se - - BOOLEAN DEFAULT FALSE
) ;
end;
/
Collecting Table Statistics
method_opt Accepts:
o FOR ALL [INDEXED | HIDDEN] COLUMNS [size_clause]
o FOR COLUMNS [size clause] column|attribute [size_clause] [,column|attribute
[size_clause]...]
o size_clause is defined as size_clause := SIZE {integer | REPEAT | AUTO | SKEWONLY}
- integer : Number of histogram buckets. Must be in the range [1,254].
- REPEAT : Collects histograms only on the columns that already have histograms.
- AUTO : Oracle determines the columns to collect histograms based on data distribution and
the workload of the columns.
Page 114 Oracle DBA Code Examples

- SKEWONLY : Oracle determines the columns to collect histograms based on the data
distribution of the columns.
The default is FOR ALL COLUMNS SIZE AUTO
granularity takes: 'ALL', 'AUTO', 'DEFAULT', 'GLOBAL', 'GLOBAL AND PARTITION',
'PARTITION', 'SUBPARTITION'
begi n
DBMS_STATS. GATHER_TABLE_STATS (
ownname =>' HR' ,
t abname =>' NAMES' ,
par t name =>' ' ,
est i mat e_per cent => DBMS_STATS. AUTO_SAMPLE_SI ZE, - - NUMBER DEFAULT
t o_est i mat e_per cent _t ype( get _par am( ' ESTI MATE_PERCENT' ) )
bl ock_sampl e => f al se, - - DEFAULT FALSE
met hod_opt =>' FOR ALL COLUMNS SI ZE AUTO' , - - DEFAULT
get _par am( ' METHOD_OPT' )
degr ee =>1, - - DEFAULT t o_degr ee_t ype( get _par am( ' DEGREE' ) )
gr anul ar i t y =>' ALL' , - - DEFAULT GET_PARAM( ' GRANULARI TY' )
cascade =>t r ue, - - t o_cascade_t ype( get _par am( ' CASCADE' ) )
st at t ab =>' ' ,
st at i d =>' ' ,
st at own =>' ' ,
no_i nval i dat e => f al se, - - DEFAULT t o_no_i nval i dat e_t ype
( get _par am( ' NO_I NVALI DATE' ) )
f or ce => f al se
) ;
end;
/
Collecting Schema Statistics
method_opt Accepts:
o FOR ALL [INDEXED | HIDDEN] COLUMNS [size_clause]
o FOR COLUMNS [size clause] column|attribute [size_clause] [,column|attribute
[size_clause]...]
o size_clause is defined as size_clause := SIZE {integer | REPEAT | AUTO | SKEWONLY}
- integer : Number of histogram buckets. Must be in the range [1,254].
- REPEAT : Collects histograms only on the columns that already have histograms.
- AUTO : Oracle determines the columns to collect histograms based on data distribution and
the workload of the columns.
- SKEWONLY : Oracle determines the columns to collect histograms based on the data
distribution of the columns.
The default is FOR ALL COLUMNS SIZE AUTO
granularity takes: 'ALL', 'AUTO', 'DEFAULT', 'GLOBAL', 'GLOBAL AND PARTITION',
'PARTITION', 'SUBPARTITION'
options takes : GATHER, GATHER AUTO, GATHER STALE, GATHER EMPTY. It also takes
LIST STALE, LIST EMPTY, LIST AUTO (you should use an overloaded procedure different
from the example above).
Note: GET_PARAM('..')is used till version 10g. In 11g, DBMS_STATS.GET_PREFS should be
used.
begi n
DBMS_STATS. GATHER_SCHEMA_STATS (
ownname =>' HR' ,
Page 115 Oracle DBA Code Examples

est i mat e_per cent =>DBMS_STATS. AUTO_SAMPLE_SI ZE, - - 0. 1- 100 DEFAULT
t o_est i mat e_per cent _t ype( get _par am( ' ESTI MATE_PERCENT' ) )
bl ock_sampl e =>FALSE,
met hod_opt =>' FOR ALL COLUMNS SI ZE AUTO' , - - DEFAULT get _par am( ' METHOD_OPT' )
degr ee =>NULL, - - t o_degr ee_t ype( get _par am( ' DEGREE' ) ) ,
gr anul ar i t y =>' ALL' , - - DEFAULT GET_PARAM( ' GRANULARI TY' ) ,
cascade =>TRUE, - - DEFAULT t o_cascade_t ype( get _par am( ' CASCADE' ) ) ,
st at t ab =>' ' , - - DEFAULT NULL,
st at i d =>' ' , - - DEFAULT NULL,
opt i ons =>' GATHER' , - - DEFAULT ' GATHER' ,
st at own =>' ' , - - DEFAULT NULL,
no_i nval i dat e =>f al se, - - DEFAULT t o_no_i nval i dat e_t ype
( get _par am( ' NO_I NVALI DATE' )
f or ce => FALSE) ;
end;
/


begi n
DBMS_STATS. GATHER_SCHEMA_STATS (
ownname =>' HR' ,
est i mat e_per cent =>NULL,
met hod_opt =>' FOR ALL COLUMNS SI ZE AUTO' ,
degr ee =>DBMS_STATS. DEFAULT_DEGREE,
gr anul ar i t y =>' ALL' ,
cascade =>TRUE,
opt i ons =>' GATHER AUTO' ) ;
end;
/
Validating Tables, Indexes, Clusters, and Materialized Views
Validating an object means verifying the integrity of the structure of it.
If a corruption is reported, re-create the object.
ANALYZE TABLE emp VALI DATE STRUCTURE;
ANALYZE TABLE emp VALI DATE STRUCTURE CASCADE;
ANALYZE TABLE emp VALI DATE STRUCTURE CASCADE ONLI NE;
ANALYZE I NDEX l oc_count r y_i x VALI DATE STRUCTURE;
Listing Chained and Migrated Rows of Tables and Clusters
- - set up
- - f ol l owi ng scr i pt cr eat es CHAI NED_ROWS t abl e
@$ORACLE_HOME$\ RDBMS\ ADMI N\ ut l chai n. sql

- - handl i ng chai ned and mi gr at ed r ows
- - 1
ANALYZE TABLE or der _hi st LI ST CHAI NED ROWS;
ANALYZE CLUSTER emp_dept LI ST CHAI NED ROWS I NTO CHAI NED_ROWS;
- - 2
SELECT * FROM CHAI NED_ROWS
WHERE TABLE_NAME = ' ORDER_HI ST' ;
- - 3 i f you have t oo many r ows
- - i nt er medi at e t abl e t o hol d t he chai ned r ows
Page 116 Oracle DBA Code Examples

CREATE TABLE i nt _or der _hi st
AS SELECT *
FROM or der _hi st
WHERE ROWI D I N
( SELECT HEAD_ROWI D
FROM CHAI NED_ROWS
WHERE TABLE_NAME = ' ORDER_HI ST' ) ;
- - 4
DELETE FROM or der _hi st
WHERE ROWI D I N
( SELECT HEAD_ROWI D
FROM CHAI NED_ROWS
WHERE TABLE_NAME = ' ORDER_HI ST' ) ;
- - 5
I NSERT I NTO or der _hi st
SELECT * FROM i nt _or der _hi st ;
- - 6
DROP TABLE i nt _or der _hi st or y;
- - 7
DELETE FROM CHAI NED_ROWS WHERE TABLE_NAME = ' ORDER_HI ST' ;
- - 8 Use t he ANALYZE st at ement agai n, and quer y t he out put t abl e. Any r ows t hat
appear i n t he out put t abl e ar e chai ned. You can el i mi nat e chai ned r ows onl y by
i ncr easi ng your dat a bl ock si ze.
Truncating Tables or Clusters
TRUNCATE TABLE emp_dept DROP STORAGE; - - def aul t , l eave space of MI NI EXTENTS
TRUNCATE TABLE emp_dept REUSE STORAGE;
TRUNCATE TABLE emp DROP ALL STORAGE; - - al l segment s wi l l be dr opped
Enabling and Disabling Triggers
sel ect t abl e_name, t r i gger _name f r omuser _t r i gger s wher e st at us=' DI SABLED' ;
ALTER TRI GGER r eor der ENABLE;
ALTER TRI GGER r eor der DI SABLE;
ALTER TABLE i nvent or y ENABLE ALL TRI GGERS;
ALTER TABLE i nvent or y DI SABLE ALL TRI GGERS;
Managing Integrity Constraints
Setting Constraint States and Deferability
Constraint states:
ENABLE, VALIDATE : inserts are checked, existing data in the table is checked
ENABLE, NOVALIDATE (fast): inserts are checked, existing data in the table is NOT checked
DISABLE, VALIDATE : DML on constrained columns disallowed
DISABLE, NOVALIDATE : inserts are NOT checked, existing data in the table is NOT
checked
Constraint Checking (Deferability)
Nondeferred: enforced at the end of every DML statement.
Deferred : enforced when a transaction is committed.
see next section for altering a constraint
Page 117 Oracle DBA Code Examples

CONSTRAI NT . . . [ [ NOT] DEFERRABLE I NI TI ALLY [ DEFERRED| I MMEDI ATE] ] [ ENABLE| DI SABLE]
[ VALI DATE| NOVALI DATE]

ALTER SESSI ON SET CONSTRAI NT[ S] = {I MMEDI ATE| DEFERRED| DEFAULT}

- - t akes ef f ect i n TRANSACTI ON l evel
- - t he t r ans i s r ol l ed back, i f COMMI T f ai l s
- - you can use SET CONSTRAI NTS ALL I MMEDI ATE t o see whet her COMMI T wi l l f ai l bef or e i t
- - r eal l y commi t s
SET CONSTRAI NT | CONSTRAI NTS {const r ai nt | ALL } {I MMEDI ATE| DEFERRED}

SELECT CONSTRAI NT_NAME, CONSTRAI NT_TYPE, STATUS, DEFERRABLE, DEFERRED, VALI DATED
FROM USER_CONSTRAI NTS
WHERE CONSTRAI NT_NAME=' ' ;
ALTER TABLE emp ADD PRI MARY KEY ( empno) DI SABLE;
ALTER TABLE count r i es ADD ( UNI QUE( count r y_name) ENABLE NOVALI DATE) ;
ALTER TABLE myTabl e ADD CONSTRAI NT uq UNI QUE ( i d) DEFERRABLE I NI TI ALLY
DEFERRED;
- - t akes ef f ect i n TRANSACTI ON l evel
- - not def er r abl e const r ai nt s ar e NOT af f ect ed
set const r ai nt j ob_f k def er r ed;
set const r ai nt j ob_f k i mmedi at e;
set const r ai nt s al l def er r ed;
Modifying, Renaming, or Dropping Existing Integrity Constraints
ALTER TABLE dept DI SABLE CONSTRAI NT dname_ukey;
ALTER TABLE dept DI SABLE PRI MARY KEY KEEP I NDEX, DI SABLE UNI QUE ( dname, l oc)
KEEP I NDEX;
- - al l FKs ar e al so di sabl ed
ALTER TABLE dept DI SABLE PRI MARY KEY CASCADE;
ALTER TABLE dept ENABLE NOVALI DATE CONSTRAI NT dname_ukey;
ALTER TABLE dept ENABLE NOVALI DATE PRI MARY KEY, ENABLE NOVALI DATE UNI QUE
( dname, l oc) ;
ALTER TABLE dept MODI FY CONSTRAI NT dname_key VALI DATE;
ALTER TABLE dept MODI FY PRI MARY KEY ENABLE NOVALI DATE;

ALTER TABLE dept RENAME CONSTRAI NT dname_ukey TO dname_uni key;
ALTER TABLE dept DROP UNI QUE ( dname, l oc) ;
ALTER TABLE emp DROP PRI MARY KEY KEEP I NDEX, DROP CONSTRAI NT dept _f key;
Reporting Constraint Exceptions
The target is to put all the rows that voilate sepcific integrity contraints in the
EXCEPTIONS table.
1. cr eat e t he EXCEPTI ONS t abl e
ORACLE_HOME\ RDBMS\ ADMI N\ ut l excpt . sql
2.
ALTER TABLE dept ENABLE PRI MARY KEY EXCEPTI ONS I NTO EXCEPTI ONS;
3.
SELECT * FROM EXCEPTI ONS;
4. j oi n t he mast er t abl e wi t h t he EXCEPTI ONS
SELECT dept no, dname, l oc FROM dept , EXCEPTI ONS
WHERE EXCEPTI ONS. const r ai nt = ' SYS_C00610'
AND dept . r owi d = EXCEPTI ONS. r ow_i d;
5. f i x t he i ncor r ect dat a
6.
DELETE FROM EXCEPTI ONS WHERE const r ai nt = ' SYS_C00610' ;
Page 118 Oracle DBA Code Examples

Obtaining Information on Constraints
sel ect * f r omUSER_CONSTRAI NTS;
sel ect * f r omUSER_CONS_COLUMNS;
Renaming Schema Objects
r ename myt abl e t o myt abl e2
Managing Object Dependencies
Manually Recompiling Views Procedures and Packages
ALTER VI EWemp_dept COMPI LE;
ALTER PROCEDURE updat e_sal ar y COMPI LE;
ALTER PACKAGE acct _mgmt COMPI LE BODY;
ALTER PACKAGE acct _mgmt COMPI LE PACKAGE;
Switching to a Different Schema
CONNECT scot t / t i ger
ALTER SESSI ON SET CURRENT_SCHEMA = j oe;
- - t he f ol l owi ng i s equi val ent t o SELECT * FROM j oe. emp
SELECT * FROM emp;
Using DBMS_METADATA to Display Information About Schema Objects
SET LONG 9999
- - st or age cl auses ar e not t o be r et ur ned
EXECUTE
DBMS_METADATA. SET_TRANSFORM_PARAM( DBMS_METADATA. SESSI ON_TRANSFORM, ' STORAGE' , f
al se) ;
- - f et ch t he DDL of al l t abl es ( r el at i onal and obj ect s)
SELECT DBMS_METADATA. GET_DDL( ' TABLE' , u. t abl e_name)
FROM USER_ALL_TABLES u
WHERE u. nest ed=' NO'
AND ( u. i ot _t ype i s nul l or u. i ot _t ype=' I OT' ) ;
- - r et ur n t he par amet er val ue t o i t s def aul t
EXECUTE
DBMS_METADATA. SET_TRANSFORM_PARAM( DBMS_METADATA. SESSI ON_TRANSFORM, ' DEFAULT' ) ;
Specifying Storage Parameters at Object Creation
Objects include: Tables, Clusters, Indexes, LOBs, Varrays, Nested Tables, MViews
CREATE TABLE MYTABLE( COL1 NUMBER, COL2 VARCHAR2( 100) )
STORAGE ( I NI TI AL 10M BUFFER_POOL DEFAULT) ; - - MI NEXTENTS

SELECT EXTENT_I D, BYTES/ 1024 KB
FROM DBA_EXTENTS
WHERE SEGMENT_TYPE=' TABLE' AND SEGMENT_NAME=' MYTABLE' ;
Page 119 Oracle DBA Code Examples


CREATE TABLE . . .
( . . , CONSTRAI NT UQ) CON UNI QUE ( PK_i d)
USI NG I NDEX
TABLESPACE MYTBS
STORAGE ( I NI TI AL 8K ) ) ;

CREATE MATERI ALI ZED VI EW. .
TABLESPACE MYTBS
STORAGE ( I NI TI AL 50K)
USI NG I NDEX STORAGE ( I NI TI AL 25K)
. . .

Managing Resumable Space Allocation
Enabling Resumable Space Allocation
- - t he user shoul d have t hi s pr i v
gr ant RESUMABLE t o hr ;

sel ect val ue f r omv$par amet er wher e upper ( name) =' RESUMABLE_TI MEOUT' ;

- - t o enabl e r esumabl e space al l ocat i on syst emwi de
- - 0 t o di sabl e
al t er syst emset RESUMABLE_TI MEOUT = 3600;
- - or i n sessi on l evel
al t er sessi on set RESUMABLE_TI MEOUT = 3600;

- - besi de t he RESUMABLE_TI MEOUT par amet er
ALTER SESSI ON ENABLE RESUMABLE;
ALTER SESSI ON ENABLE RESUMABLE TI MEOUT 3600; - - def aul t 7200
- - 4340 i s SI D. NULL f or cur r ent sessi on
EXEC DBMS_RESUMABLE. set _sessi on_t i meout ( 4340, 18000) ;
ALTER SESSI ON DI SABLE RESUMABLE;

- - nami ng r esumabl e st at ement s
- - def aul t i s ' User user name( user i d) , Sessi on sessi oni d, I nst ance i nst ancei d'
- - name i s used i n t he DBA_RESUMABLE and USER_RESUMABLE vi ews
ALTER SESSI ON ENABLE RESUMABLE TI MEOUT 3600 NAME ' i nser t i nt o t abl e' ;
Detecting Suspended Statements
The AFTER SUSPEND System Event and Trigger is executed after a SQL statement has
been suspended.
- - sour ce: Or acl e Document at i on
CREATE OR REPLACE TRI GGER r esumabl e_def aul t
AFTER SUSPEND ON DATABASE
DECLARE
/ * decl ar e t r ansact i on i n t hi s t r i gger i s aut onomous */
/ * t hi s i s not r equi r ed because t r ansact i ons wi t hi n a t r i gger ar e al ways
aut onomous */
PRAGMA AUTONOMOUS_TRANSACTI ON;
cur _si d NUMBER;
cur _i nst NUMBER;
er r no NUMBER;
Page 120 Oracle DBA Code Examples

er r _t ype VARCHAR2;
obj ect _owner VARCHAR2;
obj ect _t ype VARCHAR2;
t abl e_space_name VARCHAR2;
obj ect _name VARCHAR2;
sub_obj ect _name VARCHAR2;
er r or _t xt VARCHAR2;
msg_body VARCHAR2;
r et _val ue BOOLEAN;
mai l _conn UTL_SMTP. CONNECTI ON;
BEGI N
- - Get sessi on I D
SELECT DI STI NCT( SI D) I NTO cur _SI D FROM V$MYSTAT;

- - Get i nst ance number
cur _i nst : = user env( ' i nst ance' ) ;

- - Get space er r or i nf or mat i on
r et _val ue : =
DBMS_RESUMABLE. SPACE_ERROR_I NFO( er r _t ype, obj ect _t ype, obj ect _owner , t abl e_space
_name, obj ect _name, sub_obj ect _name) ;

/ *
- - I f t he er r or i s r el at ed t o undo segment s, l og er r or , send emai l
- - t o DBA, and abor t t he st at ement . Ot her wi se, set t i meout t o 8 hour s.
- -
- - sys. r bs_er r or i s a t abl e whi ch i s t o be
- - cr eat ed by a DBA manual l y and def i ned as
- - ( sql _t ext VARCHAR2( 1000) , er r or _msg VARCHAR2( 4000) , suspend_t i me DATE)
*/

I F OBJ ECT_TYPE = ' UNDO SEGMENT' THEN
/ * LOG ERROR */
I NSERT I NTO sys. r bs_er r or (
SELECT SQL_TEXT, ERROR_MSG, SUSPEND_TI ME
FROM DBA_RESUMABLE
WHERE SESSI ON_I D = cur _si d AND I NSTANCE_I D = cur _i nst ) ;

SELECT ERROR_MSG I NTO er r or _t xt FROM DBMS_RESUMABLE
WHERE SESSI ON_I D = cur _si d and I NSTANCE_I D = cur _i nst ;

- - Send emai l t o r ecei pi ent vi a UTL_SMTP package
msg_body: =' Subj ect : Space Er r or Occur r ed
Space l i mi t r eached f or undo segment ' | | obj ect _name | |
on ' | | TO_CHAR( SYSDATE, ' Mont h dd, YYYY, HH: MI am' ) | |
' . Er r or message was ' | | er r or _t xt ;
mai l _conn : = UTL_SMTP. OPEN_CONNECTI ON( ' l ocal host ' , 25) ;
UTL_SMTP. HELO( mai l _conn, ' l ocal host ' ) ;
UTL_SMTP. MAI L( mai l _conn, ' sender @l ocal host ' ) ;
UTL_SMTP. RCPT( mai l _conn, ' r eci pi ent @l ocal host ' ) ;
UTL_SMTP. DATA( mai l _conn, msg_body) ;
UTL_SMTP. QUI T( mai l _conn) ;
- - Abor t t he st at ement
DBMS_RESUMABLE. ABORT( cur _si d) ;
ELSE
- - Set t i meout t o 8 hour s
DBMS_RESUMABLE. SET_TI MEOUT( 28800) ;
Page 121 Oracle DBA Code Examples

END I F;

/ * commi t aut onomous t r ansact i on */
COMMI T;
END;
/
Obtaining Information about Suspended Statements
SELECT USER_I D, SESSI ON_I D, I NSTANCE_I D,
COORD_I NSTANCE_I D, COORD_SESSI ON_I D, STATUS,
TI MEOUT, START_TI ME, SUSPEND_TI ME,
RESUME_TI ME, NAME, SQL_TEXT,
ERROR_NUMBER, ERROR_PARAMETER1, ERROR_PARAMETER2,
ERROR_PARAMETER3, ERROR_PARAMETER4, ERROR_PARAMETER5, ERROR_MSG
FROM DBA_RESUMABLE;

SELECT SI D, SEQ#, EVENT,
P1TEXT, P1, P1RAW,
P2TEXT, P2, P2RAW,
P3TEXT, P3, P3RAW,
WAI T_CLASS_I D, WAI T_CLASS#, WAI T_CLASS,
WAI T_TI ME, SECONDS_I N_WAI T, STATE
FROM V$SESSI ON_WAI T
WHERE EVENT LI KE ' %st at ement suspended%'

exec DBMS_RESUMABLE.ABORT( 159) ;
sel ect DBMS_RESUMABLE.GET_SESSION_TIMEOUT( 159) f r omdual ;
exec DBMS_RESUMABLE.SET_SESSION_TIMEOUT( sessi onI D=>159, t i meout =>8000) ;
Reclaiming Wasted Space
Displaying Information About Space Usage for Schema Objects
/ * Usi ng PL SQL */
SET SERVEROUTPUT ON
decl ar e
- - I N var s
v_segment _owner VARCHAR2( 30) : =' HR' ;
v_segment _name VARCHAR2( 30) : =' NAMES' ;
v_segment _t ype VARCHAR2( 30) : =' TABLE' ; - - TABLE, TABLE PARTI TI ON, TABLE
SUBPARTI TI ON, I NDEX, I NDEX PARTI TI ON, I NDEX SUBPARTI TI ON, CLUSTER, LOB, LOB
PARTI TI ON, LOB SUBPARTI TI ON
v_par t i t i on_name VARCHAR2( 30) : =NULL;
- - OUT var s
v_t ot al _bl ocks NUMBER;
v_t ot al _byt es NUMBER;
v_unused_bl ocks NUMBER;
v_unused_byt es NUMBER;
v_l ast _used_ext ent _f i l e_i d NUMBER; - - f i l e i d of l ast Ext end cont ai ni ng dat a
v_f i l ename var char 2( 300) ;
v_l ast _used_ext ent _bl ock_i d NUMBER;
v_l ast _used_bl ock NUMBER;
begi n
DBMS_SPACE. UNUSED_SPACE (
segment _owner => v_segment _owner ,
segment _name => v_segment _name ,
segment _t ype => v_segment _t ype,
Page 122 Oracle DBA Code Examples

t ot al _bl ocks => v_t ot al _bl ocks ,
t ot al _byt es => v_t ot al _byt es ,
unused_bl ocks => v_unused_bl ocks,
unused_byt es => v_unused_byt es ,
l ast _used_ext ent _f i l e_i d => v_l ast _used_ext ent _f i l e_i d ,
l ast _used_ext ent _bl ock_i d =>v_l ast _used_ext ent _bl ock_i d ,
l ast _used_bl ock => v_l ast _used_bl ock ,
par t i t i on_name => v_par t i t i on_name ) ;

i f v_l ast _used_ext ent _f i l e_i d i s not nul l t hen
sel ect f i l e_name i nt o v_f i l ename f r omdba_dat a_f i l es wher e f i l e_i d =
v_l ast _used_ext ent _f i l e_i d ;
end i f ;

DBMS_OUTPUT. PUT_LI NE( ' Tot al Bl ocks : ' | | v_t ot al _bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' Tot al MByt es : ' | | t o_char ( v_t ot al _byt es/ 1024/ 1024) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Unused Bl ocks: ' | | v_unused_bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' Unused MByt es: ' | | t o_char ( v_unused_byt es/ 1024/ 1024) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Fi l e of Last Ext ent Cont ai ni ng Dat a:
' | | ' ( ' | | v_l ast _used_ext ent _f i l e_i d | | ' ) ' | | v_f i l ename ) ;
DBMS_OUTPUT. PUT_LI NE( ' St ar t i ng Bl ock I D of t he Last Ext ent Cont ai ni ng Dat a:
' | | v_l ast _used_bl ock ) ;
DBMS_OUTPUT. PUT_LI NE( ' Last Bl ock Wi t hi n Thi s Ext ent Whi ch Cont ai ns Dat a:
' | | v_l ast _used_bl ock ) ;
end;
/

- - space usage of dat a bl ocks under t he segment Hi gh Wat er Mar k wi t h
- - aut o segment space management Tabl espaces
- - f ol l owi ng code i n Or acl e 10g
set ser ver out put on

decl ar e
- - I N var s
v_segment _owner VARCHAR2( 100) : =' HR' ;
v_segment _name VARCHAR2( 100) : =' NAMES2' ;
v_segment _t ype VARCHAR2( 100) : =' TABLE' ;
v_par t i t i on_name VARCHAR2( 100) : =nul l ;

- - OUT var s
v_unf or mat t ed_bl ocks NUMBER;
v_unf or mat t ed_byt es NUMBER;
v_f s1_bl ocks NUMBER;
v_f s1_byt es NUMBER;
v_f s2_bl ocks NUMBER;
v_f s2_byt es NUMBER;
v_f s3_bl ocks NUMBER;
v_f s3_byt es NUMBER;
v_f s4_bl ocks NUMBER;
v_f s4_byt es NUMBER;
v_f ul l _bl ocks NUMBER;
v_f ul l _byt es NUMBER;
v_segment _si ze_bl ocks NUMBER;
v_segment _si ze_byt es NUMBER;
v_used_bl ocks NUMBER;
v_used_byt es NUMBER;
v_expi r ed_bl ocks NUMBER;
v_expi r ed_byt es NUMBER;
Page 123 Oracle DBA Code Examples

v_unexpi r ed_bl ocks NUMBER;
v_unexpi r ed_byt es NUMBER;
begi n
DBMS_SPACE. SPACE_USAGE(
segment _owner => v_segment _owner ,
segment _name => v_segment _name ,
segment _t ype => v_segment _t ype ,
unf or mat t ed_bl ocks =>v_unf or mat t ed_bl ocks ,
unf or mat t ed_byt es => v_unf or mat t ed_byt es ,
f s1_bl ocks =>v_f s1_bl ocks ,
f s1_byt es => v_f s1_byt es ,
f s2_bl ocks =>v_f s2_bl ocks ,
f s2_byt es => v_f s2_byt es ,
f s3_bl ocks =>v_f s3_bl ocks ,
f s3_byt es => v_f s3_byt es ,
f s4_bl ocks =>v_f s4_bl ocks ,
f s4_byt es => v_f s4_byt es ,
f ul l _bl ocks => v_f ul l _bl ocks ,
f ul l _byt es =>v_f ul l _byt es ,
par t i t i on_name => v_par t i t i on_name ) ;

DBMS_OUTPUT. PUT_LI NE( ' Fr ee Space i n MB: ' ) ;
DBMS_OUTPUT. PUT_LI NE( ' Unf or mat t ed Mbyt es: ' | | v_unf or mat t ed_byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' Fr ee Space i n MB: ' ) ;
DBMS_OUTPUT. PUT_LI NE( ' 0 t o 25% f r ee space: ' | | v_f s1_byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' 25 t o 50% f r ee space: ' | | v_f s2_byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' 50 t o 75% f r ee space: ' | | v_f s3_byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' 75 t o 100%f r ee space: ' | | v_f s4_byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' Ful l Mbyt es : ' | | v_f ul l _byt es/ 1024/ 1024) ;
DBMS_OUTPUT. PUT_LI NE( ' Fr ee Space i n Bl ocks: ' ) ;
DBMS_OUTPUT. PUT_LI NE( ' Unf or mat t ed Bl ocks: ' | | v_unf or mat t ed_bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' 0 t o 25% f r ee space: ' | | v_f ul l _bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' 25 t o 50% f r ee space: ' | | v_f s2_bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' 50 t o 75% f r ee space: ' | | v_f s3_bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' 75 t o 100%f r ee space: ' | | v_f s4_bl ocks) ;
DBMS_OUTPUT. PUT_LI NE( ' Ful l bl ocks : ' | | v_f ul l _bl ocks) ;

except i on
when ot her s t hen
i f sql code = ' - 942' t hen
DBMS_OUTPUT. PUT_LI NE( ' Obj ect Does not Exi st . ' ) ;
el se
r ai se;
end i f ;
end;
/


/ * Usi ng Vi ews */
- - segment i nf o
sel ect OWNER, SEGMENT_NAME, PARTI TI ON_NAME, SEGMENT_TYPE, S. TABLESPACE_NAME,
HEADER_FI LE, HEADER_BLOCK, S. BYTES/ 1024/ 1024 SEGMENT_SI ZE_MB,
D. BLOCKS SEGMENT_BLOCKS, EXTENTS, S. I NI TI AL_EXTENT,
S. NEXT_EXTENT NEXT_EXTENT_SI ZE, S. MI N_EXTENTS, S. MAX_EXTENTS, S. PCT_I NCREASE,
FREELI STS, FREELI ST_GROUPS, D. RELATI VE_FNO, D. FI LE_NAME
f r omDBA_SEGMENTS S, DBA_TABLESPACES T, DBA_DATA_FI LES D
wher e S. TABLESPACE_NAME = T. TABLESPACE_NAME AND T. TABLESPACE_NAME =
Page 124 Oracle DBA Code Examples

D. TABLESPACE_NAME
AND S. RELATI VE_FNO = D. RELATI VE_FNO
AND T. TABLESPACE_NAME NOT I N ( ' SYSAUX' , ' SYSTEM' )
or der BY S. TABLESPACE_NAME;

- - ext ent i nf o
SELECT EXTENT_I D, E. BLOCK_I D, E. BYTES/ 1024 EXTENT_SI ZE_KB,
E. OWNER, E. SEGMENT_NAME, E. PARTI TI ON_NAME,
E. SEGMENT_TYPE, D. FI LE_NAME, S. TABLESPACE_NAME, HEADER_FI LE,
HEADER_BLOCK SEG_HEADER_BLOCK, S. BYTES/ 1024/ 1024 SEGMENT_SI ZE_MB, D. BLOCKS
SEGMENT_BLOCKS, EXTENTS SEG_EXTENTS
FROM DBA_EXTENTS E, DBA_SEGMENTS S, DBA_DATA_FI LES D
WHERE E. OWNER=S. OWNER AND E. SEGMENT_NAME = S. SEGMENT_NAME
AND NVL( E. PARTI TI ON_NAME, ' 0' ) = NVL( S. PARTI TI ON_NAME, ' 0' )
AND E. SEGMENT_TYPE = S. SEGMENT_TYPE
AND E. FI LE_I D = D. FI LE_I D
AND S. TABLESPACE_NAME NOT I N ( ' SYSAUX' , ' SYSTEM' )
ORDER BY E. SEGMENT_NAME, E. OWNER, E. PARTI TI ON_NAME, E. EXTENT_I D;

- - Segment t hat cannot al l ocat e addi t i onal ext ent s
SELECT a. SEGMENT_NAME, a. SEGMENT_TYPE, a. TABLESPACE_NAME, a. OWNER
FROM DBA_SEGMENTS a
WHERE a. NEXT_EXTENT >= ( SELECT MAX( b. BYTES)
FROM DBA_FREE_SPACE b
WHERE b. TABLESPACE_NAME = a. TABLESPACE_NAME)
OR a. EXTENTS = a. MAX_EXTENTS
OR a. EXTENTS = ' 8192' ; - - dat a_bl ock_si ze

- - f r ee ext ent s wi t hi n t abl espaces
SELECT F. TABLESPACE_NAME, F. FI LE_I D, F. BLOCK_I D,
F. BYTES/ 1024/ 1024 FREE_MB, D. FI LE_NAME
FROM DBA_FREE_SPACE F, DBA_DATA_FI LES D
WHERE F. FI LE_I D = D. FI LE_I D
UNI ON
SELECT F. TABLESPACE_NAME, TO_NUMBER( ' ' ) AS FI LE_I D, TO_NUMBER( ' ' ) AS BLOCK_I D,
SUM( F. BYTES/ 1024/ 1024) FREE_MB, TO_CHAR( ' ' ) AS FI LE_NAME
FROM DBA_FREE_SPACE F
GROUP BY F. TABLESPACE_NAME, TO_NUMBER( ' ' ) , TO_NUMBER( ' ' ) , TO_CHAR( ' ' )
ORDER BY TABLESPACE_NAME;
Segment Advisor
The Automatic Segment Advisor is started by a Scheduler job that is configured to run
during the default maintenance window(s).
Input for DBMS_ADVISOR.CREATE_OBJECT
ATTR4 i s unused. Speci f y NULL
OBJ ECT_TYPE ATTR1 ATTR2 ATTR3
TABLESPACE t bs name
TABLE schema name t abl e name
I NDEX schema name i ndex name
TABLE PARTI TI ON schema name t abl e name t abl e par t i t i on name
I NDEX PARTI TI ON schema name i ndex name i ndex par t i t i on name
TABLE SUBPART. schema name t abl e name t abl e subpar t i t i on name
I NDEX SUBPART. schema name i ndex name i ndex subpar t i t i on name
LOB schema name segment name
LOB PARTI TI ON schema name segment name l ob par t i t i on name
LOB SUBPART. schema name segment name l ob subpar t i t i on name

- - obj ect pr i v EXECUTE ON DBMS_ADVI SOR or t he syst empr i v ADVI SOR

Page 125 Oracle DBA Code Examples

- - r un Segment Advi sor on hr . empl oyees
var i abl e i d number ;
decl ar e
v_name var char 2( 100) ;
v_descr var char 2( 500) ;
obj _i d number ;
begi n
v_name: =' Manual _Empl oyees' ;
v_descr : =' Segment Advi sor Exampl e' ;
dbms_advi sor . cr eat e_t ask (
advi sor _name => ' Segment Advi sor ' ,
t ask_i d => : i d,
t ask_name => v_name,
t ask_desc => v_descr ) ;

- - i dent i f y t he t ar get obj ect
dbms_advi sor . cr eat e_obj ect (
t ask_name => v_name,
obj ect _t ype => ' TABLE' ,
at t r 1 => ' HR' ,
at t r 2 => ' EMPLOYEES' ,
at t r 3 => NULL,
at t r 4 => NULL,
at t r 5 => NULL,
obj ect _i d => obj _i d) ;

dbms_advi sor . set _t ask_par amet er (
t ask_name => v_name,
par amet er => ' r ecommend_al l ' ,
val ue => ' TRUE' ) ;
dbms_advi sor . execut e_t ask( v_name) ;
end;
/

- - vi ewi ng segment r esul t s
- - asa_r ecommendat i ons ( al l _r uns i n var char 2 DEFAULT ' TRUE' ,
- - show_manual i n var char 2 DEFAULT ' TRUE' ,
- - show_f i ndi ngs i n var char 2 DEFAULT ' FALSE' )
sel ect t abl espace_name, segment _name, segment _t ype, par t i t i on_name,
r ecommendat i ons, c1 f r om
t abl e( dbms_space. asa_r ecommendat i ons( ' TRUE' , ' TRUE' , ' TRUE' ) ) ;

sel ect * f r omt abl e( dbms_space. asa_r ecommendat i ons( ' TRUE' , ' TRUE' , ' TRUE' ) ) ;

- - al t er nat i vel y use DBA_ADVI SOR_*
SELECT OWNER, REC_I D, TASK_I D,
TASK_NAME, FI NDI NG_I D, TYPE,
RANK, PARENT_REC_I DS, BENEFI T_TYPE,
BENEFI T, ANNOTATI ON_STATUS, FLAGS
FROM DBA_ADVISOR_RECOMMENDATIONS
WHERE TASK_I D = : I D

SELECT OWNER, TASK_I D, TASK_NAME,
FI NDI NG_I D, TYPE, PARENT,
OBJ ECT_I D, I MPACT_TYPE, I MPACT, MESSAGE, MORE_I NFO
FROM DBA_ADVISOR_FINDINGS
WHERE TASK_I D = : I D
Page 126 Oracle DBA Code Examples


- - suggest ed act i ons t o per f or m
SELECT OWNER, TASK_I D, TASK_NAME,
REC_I D, ACTI ON_I D, OBJ ECT_I D,
COMMAND, COMMAND_I D, FLAGS,
ATTR1, ATTR2, ATTR3,
ATTR4, ATTR5, ATTR6,
NUM_ATTR1, NUM_ATTR2, NUM_ATTR3,
NUM_ATTR4, NUM_ATTR5, MESSAGE
FROM DBA_ADVISOR_ACTIONS
WHERE TASK_I D = : I D

- - anal yzed obj ect s
SELECT OWNER, OBJ ECT_I D, TYPE, TYPE_I D,
TASK_I D, TASK_NAME, ATTR1, ATTR2,
ATTR3, ATTR4, ATTR5, OTHER
FROM DBA_ADVISOR_OBJECTS
WHERE TASK_I D = : I D

/ * i nf or mat i on about t he Advi sor Runs */
SELECT AUTO_TASKI D, SNAPI D, SEGMENTS_SELECTED, SEGMENTS_PROCESSED,
TABLESPACE_SELECTED, TABLESPACE_PROCESSED, RECOMMENDATI ONS_COUNT,
START_TI ME, END_TI ME
FROM DBA_AUTO_SEGADV_SUMMARY;

/ * cont r ol i nf or mat i on t hat show whi ch obj ect anal yzed by t he Advi sor */
SELECT *
FROM DBA_AUTO_SEGADV_CTL
Shrinking Database Segments Online
- - r equi r ed
ALTER TABLE names ENABLE ROWMOVEMENT - - i t acqui r es t abl e l ock

- - shr i nk t abl e ( def r age and t hen move t he HWM)
ALTER TABLE names SHRI NK SPACE; - - i t acqui r es t abl e l ock

- - def r age and don' t move HWM ( l at er you can SHRI NK SPACE)
ALTER TABLE names SHRI NK SPACE COMPACT; - - no t abl e l ock

- - LOBs and t he I ndexes ar e al os shr i nked
ALTER TABLE names SHRI NK SPACE CASCADE;

- - shr i nk LOB onl y
ALTER TABLE names MODI FY LOB ( per f _r evi ew) ( SHRI NK SPACE) ;

- - shr i nk par t i t i on
ALTER TABLE names MODI FY PARTI TI ON cust _P1 SHRI NK SPACE;

- - I OT
ALTER TABLE names SHRI NK SPACE CASCADE;

- - I OT Over f l ow Segment
ALTER TABLE names OVERFLOWSHRI NK SPACE;
Deallocating Unused Space
deallocates unused space at the end of the segment; no data is moved
Page 127 Oracle DBA Code Examples

ALTER TABLE myt abl e DEALLOCATE UNUSED KEEP i nt eger ;
ALTER I NDEX myi ndex DEALLOCATE UNUSED KEEP i nt eger ;
ALTER CLUSTER cl ust er DEALLOCATE UNUSED KEEP i nt eger ;
Capacity Planning for Database Objects
Estimating the Space Use of a Table
DBMS_SPACE.CREATE_TABLE_COST can be used on dictionary-managed or locally
managed tablespaces.
- - based on aver age r ow si ze
SET SERVEROUTPUT ON
decl ar e
v_t abl e_name var char 2( 30) : =' NAMES' ;
v_owner var char 2( 30) : =' HR' ;
v_t abl espace_name var char 2( 100) : = ' USERS' ;
v_avg_r ow_si ze number ; - - ant i ci pat ed aver age r ow si ze
v_r ow_count number : = 1000000;
v_pct _f r ee number : = 10;
v_used_byt es number ; - - User dat a space i ncl udi ng PCTFREE
v_al l oc_byt es number ; - - The ant i ci pat ed si ze of t he t abl e t aki ng i nt o
account t he t abl espace ext ent char act er i st i cs
x char ( 1) ;
begi n

- - check t he t abl espace exi st s
begi n
SELECT ' x' i nt o x f r omdba_t abl espaces wher e
t abl espace_name=v_t abl espace_name ;
except i on
when no_dat a_f ound t hen
r ai se_appl i cat i on_er r or ( - 20001, ' Tabl espace: ' | | v_t abl espace_name | | '
does not exi st ' ) ;
end;

- - r et r ei ve aver age r ow si ze
begi n
SELECT AVG_ROW_LEN i nt o V_avg_r ow_si ze FROM DBA_TABLES wher e
t abl e_name=v_t abl e_name and owner =v_owner ;
except i on
when no_dat a_f ound t hen
r ai se_appl i cat i on_er r or ( - 20002, ' Tabl e : ' | | V_OWNER | | ' . ' | | v_t abl e_name | |
' does not exi st ' ) ;
end;

DBMS_SPACE. CREATE_TABLE_COST (
t abl espace_name => v_t abl espace_name,
avg_r ow_si ze => v_avg_r ow_si ze,
r ow_count => v_r ow_count ,
pct _f r ee => v_pct _f r ee,
used_byt es => v_used_byt es,
al l oc_byt es => v_al l oc_byt es) ;

dbms_out put . put _l i ne( ' User Dat a Space ( MB) : ' | |
TO_CHAR( v_used_byt es/ 1024/ 1024 , ' 999, 999, 999, 999, 999. 99' ) ) ;
dbms_out put . put _l i ne( ' Dat a Space i n t he Tabl espace ( MB) : ' | |
Page 128 Oracle DBA Code Examples

TO_CHAR( v_al l oc_byt es/ 1024/ 1024, ' 999, 999, 999, 999, 999. 99' ) ) ;
end;
/

- - based on col umn i nf o
decl ar e
ub NUMBER;
ab NUMBER;
cl sys. cr eat e_t abl e_cost _col umns;
begi n
cl : = sys. cr eat e_t abl e_cost _col umns(
sys. cr eat e_t abl e_cost _col i nf o( ' NUMBER' , 10) ,
sys. cr eat e_t abl e_cost _col i nf o( ' VARCHAR2' , 30) ,
sys. cr eat e_t abl e_cost _col i nf o( ' VARCHAR2' , 30) ,
sys. cr eat e_t abl e_cost _col i nf o( ' DATE' , NULL) ) ;
DBMS_SPACE. CREATE_TABLE_COST( ' SYSTEM' , cl , 100000, 0, ub, ab) ;
DBMS_OUTPUT. PUT_LI NE( ' Used Byt es: ' | | TO_CHAR( ub) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Al l oc Byt es: ' | | TO_CHAR( ab) ) ;
end;
/
Obtaining Object Growth Trends
User DBMS_SPACE.OBJECT_GROWTH_TREND
o start_time Statistics generated after this time will be used in generating the growth
trend
o end_time Statistics generated until this time will be used in generating the growth
trend
o interval The interval at which to sample
o skip_interpolated Whether interpolation of missing values should be skipped
o single_data_point_flag Whether in the absence of statistics the segment should be
sampled
Returned columns:
o timepoint The time at which the statistic was recorded
o space_usage The space used by data
o space_alloc The size of the segment including overhead and unused space
o quality The quality of result: "GOOD", "INTERPOLATED", "PROJECTION"
GOOD: accurate figure
PROJECTED: figures projected from the data collected by the AWR
INTERPOLATED: no data was available for calculations
COL TI MEPOI NT FORMAT A30

SELECT *
FROM
t abl e(
DBMS_SPACE. OBJ ECT_GROWTH_TREND (
obj ect _owner =>' HR' ,
obj ect _name =>' NAMES' ,
obj ect _t ype =>' TABLE' ,
par t i t i on_name =>NULL,
st ar t _t i me =>NULL,
end_t i me =>NULL,
i nt er val =>t o_dsi nt er val ( ' 0 00: 10: 00' ) , - - Day t o Second i nt er val
ski p_i nt er pol at ed => ' FALSE' ,
Page 129 Oracle DBA Code Examples

t i meout _seconds =>NULL,
si ngl e_dat apoi nt _f l ag =>' TRUE' )
)
Using the SQL Access Advisor
Estimating the Space Use of a Table
The SQL Access Advisor sources:
o A hypothetical database workload
o An actual workload you provide
o SQL cache
- - Met hod 1: t o i nvoke SQL Access Advi sor t ask l i nked t o a wor kl oad
decl ar e
l _t askname VARCHAR2( 30) : = ' sql _access_t est _t ask' ;
l _t ask_desc VARCHAR2( 128) : = ' Test SQL Access' ;
l _wkl d_name VARCHAR2( 30) : = ' t est _wor k_l oad' ;
l _saved_r ows NUMBER : = 0;
l _f ai l ed_r ows NUMBER : = 0;
l _num_f ound NUMBER;
BEGI N
- - cr eat e an SQL Access Advi sor t ask.
sel ect COUNT( *)
i nt o l _num_f ound
f r omDBA_ADVI SOR_TASKS
wher e TASK_NAME = l _t askname ;
I F l _num_f ound = 0 THEN
DBMS_ADVI SOR. CREATE_TASK (
ADVI SOR_NAME => DBMS_ADVI SOR. SQLACCESS_ADVI SOR,
TASK_NAME => l _t askname,
TASK_DESC => l _t ask_desc) ;
END I F;

- - r eset t he t ask ( r emove al l r ecommendat i ons, and i nt er medi at e dat a f r om
t he t ask)
DBMS_ADVI SOR. RESET_TASK( TASK_NAME => l _t askname) ;

- - cr eat e a wor kl oad.
SELECT COUNT( *)
I NTO l _num_f ound
FROM USER_ADVI SOR_SQLW_SUM
WHERE WORKLOAD_NAME = l _wkl d_name;

I F l _num_f ound = 0 THEN
DBMS_ADVI SOR. CREATE_SQLWKLD( WORKLOAD_NAME => l _wkl d_name) ;
END I F;

- - l i nk t he wor kl oad t o t he t ask
SELECT count ( *)
I NTO l _num_f ound
FROM USER_ADVI SOR_SQLA_WK_MAP
WHERE TASK_NAME = l _t askname
AND WORKLOAD_NAME = l _wkl d_name;

I F l _num_f ound = 0 THEN
Page 130 Oracle DBA Code Examples

DBMS_ADVI SOR. ADD_SQLWKLD_REF(
TASK_NAME => l _t askname,
WORKLOAD_NAME => l _wkl d_name) ;
END I F;

- - Set wor kl oad par amet er s.
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' ACTI ON_LI ST' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' MODULE_LI ST' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' SQL_LI MI T' ,
DBMS_ADVI SOR. ADVI SOR_UNLI MI TED) ;
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' ORDER_LI ST' ,
' PRI ORI TY, OPTI MI ZER_COST' ) ;
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' USERNAME_LI ST' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_SQLWKLD_PARAMETER( l _wkl d_name, ' VALI D_TABLE_LI ST' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;

- - unmar k t he r equi r ed opt i on
/ *
- - i mpor t t he cur r ent cont ent s of t he ser ver ' s SQL cache
DBMS_ADVI SOR. I MPORT_SQLWKLD_SQLCACHE( l _wkl d_name, ' REPLACE' , 2,
l _saved_r ows, l _f ai l ed_r ows) ;
- - l oad a SQL wor kl oad f r oman exi st i ng SQL Tuni ng Set
DBMS_ADVI SOR. I MPORT_SQLWKLD_STS ( l _wkl d_name, ' SOURCE_STS_Name' ,
' REPLACE' , 2, l _saved_r ows, l _f ai l ed_r ows) ;
*/
- - Set t ask par amet er s.
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' _MARK_I MPLEMENTATI ON' ,
' FALSE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' EXECUTI ON_TYPE' ,
' I NDEX_ONLY' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' MODE' , ' COMPREHENSI VE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' STORAGE_CHANGE' ,
DBMS_ADVI SOR. ADVI SOR_UNLI MI TED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DML_VOLATI LI TY' , ' TRUE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' ORDER_LI ST' ,
' PRI ORI TY, OPTI MI ZER_COST' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' WORKLOAD_SCOPE' , ' PARTI AL' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_I NDEX_TABLESPACE' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_I NDEX_OWNER' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_MVI EW_TABLESPACE' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_MVI EW_OWNER' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;

- - Execut e t he t ask: cont r ol wi l l not r et ur n t i l l t he execut i on f i ni shes
DBMS_ADVI SOR. execut e_t ask( t ask_name => l _t askname) ;
END;
/


- - Met hod 2: t o i nvoke SQL Access Advi sor l i nked t o a speci f i c STS
decl ar e
l _t askname VARCHAR2( 30) : = ' sql _access_t est _t ask2' ;
l _t ask_desc VARCHAR2( 128) : = ' Test SQL Access f or a STS' ;
Page 131 Oracle DBA Code Examples

l _wkl d_name VARCHAR2( 30) : = ' t est _wor k_l oad' ;
l _st s_name VARCHAR2( 30) : = ' t est _st s' ;
l _saved_r ows NUMBER : = 0;
l _f ai l ed_r ows NUMBER : = 0;
l _num_f ound NUMBER;
BEGI N
- - cr eat e an SQL Access Advi sor t ask, i f i t doesn t exi st
sel ect COUNT( *)
i nt o l _num_f ound
f r omDBA_ADVI SOR_TASKS
wher e TASK_NAME = l _t askname ;
I F l _num_f ound = 0 THEN
DBMS_ADVI SOR. CREATE_TASK (
ADVI SOR_NAME => DBMS_ADVI SOR. SQLACCESS_ADVI SOR,
TASK_NAME => l _t askname,
TASK_DESC => l _t ask_desc) ;
END I F;

- - r eset t he t ask ( r emove al l r ecommendat i ons, and i nt er medi at e dat a f r om
t he t ask)
DBMS_ADVI SOR. RESET_TASK( TASK_NAME => l _t askname) ;

- - check i f STS al r eady exi st s
sel ect count ( *)
i nt o l _num_f ound
f r om DBA_SQLSET wher e upper ( NAME) = upper ( l _st s_name) ;

I F l _num_f ound <> 0 THEN
DBMS_SQLTUNE. DROP_SQLSET ( sql set _name => l _st s_name) ;
END I F;

- - cr eat e STS
DBMS_SQLTUNE. CREATE_SQLSET( SQLSET_NAME => l _st s_name, DESCRI PTI ON =>' To
t est Access Advi sor ' ) ;

/ * unmar k t he r equi r ed opt i on
- - ( Opt i on 1) Load l _st s_name f r oman AWR basel i ne.
- - The dat a has been f i l t er ed t o sel ect onl y t he t op 30 SQL st at ement s
or der ed by el apsed t i me.
decl ar e
basel i ne_cur DBMS_SQLTUNE. SQLSET_CURSOR;
begi n
- - a r ef cur sor i s opened t o sel ect f r omt he speci f i ed basel i ne
OPEN basel i ne_cur FOR
SELECT VALUE( p)
FROM TABLE ( DBMS_SQLTUNE. SELECT_WORKLOAD_REPOSI TORY(
' peak basel i ne' , NULL, NULL, ' el apsed_t i me' , NULL, NULL, NULL, 30 ) ) p;

- - Next t he st at ement s and t hei r st at i st i cs ar e l oaded i nt o t he STS
DBMS_SQLTUNE. LOAD_SQLSET( SQLSET_NAME=>l _st s_name,
POPULATE_CURSOR=>basel i ne_cur ) ;
end;

- - ( Opt i on 2) Load l _st s_name wi t h SQL st at ement s t hat ar e not owned by SYS
and
- - t hei r el apsed t i me i s gr eat er t han 20, 000 seconds.
decl ar e
sql _cur DBMS_SQLTUNE. SQLSET_CURSOR;
Page 132 Oracle DBA Code Examples

begi n
- - a r ef cur sor i s opened t o sel ect t he r equi r ed SQL st at ment s
OPEN sql _cur FOR
SELECT VALUE( p)
FROM TABLE ( DBMS_SQLTUNE. SELECT_CURSOR_CACHE( ' par si ng_schema_name <>
' ' SYS' ' and el apsed_t i me > 2000000' , NULL, NULL, NULL, NULL, 1, NULL, ' ALL' ) )
p;
- - t he st at ement s ar e l oaded i nt o t he STS
DBMS_SQLTUNE. LOAD_SQLSET( SQLSET_NAME=>l _st s_name,
POPULATE_CURSOR=>sql _cur ) ;
end;

- - ( Opt i on 3) Copy t he cont ent s of a SQL wor kl oad obj ect t o a SQL Tuni ng Set
- - check t he exampl e above f or cr eat i ng a wor kl oad
DBMS_ADVI SOR. COPY_SQLWKLD_TO_STS ( ' My_Wor kLoad' , l _st s_name, ' REPLACE' ) ;
*/

- - l i nk t he STS t o t he t ask
DBMS_ADVI SOR. ADD_STS_REF ( l _t askname, nul l , l _st s_name) ;

- - Set t ask par amet er s.
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' _MARK_I MPLEMENTATI ON' ,
' FALSE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' EXECUTI ON_TYPE' ,
' I NDEX_ONLY' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' MODE' , ' COMPREHENSI VE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' STORAGE_CHANGE' ,
DBMS_ADVI SOR. ADVI SOR_UNLI MI TED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DML_VOLATI LI TY' , ' TRUE' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' ORDER_LI ST' ,
' PRI ORI TY, OPTI MI ZER_COST' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' WORKLOAD_SCOPE' , ' PARTI AL' ) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_I NDEX_TABLESPACE' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_I NDEX_OWNER' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_MVI EW_TABLESPACE' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;
DBMS_ADVI SOR. SET_TASK_PARAMETER( l _t askname, ' DEF_MVI EW_OWNER' ,
DBMS_ADVI SOR. ADVI SOR_UNUSED) ;

- - Execut e t he t ask: cont r ol wi l l not r et ur n t i l l t he execut i on f i ni shes
DBMS_ADVI SOR. EXECUTE_TASK( t ask_name => l _t askname) ;
END;
/


- - Met hod 3: Qui ck Tune f or a si ngl e gi ven st at ement
begi n
- - a t ask and a wor kl oad wi l l be cr eat ed t hen t he t ask wi l l be execut ed
DBMS_ADVI SOR. QUI CK_TUNE(
ADVI SOR_NAME => DBMS_ADVI SOR. SQLACCESS_ADVI SOR,
TASK_NAME => ' names_qui ck_t une' ,
ATTR1 => ' SELECT i d FROM hr . names n WHERE i d = 100' ) ;
end;
/
Following are examples of how to manage the task and obtain information about the advisors
output repot:
Page 133 Oracle DBA Code Examples

- - whi l e t he t ask i s bei ng execut ed, you can moni t or i t usi ng t he f ol l owi ng
quer y:
sel ect TASK_NAME, STATUS, PCT_COMPLETI ON_TI ME, ERROR_MESSAGE
f r om DBA_ADVI SOR_LOG
wher e TASK_NAME =' sql _access_t est _t ask' ;

- - i f you need t o t er mi nat e t he execut i ng t ask ( may be t i me consumi ng)
exec DBMS_ADVI SOR. CANCEL_TASK( TASK_NAME =>' sql _access_t est _t ask' ) ;

- - Di spl ay t he r esul t i ng scr i pt ( met hod 1)
SET LONG 100000
SET PAGESI ZE 50000
SELECT DBMS_ADVI SOR. GET_TASK_SCRI PT( ' sql _access_t est _t ask' ) AS scr i pt FROM
dual ;
SET PAGESI ZE 24

- - Di spl ay t he r esul t i ng scr i pt ( met hod 2)
CREATE DI RECTORY ADVI SOR_RESULTS AS ' C: \ TEMP\ ' ;
exec
DBMS_ADVI SOR. CREATE_FI LE( DBMS_ADVI SOR. GET_TASK_SCRI PT( ' sql _access_t est _t ask' ) ,
' ADVI SOR_RESULTS' , ' advscr i pt . sql ' ) ;

- - al t er nat i vel y, use t he f ol l owi ng quer i es
- - benef i t i s t he t ot al i mpr ovement i n execut i on cost of al l t he quer i es
sel ect REC_I D, RANK, BENEFI T, TYPE " Recommendat i on Type"
f r om DBA_ADVI SOR_RECOMMENDATI ONS
wher e TASK_NAME = ' sql _access_t est _t ask'
or der by RANK;

- - di spl ay pr ocessed st at ement s i n t he wor kl oad
sel ect SQL_I D, REC_I D, PRECOST, POSTCOST,
( PRECOST- POSTCOST) *100/ PRECOST AS PERCENT_BENEFI T
f r om USER_ADVI SOR_SQLA_WK_STMTS
wher e TASK_NAME = ' sql _access_t est _t ask' AND wor kl oad_name =
' t est _wor k_l oad' ;

- - see t he act i ons f or each r ecommendat i ons
sel ect REC_I D, ACTI ON_I D, SUBSTR( COMMAND, 1, 30) AS COMMAND
f r om USER_ADVI SOR_ACTI ONS wher e TASK_NAME = ' sql _access_t est _t ask'
ORDER BY r ec_i d, act i on_i d;

- - t o del et e a gi ven t ask
exec DBMS_ADVI SOR. DELETE_TASK( ' sql _access_t est _t ask' ) ;
Page 134 Oracle DBA Code Examples

Managing Tables
Obtaining Information about Tables
- - 11g
SELECT OWNER, TABLE_NAME, TABLESPACE_NAME, CLUSTER_NAME, I OT_NAME, STATUS, PCT_FREE,
PCT_USED, I NI _TRANS, MAX_TRANS, I NI TI AL_EXTENT,
NEXT_EXTENT, MI N_EXTENTS, MAX_EXTENTS, PCT_I NCREASE, FREELI STS, FREELI ST_GROUPS, LOGGI NG,
BACKED_UP, NUM_ROWS, BLOCKS, EMPTY_BLOCKS, AVG_SPACE, CHAI N_CNT,
AVG_ROW_LEN, AVG_SPACE_FREELI ST_BLOCKS, NUM_FREELI ST_BLOCKS, DEGREE,
I NSTANCES, CACHE, TABLE_LOCK, SAMPLE_SI ZE, LAST_ANALYZED, PARTI TI ONED, I OT_TYPE,
TEMPORARY, SECONDARY, NESTED, BUFFER_POOL, ROW_MOVEMENT, GLOBAL_STATS, USER_STATS,
DURATI ON, SKI P_CORRUPT, MONI TORI NG, CLUSTER_OWNER, DEPENDENCI ES, COMPRESSI ON,
COMPRESS_FOR, DROPPED, READ_ONLY
FROM DBA_TABLES
WHERE TABLE_NAME=' EMP' AND OWNER=' HR' ;

- - col umns
SELECT
OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_TYPE_MOD, DATA_TYPE_OWNER, DATA_LENGTH, DATA_P
RECI SI ON, DATA_SCALE, NULLABLE, COLUMN_I D, DEFAULT_LENGTH, DATA_DEFAULT, NUM_DI STI NCT, LOW_VAL
UE, HI GH_VALUE, DENSI TY, NUM_NULLS, NUM_BUCKETS, LAST_ANALYZED, SAMPLE_SI ZE, CHARACTER_SET_NAM
E, CHAR_COL_DECL_LENGTH, GLOBAL_STATS, USER_STATS, AVG_COL_LEN, CHAR_LENGTH, CHAR_USED, V80_FM
T_I MAGE, DATA_UPGRADED, HI STOGRAM
FROM DBA_TAB_COLUMNS
WHERE TABLE_NAME=' EMP' AND OWNER=' HR' ;

- - t abl e gat her ed st at i st i cs
SELECT
OWNER, TABLE_NAME, PARTI TI ON_NAME, PARTI TI ON_POSI TI ON, SUBPARTI TI ON_NAME, SUBPARTI TI ON_POSI T
I ON, OBJ ECT_TYPE, NUM_ROWS, BLOCKS, EMPTY_BLOCKS, AVG_SPACE, CHAI N_CNT, AVG_ROW_LEN, AVG_SPACE_
FREELI ST_BLOCKS, NUM_FREELI ST_BLOCKS, AVG_CACHED_BLOCKS, AVG_CACHE_HI T_RATI O, SAMPLE_SI ZE, L
AST_ANALYZED, GLOBAL_STATS, USER_STATS, STATTYPE_LOCKED, STALE_STATS
FROM DBA_TAB_STATI STI CS
WHERE TABLE_NAME=' EMP' AND OWNER=' HR' ;

- - comment s
sel ect * f r omDBA_TAB_COMMENTS;
sel ect * f r omDBA_COL_COMMENTS;

- - obj ect and r el at i onal t abl es
SELECT
OWNER, TABLE_NAME, TABLESPACE_NAME, CLUSTER_NAME, I OT_NAME, STATUS, PCT_FREE, PCT_USED, I NI _TRA
NS, MAX_TRANS, I NI TI AL_EXTENT, NEXT_EXTENT, MI N_EXTENTS, MAX_EXTENTS, PCT_I NCREASE, FREELI STS,
FREELI ST_GROUPS, LOGGI NG, BACKED_UP, NUM_ROWS, BLOCKS, EMPTY_BLOCKS, AVG_SPACE, CHAI N_CNT, AVG_
ROW_LEN, AVG_SPACE_FREELI ST_BLOCKS, NUM_FREELI ST_BLOCKS, DEGREE, I NSTANCES, CACHE, TABLE_LOCK
, SAMPLE_SI ZE, LAST_ANALYZED, PARTI TI ONED, I OT_TYPE, OBJ ECT_I D_TYPE, TABLE_TYPE_OWNER, TABLE_T
YPE, TEMPORARY, SECONDARY, NESTED, BUFFER_POOL, ROW_MOVEMENT, GLOBAL_STATS, USER_STATS, DURATI O
N, SKI P_CORRUPT, MONI TORI NG, CLUSTER_OWNER, DEPENDENCI ES, COMPRESSI ON, COMPRESS_FOR, DROPPED
FROM DBA_ALL_TABLES
WHERE TABLE_NAME=' EMP' AND OWNER=' HR' ;
Creating Tables with some Options
- - speci f i c t abl space
cr eat e t abl e myt ab . . . t abl space myt bs
- - Par al l el i zi ng Tabl e Cr eat i on
CREATE TABLE myt b PARALLEL AS SELECT . .
ALTER SESSI ON FORCE PARALLEL DDL; - - cr eat ed t abl es wi l l be par al l el i zed

- - nol oggi ng
Page 135 Oracle DBA Code Examples

CREATE TABLE myt b NOLOGGI NG AS SELECT . .

-- compression
CREATE TABLE myt b ( . . . ) COMPRESS FOR ALL OPERATI ONS; - - OK i n OLTP
CREATE TABLE sal es_hi st or y ( . . . ) COMPRESS FOR DI RECT_LOAD OPERATI ONS; - - OK i n OLAP
CREATE TABLE sal es_hi st or y ( . . . ) COMPRESS; - - same as above
CREATE TABLE sal es
( sal eskey number , quar t er . . r egi on var char 2( 10) ) COMPRESS
PARTI TI ON BY LI ST ( r egi on)
( PARTI TI ON nor t hwest VALUES ( ' NORTHWEST' ) ,
PARTI TI ON sout hwest VALUES ( ' SOUTHWEST' ) ,
PARTI TI ON nor t heast VALUES ( ' NORTHEAST' ) NOCOMPRESS,
PARTI TI ON sout heast VALUES ( ' SOUTHEAST' ) ,
PARTI TI ON west er n VALUES ( ' WESTERN' ) )

-- encrypting columns (REQUIRES OEPENED WALLET)
CREATE TABLE myt b ( . . ssn NUMBER( 9) ENCRYPT, . . )

-- temporary table
- - t r ansact i on l evel
CREATE GLOBAL TEMPORARY TABLE myt b ( . . ) ON COMMI T DELETE ROWS;
- - sessi on l evel
CREATE GLOBAL TEMPORARY TABLE myt b ( . . ) ON COMMI T PRESERVE ROWS;
DML Error Logging
DML error logging works with INSERT, UPDATE, MERGE, and DELETE statements.
The following conditions cause the statement to fail and roll back without invoking the
error logging capability:
o Violated deferred constraints
o Out-of-space errors
o Any direct-path INSERT operation (INSERT or MERGE) that raises a unique constraint
or index violation
o Any UPDATE or MERGE that raises a unique constraint or index violation
- - 1. Cr eat e an er r or l oggi ng t abl e.
- - LONG, CLOB, BLOB, BFI LE, and ADT dat at ypes ar e not suppor t ed i n t he
col umns
EXECUTE DBMS_ERRLOG. CREATE_ERROR_LOG( dml _t abl e_name=>' EMP' ,
er r _l og_t abl e_name=>' ERR_EMP' ) ;
EXECUTE DBMS_ERRLOG. CREATE_ERROR_LOG( dml _t abl e_name=>' EMP' ,
er r _l og_t abl e_name=>' ERR_EMP' , er r _l og_t abl e_owner =>' HR' ,
er r _l og_t abl e_space=>' USERS' ) ;
- - 2 i ncl ude an er r or l oggi ng cl ause
I NSERT I NTO emp VALUES( 1001, ' abcd' , 75, NULL)
LOG ERRORS I NTO ERR_EMP REJ ECT LI MI T UNLI MI TED;
I NSERT I NTO hr . emp
SELECT . . FROM . .
LOG ERRORS I NTO er r _emp ( ' dai l y_l oad' ) REJ ECT LI MI T 25
- - 3 Quer y t he er r or l oggi ng t abl e and t ake cor r ect i ve act i on
Enabling Direct-Path INSERT
To activate direct-path INSERT in serial mode, you must specify the APPEND hint in each
INSERT statement, either immediately after the INSERT keyword, or immediately after the
SELECT keyword in the subquery of the INSERT statement.
Page 136 Oracle DBA Code Examples

i nser t / *+ append */ i nt o cust omer ( sel ect xxx) ;
When you are inserting in parallel DML mode, direct-path INSERT is the default. In order
to run in parallel DML mode, the following requirements must be met:
o You must have Oracle Enterprise Edition installed.
o You must enable parallel DML in your session. To do this, run the following statement:
ALTER SESSI ON { ENABLE | FORCE } PARALLEL DML;
o You must specify the parallel attribute for the target table, either at create time or
subsequently, or you must specify the PARALLEL hint for each insert operation.
i nser t / *+ par al l el */ i nt o names3 ( sel ect * f r omnames)
If nologging is specified, the insert will finish faster.
sel ect l oggi ng f r omdba_t abl es wher e owner =' HR' and t abl e_name=' EMPLOYEES' ;
sel ect l oggi ng f r omdba_t abl espaces wher e t abl espace_name = ' USERS' ;
Index maintenance is done by end of command. Consider drop and then re-creating the
indexes after the statement.
Exclusive table lock is acquired.
Automatically Collecting Statistics on Tables
In Oracle Database 11g, statistics are collected automatically for tables regardless of the
the MONITORING and NOMONITORING keywords
when creating them.
Altering Tables
If you enable compression for all operations on a table, you can drop table columns. If you
enable compression for direct-path inserts only, you cannot drop columns.
- - move t he t abl e t o a new segment
- - i ndexes wi l l be UNUSABLE and must be r ebui l t
- - st at i st i cs must be r egat her ed
ALTER TABLE hr . emp MOVE
STORAGE ( I NI TI AL 20K
NEXT 40K
MI NEXTENTS 2
MAXEXTENTS 20
PCTI NCREASE 0 ) ;
al t er t abl e emp MOVE TABLESPACE exampl e ;
al t er t abl e emp move st or age (
NEXT 1024K
PCTI NCREASE 0 )
COMPRESS;

- - al l ocat i ng and deal l ocat i ng ext ent s
al t er t abl e hr . emp al l ocat e ext ent ;
al t er t abl e hr . emp deal l ocat e ext ent ;

- - al l ocat i ng and deal l ocat i ng ext ent s
al t er t abl e hr . emp al l ocat e ext ent ;
al t er t abl e hr . emp deal l ocat e unused;

Page 137 Oracle DBA Code Examples

- - Mar ki ng Col umns Unused
ALTER TABLE hr . emp SET UNUSED ( hi r edat e, mgr ) ;
SELECT * FROM DBA_UNUSED_COL_TABS;
ALTER TABLE hr . emp DROP UNUSED COLUMNS st at ement ;
- - l ess undo space i s consumed when checkpoi nt i s done per i odi cal l y
ALTER TABLE hr . admi n_emp DROP UNUSED COLUMNS CHECKPOI NT 250;

- - r ead onl y and r ead wr i t e
ALTER TABLE empl oyees READ ONLY;
ALTER TABLE empl oyees READ WRI TE;
sel ect TABLE_NAME, READ_ONLY f r omuser _t abl es wher e t abl e_name=' EMPLOYEES' ;
Performing Online Redefinition with DBMS_REDEFINITION
Redefining a Table
/ *
Thi s exampl e i l l ust r at es onl i ne r edef i ni t i on of t he pr evi ousl y cr eat ed t abl e
hr . admi n_emp, whi ch at t hi s poi nt onl y cont ai ns col umns: empno, ename,
j ob, dept no.
The t abl e i s r edef i ned as f ol l ows:
- New col umns mgr , hi r edat e, sal , and bonus ar e added.
- The new col umn bonus i s i ni t i al i zed t o 0
- The col umn dept no has i t s val ue i ncr eased by 10.
- The r edef i ned t abl e i s par t i t i oned by r ange on empno.
*/
- - 1 Ver i f y t hat t he t abl e i s a candi dat e f or onl i ne r edef i ni t i on.
BEGI N
DBMS_REDEFI NI TI ON. CAN_REDEF_TABLE(
UNAME => ' HR' ,
TNAME => ' ADMI N_EMP' ,
OPTI ONS_FLAG => dbms_r edef i ni t i on. cons_use_pk) ; - - OR
DBMS_REDEFI NI TI ON. CONS_USE_ROWI D
END;
/
- - 2. Cr eat e an i nt er i mt abl e hr . i nt _admi n_emp.
CREATE TABLE hr . i nt _admi n_emp
( empno NUMBER( 5) PRI MARY KEY,
ename VARCHAR2( 15) NOT NULL,
j ob VARCHAR2( 10) ,
mgr NUMBER( 5) ,
hi r edat e DATE DEFAULT ( sysdat e) ,
sal NUMBER( 7, 2) ,
dept no NUMBER( 3) NOT NULL,
bonus NUMBER ( 7, 2) DEFAULT( 1000) )
PARTI TI ON BY RANGE( empno)
( PARTI TI ON emp1000 VALUES LESS THAN ( 1000) TABLESPACE admi n_t bs,
PARTI TI ON emp2000 VALUES LESS THAN ( 2000) TABLESPACE admi n_t bs2) ;

- - ( Opt i onal ) I f you ar e r edef i ni ng a l ar ge t abl e
al t er sessi on f or ce par al l el dml par al l el 2;
al t er sessi on f or ce par al l el quer y par al l el 2;

- - 3. St ar t t he r edef i ni t i on pr ocess.
BEGI N
Page 138 Oracle DBA Code Examples

DBMS_REDEFI NI TI ON. START_REDEF_TABLE(
UNAME => ' HR' ,
ORI G_TABLE => ' ADMI N_EMP' ,
I NT_TABLE => ' i nt _admi n_emp' ,
col _mappi ng=>' empno empno, ename ename, j ob j ob, dept no+10 dept no, 0
bonus' , - - NULL i f same col umns i n bot h t abl es
opt i ons_f l ag => dbms_r edef i ni t i on. cons_use_pk) ;
END;
/

- - 4 Copy dependent obj ect s.
DECLARE
N NUMBER;
BEGI N
DBMS_REDEFI NI TI ON. COPY_TABLE_DEPENDENTS(
uname =>' HR' ,
or i g_t abl e =>' admi n_emp' ,
i nt _t abl e => ' i nt _admi n_emp' ,
copy_i ndexes =>dbms_r edef i ni t i on. cons_or i g_par ams, - - 0 don' t copy
copy_t r i gger s =>TRUE,
copy_const r ai nt s =>TRUE,
copy_pr i vi l eges =>TRUE,
i gnor e_er r or s => TRUE, - - def aul t FALSE
num_er r or s => n,
copy_st at i st i cs => FALSE, - - def aul t FALSE
copy_mvl og => FALSE) ; - - def aul t FALSE
- - bcuz i gnor e_er r or s=t r ue
i f n =0 t hen
dbms_out put . put _l i ne( ' Success. ' ) ;
el se
dbms_out put . put _l i ne( ' Number of Er r or s: ' | | n) ;
end i f ;
END;
/

/ * Not e t hat t he i gnor e_er r or s ar gument i s set t o TRUE f or t hi s cal l . The
r eason i s t hat t he i nt er i mt abl e was cr eat ed wi t h a pr i mar y key const r ai nt ,
and when COPY_TABLE_DEPENDENTS at t empt s t o copy t he pr i mar y key const r ai nt
and i ndex f r omt he or i gi nal t abl e, er r or s occur s. You can i gnor e t hese
er r or s, but you must r un t he quer y shown i n t he next st ep t o see i f t her e ar e
ot her er r or s. */

- - 5. Quer y t he DBA_REDEFI NI TI ON_ERRORS vi ew t o check f or er r or s.
sel ect obj ect _name, base_t abl e_name, ddl _t xt f r omDBA_REDEFI NI TI ON_ERRORS;

- - 6. Opt i onal l y, synchr oni ze t he i nt er i mt abl e hr . i nt _admi n_emp
BEGI N
DBMS_REDEFI NI TI ON. SYNC_I NTERI M_TABLE( ' hr ' , ' admi n_emp' , ' i nt _admi n_emp' ) ;
END;
/

- - 7. Compl et e t he r edef i ni t i on.
BEGI N
DBMS_REDEFI NI TI ON. FI NI SH_REDEF_TABLE( ' hr ' , ' admi n_emp' , ' i nt _admi n_emp' ) ;
END;
/

/ * The t abl e hr . admi n_emp i s l ocked i n t he excl usi ve mode onl y f or a smal l
Page 139 Oracle DBA Code Examples

wi ndow t owar d t he end of t hi s st ep. Af t er t hi s cal l t he t abl e hr . admi n_emp i s
r edef i ned such t hat i t has al l t he at t r i but es of t he hr . i nt _admi n_emp t abl e.
*/
- - 8 Wai t f or any l ong- r unni ng quer i es agai nst t he i nt er i mt abl e t o compl et e,
and t hen dr op t he i nt er i mt abl e.
Redefining a Single Partition
/ *
We want t o move t he ol dest par t i t i on of a r ange- par t i t i oned sal es t abl e t o a
t abl espace named TBS_LOW_FREQ.
The t abl e cont ai ni ng t he par t i t i on t o be r edef i ned i s def i ned as f ol l ows:
CREATE TABLE sal est abl e
( s_pr oduct i d NUMBER,
s_sal edat e DATE,
s_cust i d NUMBER,
s_t ot al pr i ce NUMBER)
TABLESPACE user s
PARTI TI ON BY RANGE( s_sal edat e)
( PARTI TI ON sal 03q1 VALUES LESS THAN ( TO_DATE( ' 01- APR- 2003' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON sal 03q2 VALUES LESS THAN ( TO_DATE( ' 01- J UL- 2003' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON sal 03q3 VALUES LESS THAN ( TO_DATE( ' 01- OCT- 2003' , ' DD- MON- YYYY' ) ) ,
PARTI TI ON sal 03q4 VALUES LESS THAN ( TO_DATE( ' 01- J AN- 2004' , ' DD- MON- YYYY' ) ) ) ;
The t abl e has a l ocal par t i t i oned i ndex t hat i s def i ned as f ol l ows:
CREATE I NDEX sal es_i ndex ON sal est abl e
( s_sal edat e, s_pr oduct i d, s_cust i d) LOCAL;
*/

- - 1. Ensur e t hat sal est abl e i s a candi dat e f or r edef i ni t i on.
BEGI N
DBMS_REDEFI NI TI ON. CAN_REDEF_TABLE(
uname => ' STEVE' ,
t name => ' SALESTABLE' ,
opt i ons_f l ag => DBMS_REDEFI NI TI ON. CONS_USE_ROWI D,
par t _name => ' sal 03q1' ) ;
END;
/

- - 2 Cr eat e t he i nt er i mt abl e i n t he TBS_LOW_FREQ t abl espace. Because t hi s i s
a r edef i ni t i on of a r ange par t i t i on, t he i nt er i mt abl e i s non- par t i t i oned.
CREATE TABLE i nt _sal est abl e
( s_pr oduct i d NUMBER,
s_sal edat e DATE,
s_cust i d NUMBER,
s_t ot al pr i ce NUMBER)
TABLESPACE t bs_l ow_f r eq;

- - 3. St ar t t he r edef i ni t i on pr ocess usi ng r owi d.
BEGI N
DBMS_REDEFI NI TI ON. START_REDEF_TABLE(
uname => ' STEVE' ,
or i g_t abl e => ' sal est abl e' ,
i nt _t abl e => ' i nt _sal est abl e' ,
col _mappi ng => NULL,
opt i ons_f l ag => DBMS_REDEFI NI TI ON. CONS_USE_ROWI D,
par t _name => ' sal 03q1' ) ;
END;
/
Page 140 Oracle DBA Code Examples

- - 4. Manual l y cr eat e any l ocal i ndexes on t he i nt er i mt abl e.
CREATE I NDEX i nt _sal es_i ndex ON i nt _sal est abl e
( s_sal edat e, s_pr oduct i d, s_cust i d)
TABLESPACE t bs_l ow_f r eq;
- - 5. Opt i onal l y synchr oni ze t he i nt er i mt abl e.
BEGI N
DBMS_REDEFI NI TI ON. SYNC_I NTERI M_TABLE(
uname => ' STEVE' ,
or i g_t abl e => ' sal est abl e' ,
i nt _t abl e => ' i nt _sal est abl e' ,
par t _name => ' sal 03q1' ) ;
END;
/
- - 6. Compl et e t he r edef i ni t i on.
BEGI N
DBMS_REDEFI NI TI ON. FI NI SH_REDEF_TABLE(
uname => ' STEVE' ,
or i g_t abl e => ' sal est abl e' ,
i nt _t abl e => ' i nt _sal est abl e' ,
par t _name => ' sal 03q1' ) ;
END;
/
- - 7. Wai t f or any l ong- r unni ng quer i es agai nst t he i nt er i mt abl e t o compl et e,
and t hen dr op t he i nt er i mt abl e.
- - The f ol l owi ng quer y shows t hat t he ol dest par t i t i on has been moved t o t he
new t abl espace:
sel ect par t i t i on_name, t abl espace_name f r omuser _t ab_par t i t i ons wher e
t abl e_name = ' SALESTABLE' ;
Migrating BasicFile LOBs to SecureFiles
- - Gr ant pr i vi l eges r equi r ed f or onl i ne r edef i ni t i on.
GRANT EXECUTE ON DBMS_REDEFI NI TI ON TO pm;
GRANT ALTER ANY TABLE TO pm;
GRANT DROP ANY TABLE TO pm;
GRANT LOCK ANY TABLE TO pm;
GRANT CREATE ANY TABLE TO pm;
GRANT SELECT ANY TABLE TO pm;

- - Pr i vi l eges r equi r ed t o per f or mcl oni ng of dependent obj ect s.
GRANT CREATE ANY TRI GGER TO pm;
GRANT CREATE ANY I NDEX TO pm;

CONNECT pm

CREATE TABLE cust ( c_i d NUMBER PRI MARY KEY,
c_zi p NUMBER,
c_name VARCHAR( 30) DEFAULT NULL,
c_l ob CLOB) ;
I NSERT I NTO cust VALUES( 1, 94065, ' hhh' , ' t t t ' ) ;

- - Cr eat i ng I nt er i mTabl e
- - no need t o speci f y const r ai nt s because t hey ar e copi ed over f r omt he
or i gi nal t abl e
CREATE TABLE cust _i nt ( c_i d NUMBER NOT NULL,
c_zi p NUMBER,
c_name VARCHAR( 30) DEFAULT NULL,
c_l ob CLOB)
Page 141 Oracle DBA Code Examples

LOB( c) STORE AS SECUREFI LE ( . . . ) ;

decl ar e
col _mappi ng VARCHAR2( 1000) ;
begi n
- - map al l t he col umns i n t he i nt er i mt abl e t o t he or i gi nal t abl e
col _mappi ng : =' c_i d c_i d , ' | | ' c_zi p c_zi p , ' | | ' c_name c_name, ' | | ' c_l ob
c_l ob' ;
DBMS_REDEFI NI TI ON. START_REDEF_TABLE( ' pm' , ' cust ' , ' cust _i nt ' , col _mappi ng) ;
end;

decl ar e
er r or _count pl s_i nt eger : = 0;
begi n
DBMS_REDEFI NI TI ON. COPY_TABLE_DEPENDENTS( ' pm' , ' cust ' , ' cust _i nt ' ,
1, TRUE, TRUE, TRUE, FALSE, er r or _count ) ;
DBMS_OUTPUT. PUT_LI NE( ' er r or s : = ' | | TO_CHAR( er r or _count ) ) ;
end;

exec DBMS_REDEFI NI TI ON. FI NI SH_REDEF_TABLE( ' pm' , ' cust ' , ' cust _i nt ' ) ;

- - Dr op t he i nt er i mt abl e
DROP TABLE cust _i nt ;
DESC cust ;

- - t o pr ove t hat t he pr i mar y key on t he c_i d col umn i s pr eser ved af t er
mi gr at i on.
I NSERT I NTO cust VALUES( 1, 94065, ' hhh' , ' t t t ' ) ;
SELECT * FROM cust ;
Using Flashback Drop and Managing the Recycle Bin
See Flashback Drop.
Managing Index-Organized Tables
- - Cr eat i ng an I ndex- Or gani zed Tabl e
- - i f t he l engt h of a r ow exceeds 20%of t he i ndex
- - bl ock si ze, t hen t he col umn t hat exceeded t hat t hr eshol d and
- - al l col umns af t er i t ar e moved t o t he over f l ow segment .
- - Speci f y MAPPI NG TABLE t o cr eat e a mappi ng t abl e; i t ' s needed t o cr eat e a
bi t map i ndex on t he I OT
CREATE TABLE admi n_doci ndex(
t oken char ( 20) ,
doc_i d NUMBER,
t oken_f r equency NUMBER,
t oken_of f set s VARCHAR2( 2000) ,
CONSTRAI NT pk_admi n_doci ndex PRI MARY KEY ( t oken, doc_i d) )
ORGANI ZATI ON I NDEX TABLESPACE admi n_t bs
PCTTHRESHOLD 20
OVERFLOWTABLESPACE admi n_t bs2;
- - Cr eat i ng I ndex- Or gani zed Tabl es t hat Cont ai n Obj ect Types
CREATE OR REPLACE TYPE admi n_t yp AS OBJ ECT ( col 1 NUMBER, col 2 VARCHAR2( 6) ) ;
CREATE TABLE admi n_i ot ( c1 NUMBER pr i mar y key, c2 admi n_t yp) ORGANI ZATI ON
I NDEX;
Page 142 Oracle DBA Code Examples

CREATE TABLE admi n_i ot 2 OF admi n_t yp ( col 1 PRI MARY KEY) ORGANI ZATI ON I NDEX;
- - oken_of f set s col umn val ue i s al ways st or ed i n t he over f l ow ar ea
TABLE admi n_doci ndex2(
t oken CHAR( 20) ,
doc_i d NUMBER,
t oken_f r equency NUMBER,
t oken_of f set s VARCHAR2( 2000) ,
CONSTRAI NT pk_admi n_doci ndex2 PRI MARY KEY ( t oken, doc_i d) )
ORGANI ZATI ON I NDEX
TABLESPACE admi n_t bs
PCTTHRESHOLD 20 - - def aul t 50
I NCLUDI NG t oken_f r equency
OVERFLOWTABLESPACE admi n_t bs2;

- - Par al l el i zi ng I ndex- Or gani zed Tabl e Cr eat i on
CREATE TABLE admi n_i ot 3( i PRI MARY KEY, j , k, l )
ORGANI ZATI ON I NDEX
PARALLEL AS SELECT * FROM hr . j obs;

- - Al t er i ng I ndex- Or gani zed Tabl es
ALTER TABLE admi n_doci ndex I NI TRANS 4 OVERFLOWI NI TRANS 6;
ALTER TABLE admi n_doci ndex PCTTHRESHOLD 15 I NCLUDI NG doc_i d;
- - i f t her e' s no exi st i ng over f l ow segment
ALTER TABLE admi n_i ot 3 ADD OVERFLOWTABLESPACE admi n_t bs2;

- - Movi ng ( Rebui l di ng) I ndex- Or gani zed Tabl es
ALTER TABLE admi n_doci ndex MOVE; - - j ust r ebui l d
ALTER TABLE admi n_doci ndex MOVE ONLI NE;
ALTER TABLE admi n_i ot _l ob MOVE LOB ( admi n_l ob) STORE AS ( TABLESPACE
admi n_t bs3) ;
- - I OT i s r ebui l t al ong wi t h i t s over f l ow segment
ALTER TABLE admi n_doci ndex MOVE TABLESPACE admi n_t bs2 OVERFLOWTABLESPACE
admi n_t bs3;

- - Cr eat i ng Secondar y I ndexes on I ndex- Or gani zed Tabl es
CREATE I NDEX Doc_i d_i ndex on Doci ndex( Doc_i d, Token) ;
Managing External Tables
/ * obt ai n i nf o about ext er nal t abl es */
sel ect OWNER, TABLE_NAME, TYPE_OWNER,
TYPE_NAME, DEFAULT_DI RECTORY_OWNER, DEFAULT_DI RECTORY_NAME,
REJ ECT_LI MI T, ACCESS_TYPE, ACCESS_PARAMETERS, PROPERTY
f r omDBA_EXTERNAL_TABLES;
sel ect OWNER, TABLE_NAME, LOCATI ON, DI RECTORY_OWNER, DI RECTORY_NAME
f r omDBA_EXTERNAL_LOCATI ONS;


/ * Cr eat i ng an Ext er nal Tabl e and Loadi ng Dat a */
CONNECT / AS SYSDBA;
- - Set up di r ect or i es and gr ant access t o hr
CREATE OR REPLACE DI RECTORY admi n_dat _di r AS ' c: \ t emp\ dat a' ;
CREATE OR REPLACE DI RECTORY admi n_l og_di r AS ' c: \ t emp\ l og' ;
CREATE OR REPLACE DI RECTORY admi n_bad_di r AS ' c: \ t emp\ bad' ;
GRANT READ ON DI RECTORY admi n_dat _di r TO hr ;
GRANT WRI TE ON DI RECTORY admi n_l og_di r TO hr ;
Page 143 Oracle DBA Code Examples

GRANT WRI TE ON DI RECTORY admi n_bad_di r TO hr ;
- - hr connect s. Pr ovi de t he user passwor d ( hr ) when pr ompt ed.
CONNECT hr
- - cr eat e t he ext er nal t abl e
CREATE TABLE admi n_ext _empl oyees
( empl oyee_i d NUMBER( 4) ,
f i r st _name VARCHAR2( 20) ,
l ast _name VARCHAR2( 25) ,
j ob_i d VARCHAR2( 10) ,
manager _i d NUMBER( 4) ,
hi r e_dat e DATE,
sal ar y NUMBER( 8, 2) ,
commi ssi on_pct NUMBER( 2, 2) ,
depar t ment _i d NUMBER( 4) ,
emai l VARCHAR2( 25) )
ORGANI ZATI ON EXTERNAL
(
TYPE ORACLE_LOADER - - or ORACLE_DATAPUMP ( f or unl oad)
DEFAULT DI RECTORY admi n_dat _di r
ACCESS PARAMETERS
(
r ecor ds del i mi t ed by newl i ne
badf i l e admi n_bad_di r : ' empxt %a_%p. bad'
l ogf i l e admi n_l og_di r : ' empxt %a_%p. l og'
f i el ds t er mi nat ed by ' , '
mi ssi ng f i el d val ues ar e nul l
( empl oyee_i d, f i r st _name, l ast _name, j ob_i d, manager _i d,
hi r e_dat e char dat e_f or mat dat e mask " dd- mon- yyyy" ,
sal ar y, commi ssi on_pct , depar t ment _i d, emai l )
)
LOCATI ON ( ' empxt 1. dat ' , ' empxt 2. dat ' )
)
PARALLEL - - usef ul t o huge dat a
REJ ECT LI MI T UNLI MI TED;

- - mor e opt i ons
- - i n ACCESS PARAMETERS you can add
LOAD WHEN ( j ob ! = MANAGER)

- - usi ng SQL*Loader t o gener at ed scr i pt f or cr eat i ng ext er nal t abl es
- - ( 1) pr epar e cont r ol f i l e such as:
LOAD DATA
I NFI LE *
I NTO TABLE t est _emp
FI ELDS TERMI NATED BY ' , ' OPTI ONALLY ENCLOSED BY ' " '
( empl oyee_i d, f i r st _name, l ast _name, hi r e_dat e, sal ar y, manager _i d)
BEGI NDATA
12345, " sam" , " al apat i " , sysdat e, 50000, 99999
23456, " mar k" , " pot t s" , sysdat e, 50000, 99999
- - ( 2) i ssue SQL*Loader usi ng EXTERNAL_TABLE =GENERATE_ONLY NOT_USED EXECUTE
sql l dr USERI D=syst em/ sammyy1 CONTROL=t est . ct l \
EXTERNAL_TABLE=GENERATE_ONLY
- - ( 3) check t he gener at ed l og f i l e


/ * Unl oadi ng i nt o Ext er nal Tabl es */
- - ( usi ng dat apump dr i ver s)
Page 144 Oracle DBA Code Examples

CREATE TABLE t est _xt
ORGANI ZATI ON EXTERNAL(
TYPE ORACLE_DATAPUMP
DEFAULT DI RECTORY ext _dat a_di r
ACCESS PARAMETERS ( COMPRESSI ON ENABLED)
LOCATI ON ( ' t est _xt . dmp' ) )
AS
SELECT * FROM scot t . dept ;

- - encr ypt i ng l oaded dat a
CREATE TABLE TEST
ORGANI ZATI ON EXTERNAL ( TYPE ORACLE_DATAPUMP DEFAULT DI RECTORY t est _di r 1
ACCESS PARAMETERS ( ENCRYPTI ON ENABLED) LOCATI ON ( ' t est . dmp' ) ) ;

- - unl oad i nt o mul t i pl e f i l es
CREATE TABLE cust omer s
ORGANI ZATI ON EXTERNAL
( TYPE ORACLE_DATAPUMP DEFAULT DI RECTORY ext _dat a_di r ACCESS PARAMETERS
( NOBADFI LE NOLOGFI LE)
LOCATI ON ( ' cust omer s1. exp' , ' cust omer s2. exp' , ' cust omer s3. exp' ,
' cust omer s4. exp' ) )
PARALLEL 4 REJ ECT LI MI T UNLI MI TED AS
SELECT c. *, co. count r y_name, co. count r y_subr egi on, co. count r y_r egi on
FROM cust omer s c, count r i es co wher e co. count r y_i d=c. count r y_i d;


- - enabl e par al l el f or l oadi ng ( good i f l ot s of dat a t o l oad)
ALTER SESSI ON ENABLE PARALLEL DML;

- - l oad t he dat a i n hr empl oyees t abl e
I NSERT I NTO emp ( empl oyee_i d, f i r st _name, l ast _name, j ob_i d, manager _i d,
hi r e_dat e, sal ar y, commi ssi on_pct , depar t ment _i d, emai l )
SELECT * FROM admi n_ext _empl oyees;


/ * Al t er i ng Ext er nal Tabl es */
ALTER TABLE admi n_ext _empl oyees REJ ECT LI MI T 100;

- - access dr i ver pr ocesses onl y t he col umns i n t he sel ect l i st ( def aul t )
ALTER TABLE admi n_ext _empl oyees PROJ ECT COLUMN REFERNCED;
- - t he access dr i ver pr ocesses al l of t he col umns
- - Thi s set t i ng al ways pr ovi des a consi st ent set of r et ur ned r ows
ALTER TABLE admi n_ext _empl oyees PROJ ECT COLUMN ALL;

- - def aul t di r ect or y
ALTER TABLE admi n_ext _empl oyees DEFAULT DI RECTORY admi n_dat 2_di r ;

- - access par amet er
ALTER TABLE admi n_ext _empl oyees ACCESS PARAMETERS ( FI ELDS TERMI NATED BY ' ; ' ) ;

- - l ocat i on
ALTER TABLE admi n_ext _empl oyees LOCATI ON ( ' empxt 3. t xt ' , ' empxt 4. t xt ' ) ;
Page 145 Oracle DBA Code Examples

Managing Indexes
Using Indexes
When creating an extremely large index, consider allocating a larger temporary tablespace
specially for the index creation.
If you want the optimizer to consider the invisible indexes in its operation, you can set the
new initialization parameter OPTIMIZER_USE_INVISIBLE_INDEXES to TRUE (the default is
FALSE). You can set the parameter in the system and session levels.
-- obtain info about indexes
sel ect * f r omDBA_I NDEXES;
sel ect * f r omDBA_I ND_COLUMNS;
-- for funcation-based indexes
sel ect * f r omDBA_I ND_EXPRESSI ONS;
-- optimizer stats
sel ect * f r omDBA_I ND_STATI STI CS;
-- obtained from ANALYZE INDEX...VALIDATE STRUCTURE
sel ect * f r omI NDEX_STATS;

-- create index
CREATE I NDEX emp_ename ON emp( ename)
TABLESPACE user s
STORAGE ( I NI TI AL 20K
NEXT 20k
PCTI NCREASE 75) ;
CREATE I NDEX emp_ename ON emp( ename) COMPUTE STATI STI CS;
CREATE I NDEX emp_name ON emp ( mgr , emp1, emp2, emp3) ONLI NE;
CREATE UNI QUE I NDEX dept _uni que_i ndex ON dept ( dname) TABLESPACE i ndx;
CREATE TABLE emp ( empno NUMBER( 5) PRI MARY KEY, age I NTEGER) ENABLE PRI MARY
KEY USI NG I NDEX TABLESPACE user s;
CREATE TABLE a ( a1 I NT PRI MARY KEY USI NG I NDEX ( cr eat e i ndex ai on a ( a1) ) ) ;
CREATE TABLE b( b1 I NT, b2 I NT,
CONSTRAI NT bu1 UNI QUE ( b1, b2)
USI NG I NDEX ( cr eat e uni que i ndex bi on b( b1, b2) ) ,
CONSTRAI NT bu2 UNI QUE ( b2, b1) USI NG I NDEX bi ) ;
CREATE TABLE c( c1 I NT, c2 I NT) ;
CREATE I NDEX ci ON c ( c1, c2) ;
ALTER TABLE c ADD CONSTRAI NT cpk PRI MARY KEY ( c1) USI NG I NDEX ci ;

-- bitmap index
Note: do not cr eat e i t on a t abl e t hat mi ght be updat ed by mor e t han one
sessi on, ot her wi se you r i sk seei ng ORA- 02049 er r or now and t hen!
CREATE BI TMAP I NDEX gender _i dx ON empl oyee( gender ) TABLESPACE emp_i ndex_05;

-- Reverse-Key Indexes
- - good when you do sequent i al i nser t i on of val ues i nt o t he i ndex
CREATE I NDEX r ever se_i dx ON empl oyee( emp_i d) REVERSE;

-- function based
CREATE I NDEX ar ea_i ndex ON r i ver s ( ar ea( geo) ) ;

-- compress
CREATE I NDEX emp_ename ON emp( ename) TABLESPACE user s COMPRESS 1;
ALTER I NDEX emp_ename REBUI LD NOCOMPRESS;

Page 146 Oracle DBA Code Examples

-- Invisible Index (11g)
CREATE I NDEX name_i ndx ON empl oyees( emp_name) I NVI SI BLE;
SELECT / *+ i ndex ( EMP_NAME NAME_I NDEX) */ . . .
ALTER I NDEX name_i ndx VI SI BLE;
ALTER I NDEX name_i ndx I NVI SI BLE;
SELECT I NDEX_NAME, VI SI BI LI TY FROM DBA_I NDEXES WHERE I NDEX_NAME=' NAME_I NDX' ;

- - Bi t map J oi n I ndex ( see next sect i on) .

-- rebuilding an index
ALTER I NDEX emp_name REBUI LD;
ALTER I NDEX emp_name REBUI LD ONLI NE;

-- Monitoring Index Usage
-- as t he i ndex owner
-- Note: gener al l y, do not dr op an i ndex bui l d on a FK col umn
ALTER I NDEX i ndex MONI TORI NG USAGE;
ALTER I NDEX i ndex NOMONI TORI NG USAGE;
Sel ect I NDEX_NAME, TABLE_NAME, MONI TORI NG, USED, START_MONI TORI NG, END_MONI TORI NG
Fr omV$OBJ ECT_USAGE - - as t he i ndex owner
WHERE I NDEX_NAME=' EMP_LNAME_I ND' ;

-- Monitoring Space Use of Indexes
- - 1. Anal yzi ng st at i st i cs
exec DBMS_STATS. GATHER_I NDEX_STATS( OWNNAME=>' HR' , I NDNAME=>' EMP_LNAME_I ND' )
- - 2. Val i dat i ng t he i ndex
ANALYZE I NDEX EMP_LNAME_I ND VALI DATE STRUCTURE;
- - 3. Checki ng PCT_USED
SELECT PCT_USED FROM I NDEX_STATS WHERE NAME = ' EMP_LNAME_I ND' ;
- - 4. Dr oppi ng and r ebui l di ng ( or coal esci ng) t he i ndex
ALTER I NDEX emp_name REBUI LD;

- - est i mat i ng i ndex space
- - gat her i ndex and i t s under l yi ng t abl e st at i st i cs
SET SERVEROUTPUT ON
decl ar e
l _i ndex_ddl VARCHAR2( 1000) ;
l _used_byt es NUMBER;
l _al l ocat ed_byt es NUMBER;
BEGI N
DBMS_SPACE.create_index_cost (
DDL => ' cr eat e i ndex per sons_i dx on per sons( per son_i d) ' ,
USED_BYTES => l _used_byt es,
ALLOC_BYTES => l _al l ocat ed_byt es) ;
DBMS_OUTPUT. PUT_LI NE ( ' used = ' | | t o_char ( l _used_byt es/ 1024) | | ' KB ' | | '
al l ocat ed = ' | | t o_char ( l _al l ocat ed_byt es/ 1024) | | ' KB' ) ;
END;
/
Using Bitmap Join Indexes (BJI)
A bitmap join index is a bitmap index for the join of two or more tables. It is designed
when joining fact tables with dimension tables as in warehouse databases (start schema
model).
CREATE BI TMAP I NDEX NAMES_CTR_bj i
ON NAMES2( COUNTRI ES. COUNTRY_NAME)
Page 147 Oracle DBA Code Examples

FROM NAMES2, COUNTRI ES
WHERE NAMES2. NAT_I D=COUNTRI ES. I D
NOLOGGI NG COMPUTE STATI STI CS;

SELECT / *+ I NDEX_COMBI NE( N NAMES_CTR_bj i ) */
C. COUNTRY_NAME
FROM NAMES2 N, COUNTRI ES C
WHERE N. NAT_I D = C. I D;
Partitioned Indexes
-- Global Indexes
-- can be nonpartitioned or partitioned indexes
CREATE I NDEX t i cket sal es_i dx ON
t i cket _sal es( mont h) GLOBAL
PARTI TI ON BY r ange( mont h)
( PARTI TI ON t i cket sal es1_i dx VALUES LESS THAN ( 3)
PARTI TI ON t i cket sal es1_i dx VALUES LESS THAN ( 6)
PARTI TI ON t i cket sal es2_i dx VALUES LESS THAN ( 9)
PARTI TI ON t i cket sal es3_i dx VALUES LESS THAN ( MAXVALUE) ) ;

CREATE I NDEX hgi dx
ON t ab ( c1, c2, c3) GLOBAL
PARTI TI ON BY HASH ( c1, c2)
( PARTI TI ON p1 TABLESPACE t s1,
PARTI TI ON p2 TABLESPACE t s2,
PARTI TI ON p3 TABLESPACE t s3,
PARTI TI ON p4 TABLESPACE t s4) ;

-- Local Indexes
CREATE I NDEX t i cket _no_i dx ON
t i cket _sal es( t i cket __no) LOCAL TABLESPACE l ocal i dx_01;
Page 148 Oracle DBA Code Examples

Managing Materialized Views
Obtaining Information about Materialized Views
-- all info about the mviews
SELECT
OWNER, MVI EW_NAME, CONTAI NER_NAME, QUERY, QUERY_LEN,
UPDATABLE, UPDATE_LOG, MASTER_ROLLBACK_SEG, MASTER_LI NK, REWRI TE_ENABLED,
REWRI TE_CAPABI LI TY, REFRESH_MODE, REFRESH_METHOD, BUI LD_MODE,
FAST_REFRESHABLE,
LAST_REFRESH_TYPE, LAST_REFRESH_DATE, STALENESS, AFTER_FAST_REFRESH,
UNKNOWN_PREBUI LT,
UNKNOWN_PLSQL_FUNC, UNKNOWN_EXTERNAL_TABLE, UNKNOWN_CONSI DER_FRESH,
UNKNOWN_I MPORT,
UNKNOWN_TRUSTED_FD, COMPI LE_STATE, USE_NO_I NDEX, STALE_SI NCE
FROM DBA_MVI EWS
ORDER BY OWNER, MVI EW_NAME


-- list mview last refreshed on year or longer ago
- - Not e: t hey cause t he mvi ew l ogs l i nked t o t hemt o get so l ar ge by t i me
SELECT OWNER, MVI EW_NAME,
TO_CHAR( LAST_REFRESH_DATE, ' DD- MM- YY' ) LAST_REFRESHED_DATE
FROM DBA_MVI EWS
WHERE LAST_REFRESH_DATE < SYSDATE- 365
ORDER BY LAST_REFRESH_DATE ASC


-- determine the master table ( and l ast r ef r esh t i me)
sel ect OWNER, NAME, MASTER_OWNER, MASTER, LAST_REFRESH
f r omDBA_SNAPSHOT_REFRESH_TI MES


-- FAST_REFRESHABLE mviews which couldn't make FAST refresh
-- in their last refreshes
SELECT
OWNER, MVI EW_NAME, REFRESH_METHOD, FAST_REFRESHABLE,
LAST_REFRESH_TYPE, LAST_REFRESH_DATE, STALENESS, AFTER_FAST_REFRESH,
COMPI LE_STATE, STALE_SI NCE
FROM DBA_MVI EWS
WHERE FAST_REFRESHABLE<>' NO' and LAST_REFRESH_TYPE<>' FAST'
ORDER BY OWNER, MVI EW_NAME


-- all MATERIALIZED VIEW LOGS
SELECT
LOG_OWNER, MASTER, LOG_TABLE, LOG_TRI GGER, ROWI DS,
PRI MARY_KEY, OBJ ECT_I D, FI LTER_COLUMNS,
SEQUENCE, I NCLUDE_NEW_VALUES
FROM DBA_MVI EW_LOGS
ORDER BY LOG_OWNER, MASTER
Monitoring the Progress of a Materialized View Refresh
Reference: Document ID 258021.1
/* Determine if a Specific MVIEW is Being Refreshed */
Page 149 Oracle DBA Code Examples

sel ect o. owner , o. obj ect _name mvi ew, user name, s. si d
f r omv$l ock l , dba_obj ect s o, v$sessi on s
wher e o. obj ect _i d=l . i d1 and
l . t ype=' J I ' and
l . l mode=6 and
s. si d=l . si d and
o. obj ect _t ype=' TABLE' ;



/* Determine if a Refresh Group is Being Refreshed */
- - Gi ven t he name of t he r ef r esh gr oup and i t s owner , t he
- - f ol l owi ng quer y can be used t o i dent i f y i f a r ef r esh
- - i s bei ng execut ed by a j ob queue pr ocess:
sel ect s. si d, s. user name
f r omdba_j obs_r unni ng j r , v$sessi on s, dba_j obs j
wher e j r . si d=s. si d and
j . j ob=j r . j ob and
upper ( j . what ) l i ke ' %REFRESH%<name of t he r ef r esh gr oup>%' ;

- - t o det er mi ne i f a r ef r esh has been execut ed manual l y (
- - not t hr ough a backgr ound j ob )
sel ect user name, si d, r owner , r name
f r om( sel ect user name, s. si d, r c. r owner , r c. r name, count ( *)
f r omv$l ock l , dba_obj ect s o, v$sessi on s,
dba_r ef r esh_chi l dr en r c
wher e o. obj ect _i d=l . i d1 and
l . t ype=' J I ' and
l . l mode=6 and
s. si d=l . si d and
o. obj ect _t ype=' TABLE' and
o. obj ect _name=r c. name and
o. owner =r c. owner and
r c. t ype=' SNAPSHOT'
gr oup by user name, s. si d, r c. r owner , r c. r name
havi ng count ( *) =( sel ect count ( *) f r omdba_r ef r esh_chi l dr en
wher e r owner = r c. r owner and r name=r c. r name and
t ype=' SNAPSHOT' ) ) ;


/* Determine which MVIEW in a Refresh Group is Being Refreshed */
sel ect SI D, SERI AL#, CURRMVOWNER, CURRMVNAME
f r omv$mvr ef r esh



/* Determine the Current Phase of a Refresh */
- - i f i n Pr opagat i on phase ( push and pur ge)
- - l ocks ar e r el eased once push and pur ge f i ni shed
- - i n Push phase:
sel ect l . si d,
decode( count ( *) , 0, ' No pr opagat i on i n pr ogr ess' ,
' Pr opagat i on i n pr ogr ess' ) St at e
f r omv$l ock l , dbms_l ock_al l ocat ed l a
wher e l . t ype=' UL' and
l . l mode=4 and
l . i d1=l a. l ocki d and
Page 150 Oracle DBA Code Examples

l a. name=' ORA$DEF$EXE$PushCommonLock'
gr oup by l . si d;

- - i dent i f yi ng t he t ar get si t e of t he pr opagat i on:
sel ect l . si d, ' Cur r ent l y pr opagat i ng t o ' | | subst r ( l a. name, 13)
f r omv$l ock l , dbms_l ock_al l ocat ed l a
wher e l . t ype=' UL' and
l . l mode=6 and
l . i d1=l a. l ocki d and
l a. name l i ke ' ORA$DEF$EXE$%' ;

- - i n Pur ge phase:
- - i f r ef r esh i s i nvoked wi t h pur ge_opt i on>0 and par al l el i sm>0
sel ect l . si d,
decode( count ( *) , 0, ' No pur ge i n pr ogr ess' ,
' Pur ge i s i n pr ogr ess' ) St at e
f r omv$l ock l , dbms_l ock_al l ocat ed l a
wher e l . t ype=' UL' and
l . l mode=6 and
l . i d1=l a. l ocki d and
l a. name=' ORA$DEF$EXE$Pur geCommonLock'
gr oup by l . si d;


- - Ref r esh Subphases ( SETUP, I NSTATNI ATI ON and WRAPUP)
- - t o get :
- t he t ype of t he ongoi ng r ef r esh
- t he phase of t he ongoi ng r ef r esh
- t he number of DMLs per f or med by t he r ef r esh
sel ect CURRMVOWNER_KNSTMVR | | ' . ' | | CURRMVNAME_KNSTMVR
" MVI EWBEI NG REFRESHED" ,
decode( REFTYPE_KNSTMVR, 1, ' FAST' , 2, ' COMPLETE' , ' UNKNOWN' )
REFTYPE,
decode( GROUPSTATE_KNSTMVR, 1, ' SETUP' , 2, ' I NSTANTI ATE' ,
3, ' WRAPUP' , ' UNKNOWN' ) STATE,
TOTAL_I NSERTS_KNSTMVR I NSERTS,
TOTAL_UPDATES_KNSTMVR UPDATES,
TOTAL_DELETES_KNSTMVR DELETES
f r omX$KNSTMVR X
WHERE t ype_knst =6 and
exi st s ( sel ect 1 f r omv$sessi on s
wher e s. si d=x. si d_knst and
s. ser i al #=x. ser i al _knst ) ;


/* Steps to Determine Whether a Refresh is Hanging, or Moving Slowly */
- - i f t he r ef r esh i n Pr opagat i on:
- - check f or bl ocki ng sessi ons:
- - t o i dent i f y i f a r ow bei ng pushed i s l ocked by a user s sessi on:
sel ect
s. user name,
w. hol di ng_sessi on hol der ,
h. user name hol der _name,
s. r ow_wai t _r ow# r owno,
o. obj ect _name,
o. owner
f r omdba_wai t er s w, dba_obj ect s o, v$sessi on s, v$sessi on h
Page 151 Oracle DBA Code Examples

wher e w. wai t i ng_sessi on = s. si d
and w. hol di ng_sessi on = h. si d
and s. r ow_wai t _obj # = o. obj ect _i d;

- - Check t he wai t event s
- - i f r ef r esh i s bei ng execut ed f r omDBMS_J OB:
sel ect sw. si d, sw. event , sw. p1, sw. p2
f r omv$sessi on_wai t sw
wher e sw. si d i n ( sel ect qs. si d
f r omdba_j obs_r unni ng j r , dba_j obs j ,
v$px_sessi on qs
wher e j r . j ob = j . j ob
and j r . si d = qs. qcsi d
and upper ( j . what ) l i ke ' %. . %' )
and sw. wai t _t i me = 0;

- - i f r ef r esh i s bei ng execut ed by a user s sessi on:
sel ect sw. si d, sw. event , sw. p1, sw. p2
f r omv$sessi on_wai t sw, v$sessi on s
wher e sw. si d = s. si d
and sw. si d i n ( sel ect qs. si d f r omv$px_sessi on qs)
and sw. wai t _t i me = 0


- - Check i f a l ar ge er r or i s bei ng queued:
- - t o i dent i f y i f a l ar ge er r or i s bei ng queued at t he r emot e mast er si t e:
sel ect count ( *)
f r omv$sql ar ea a, v$sessi on s
wher e s. sql _addr ess = a. addr ess
and s. sql _hash_val ue = a. hash_val ue
and a. sql _t ext l i ke ' %DEF$_AQERROR%'
and s. user name = ' REPADMI N' ;


- - i f r ef r esh i n WRAPUP phase:
- - get t he wai t event :
- - i n nor mal cases, i t ' s r ead scat t er ed or sequent i al :
sel ect event , p1, p2, p3
f r omv$sessi on_wai t
wher e si d=<SI D of t he sessi on at mast er si t e>;

- - t he obj ect t hat i s bei ng accessed by:
sel ect owner , segment _name
f r omdba_ext ent s
wher e f i l e_i d=<P1> and
<P2> bet ween bl ock_i d and bl ock_i d+bl ocks- 1;

- - i f t he accessed obj ect i s MVi ew l og, check t he f ol l owi ng sect i on
- - whi ch di agnoses t he MVi ew Log


- - i f r ef r esh i n I NSTANTI ATI ON phase:
- - t he r ows ar e pul l ed f r omt he mast er si t e
- - check t he wai t :
sel ect event , p1, p2, p3
f r omv$sessi on_wai t
wher e si d=<SI D of t he sessi on at mast er si t e>;
Page 152 Oracle DBA Code Examples


- - i f t he event i s enqueue: check t he bl ocki ng sessi on
sel ect
s. user name,
w. hol di ng_sessi on hol der ,
h. user name hol der _name,
s. r ow_wai t _r ow# r owno,
o. obj ect _name,
o. owner
f r omdba_wai t er s w, dba_obj ect s o, v$sessi on s, v$sessi on h
wher e w. wai t i ng_sessi on = s. si d
and w. hol di ng_sessi on = h. si d
and s. r ow_wai t _obj # = o. obj ect _i d;

- - i f event i s SQL*Net message f r omdbl i nk:
t he sessi on at mast er si t e shoul d be checked f or t he t ype of t he wai t
i f t he wai t i s " SQL*Net message f r omdbl i nk" i n bot h si t es,
submi t a SR i n Or acl e Suppor t .
Materialized View Typical Refresh Errors
ORA- 12004: " REFRESH FAST cannot be used f or . . .
Thi s er r or i ndi cat es a pr obl emwi t h t he l og at mast er . See Not e: 179469. 1 f or
f ur t her i nf or mat i on.

ORA- 12034: " snapshot l og on " %s" . " %s" younger t han l ast r ef r esh"
Thi s er r or al so i ndi cat es a pr obl emwi t h t he l og at mast er . See Not e: 204127. 1
f or f ur t her i nf or mat i on.

ORA- 23402: r ef r esh was abor t ed because of conf l i ct s caused by def er r ed t xns
Thi s er r or i s caused by out st andi ng conf l i ct s l ogged i n t he Def Er r or t abl e at
t he mast er . Thi s can be wor kar ound by set t i ng r ef r esh_af t er _er r or s t o t r ue.
See Not e: 1031119. 6 and Not e: 39232. 1 f or t he det ai l s.

ORA- 23385: r epl i cat i on par al l el push heap_si ze ar gument not val i d Thi s er r or
i s caused i f t he heap_si ze val ue i s set t o NULL. Quer y r gr oup$ t o obt ai n t he
cur r ent val ue of heap_si ze and use dbms_r ef r esh. change t o set i t t o not nul l
val ue. I E. 0. See Not e: 49558. 1 f or t he er r or def i ni t i on.
Using Materialized Views
Good reference is Note ID 179466.1
If USER1 wants to refresh MView created by USER2 and MView Master Table is owned by
USER3, then the following privileges are required:
gr ant SELECT ANY TABLE t o USER2;
gr ant CREATE TABLE, CREATE ANY MATERI ALI ZED VI EWt o USER2;
gr ant FLASHBACK on USER3. OAS_DOCLI NE t o USER1;
gr ant FLASHBACK on USER3. OAS_DOCLI NE t o USER2;
gr ant FLASHBACK on USER3. MLOG$_OAS_DOCLI NE t o USER1;
gr ant FLASHBACK on USER3. . MLOG$_OAS_DOCLI NE t o USER2;
For COMPLETE refresh, to avoid logging, you can consider setting ATOMIC_REFRESH=false. It
makes the refresh faster.
When creating materialized view, you should keep in mind the following restrictions:
The defining query of the materialized view cannot contain any non-repeatable
expressions (ROWNUM, SYSDATE, non-repeatable PL/SQL functions, and so on).
Page 153 Oracle DBA Code Examples

The query cannot contain any references to RAW or LONG RAW datatypes or object REFs
Restrictions on Fast Refresh
The defining query of the materialized view is restricted as follows:
The materialized view must not contain references to non-repeating expressions like
SYSDATE and ROWNUM.
The materialized view must not contain references to RAW or LONG RAW data types.
It cannot contain a SELECT list subquery.
It cannot contain analytical functions (for example, RANK) in the SELECT clause.
It cannot contain a MODEL clause.
It cannot contain a HAVING clause with a subquery.
It cannot contain nested queries that have ANY, ALL, or NOT EXISTS.
It cannot contain a [START WITH ] CONNECT BY clause.
It cannot contain multiple detail tables at different sites.
ON COMMIT materialized views cannot have remote detail tables.
Nested materialized views must have a join or aggregate.
If you received the following error when trying to refresh a materialized view, trying compiling
it:
ORA- 00942: t abl e or vi ew does not exi st
ORA- 06512: at " SYS. DBMS_SNAPSHOT" ,
al t er mat er i al i zed vi ew compi l e

- - r equi r ed pr i vs
GRANT CREATE MATERI ALI ZED VI EWTO hr ;
GRANT QUERY REWRI TE TO hr ;

- - mv l og
- - you must speci f y t he ROWI D, SEQUENCE and t he I NCLUDI NG NEWVALUES
- - For aggr egat e mat er i al i zed vi ews, i t must al so cont ai n ever y col umn
- - i n t he t abl e r ef er enced i n t he mat er i al i zed vi ew
CREATE MATERI ALI ZED VI EWLOG
ON empl oyees WI TH SEQUENCE, ROWI D
( empl oyee_i d, depar t ment _i d, sal ar y) I NCLUDI NG NEWVALUES;

CREATE MATERI ALI ZED VI EWLOG
ON depar t ment s WI TH SEQUENCE, ROWI D
( depar t ment _i d, depar t ment _name) I NCLUDI NG NEWVALUES;

ALTER MATERI ALI ZED VI EWLOG ON sal es ADD ROWI D
( pr od_i d, cust _i d, t i me_i d, amount _sol d) I NCLUDI NG NEWVALUES;

DROP MATERI ALI ZED VI EWLOG ON sal es;

- - cr eat e mv
- - t he opt i ons
BUI LD I MMEDI ATE | DEFERRED
REFRESH NEVER, FAST, FORCE, COMPLETE - on commi t or on demand
ENABLE QUERY REWRI TE - - i s a must f or r ewr i t i ng quer i es. DI SABLE
WI TH PRI MARY KEY
START WI TH ROUND( SYSDATE + 1) + 11/ 24 NEXT NEXT_DAY( TRUNC( SYSDATE) , ' MONDAY' )
+ 15/ 24
r ecommended t o gat her st at s on i t t hen
EXECUTE DBMS_STATS. GATHER_TABLE_STATS ( ' HR' , ' DEPT01_MV' , est i mat e_per cent
Page 154 Oracle DBA Code Examples

=> 20, bl ock_sampl e => TRUE, cascade => TRUE) ;

- - ( 1) Mat er i al i zed Vi ews wi t h Aggr egat es
- - vml og must al so cont ai n ever y col umn
- - i n t he t abl e r ef er enced i n t he mat er i al i zed vi ew
- - t her e must be a COUNT( *) and a COUNT( col umn) on any aggr egat ed col umns
CREATE MATERI ALI ZED VI EWdept 01_mv
( depar t ment _i d, depar t ment _name, sal ar y_count , aver age_sal ar y)
TABLESPACE t s1
BUI LD I MMEDI ATE
REFRESH FAST
ENABLE QUERY REWRI TE
AS
sel ect d. depar t ment _i d, d. depar t ment _name,
count ( e. sal ar y) , - - i t i s a must f or mv wi t h aggr egat e or count ( *) ,
avg( e. sal ar y)
f r omdepar t ment s d, empl oyees e
wher e d. depar t ment _i d = e. depar t ment _i d
gr oup by d. depar t ment _i d, d. depar t ment _name;

CREATE MATERI ALI ZED VI EWpr oduct _sal es_mv
TABLESPACE t s1
BUI LD I MMEDI ATE - - DEFERRED
REFRESH FAST - - FAST, FORCE, COMPLETE - on commi t or on demand
ENABLE QUERY REWRI TE
AS
SELECT p. pr od_name, SUM( s. amount _sol d) AS dol l ar _sal es,
COUNT( *) AS cnt , COUNT( s. amount _sol d) AS cnt _amt
FROM sal es s, pr oduct s p
WHERE s. pr od_i d = p. pr od_i d GROUP BY p. pr od_name;


- - ( 2) Mat er i al i zed Vi ews Cont ai ni ng Onl y J oi ns
- - cont ai n onl y j oi ns and no aggr egat es
- - ROWI D col umn must be pr esent i n each mat er i al i zed vi ew l og and mv SELECT
CREATE MATERI ALI ZED VI EWLOG ON sal es WI TH ROWI D;
CREATE MATERI ALI ZED VI EWLOG ON t i mes WI TH ROWI D;
CREATE MATERI ALI ZED VI EWLOG ON cust omer s WI TH ROWI D;
CREATE MATERI ALI ZED VI EWdet ai l _sal es_mv
PARALLEL
BUI LD I MMEDI ATE
REFRESH FAST AS
SELECT s. r owi d " sal es_r i d" , t . r owi d " t i mes_r i d" , c. r owi d " cust omer s_r i d" ,
c. cust _i d, c. cust _l ast _name, s. amount _sol d, s. quant i t y_sol d, s. t i me_i d
FROM sal es s, t i mes t , cust omer s c
WHERE s. cust _i d = c. cust _i d( +) AND s. t i me_i d = t . t i me_i d( +) ;


- - ( 3) Nest ed Mat er i al i zed Vi ews
- - a mat er i al i zed vi ew whose def i ni t i on i s based on anot her mat er i al i zed vi ew
CREATE MATERI ALI ZED VI EWLOG ON sal es WI TH ROWI D;
CREATE MATERI ALI ZED VI EWLOG ON cust omer s WI TH ROWI D;
CREATE MATERI ALI ZED VI EWLOG ON t i mes WI TH ROWI D;
/ *cr eat e mat er i al i zed vi ew j oi n_sal es_cust _t i me as f ast r ef r eshabl e at
COMMI T t i me */
CREATE MATERI ALI ZED VI EWj oi n_sal es_cust _t i me
REFRESH FAST ON COMMI T AS
Page 155 Oracle DBA Code Examples

SELECT c. cust _i d, c. cust _l ast _name, s. amount _sol d, t . t i me_i d,
t . day_number _i n_week, s. r owi d sr i d, t . r owi d t r i d, c. r owi d cr i d
FROM sal es s, cust omer s c, t i mes t
WHERE s. t i me_i d = t . t i me_i d AND s. cust _i d = c. cust _i d;
/ * cr eat e mat er i al i zed vi ew l og on j oi n_sal es_cust _t i me
and i ncl ude t he r equi r ed col umns */
CREATE MATERI ALI ZED VI EWLOG ON j oi n_sal es_cust _t i me
WI TH ROWI D ( cust _l ast _name, day_number _i n_week, amount _sol d)
I NCLUDI NG NEWVALUES;
/ * cr eat e t he si ngl e- t abl e aggr egat e mat er i al i zed vi ew sum_sal es_cust _t i me
on j oi n_sal es_cust _t i me as f ast r ef r eshabl e at COMMI T t i me */
CREATE MATERI ALI ZED VI EWsum_sal es_cust _t i me
REFRESH FAST ON COMMI T AS
SELECT COUNT( *) cnt _al l , SUM( amount _sol d) sum_sal es, COUNT( amount _sol d)
cnt _sal es, cust _l ast _name, day_number _i n_week
FROM j oi n_sal es_cust _t i me
GROUP BY cust _l ast _name, day_number _i n_week;
- - Ref r eshi ng a Nest ed Mat er i al i zed Vi ew
DBMS_MVI EW. REFRESH( ' SALES_MV, COST_MV' , nest ed => TRUE) ;

/ * comment i ng on mvs */
COMMENT ON MATERI ALI ZED VI EWsal es_mv I S ' sal es mat er i al i zed vi ew' ;
SELECT MVI EW_NAME, COMMENTS
FROM USER_MVI EW_COMMENTS WHERE MVI EW_NAME = ' SALES_MV' ;
Using Query Rewriting
A query is rewritten only when a certain number of conditions are met:
o Query rewrite must be enabled for the session.
o A materialized view must be enabled for query rewrite.
o The rewrite integrity level should allow the use of the materialized view.
Use Column Alias Lists in the CREATE MATERIALIZED VIEW command to let the query
rewrite work
/ * Requi r ed Pr i vs */
gr ant quer y r ewr i t e t o hr ;
- - i f t he mv uses a t abl e f r omot her schema
gr ant quer y r ewr i t e on empl oyees t o scot t ;
or
gr ant gl obal quer y r ewr i t e t o hr ;

/ * Ensur i ng t hat Quer y Rewr i t e Takes Ef f ect */
- - ( 1) quer y r ewr i t e enabl ed f or t he mv
sel ect REWRI TE_ENABLED f r omuser _mvi ews wher e mvi ew_name=' DEPT01_MV' ;
ALTER MATERI ALI ZED VI EWdept 01_mv ENABLE QUERY REWRI TE ;
- - ( 2) QUERY_REWRI TE_ENABLED = TRUE | FORCE
ALTER SESSI ON SET QUERY_REWRI TE_ENABLED=t r ue;
sel ect get _par ( ' quer y_r ewr i t e_enabl ed' ) f r omdual ;
- - f or user wi t h dba pr i v
sel ect val ue f r omv$par amet er wher e upper ( name) =' QUERY_REWRI TE_ENABLED' ;
al t er syst emset QUERY_REWRI TE_ENABLED=TRUE;
- - ( 3) OPTI MI ZER_MODE = ALL_ROWS, FI RST_ROWS, or FI RST_ROWS_n, ( wher e n = 1,
10, 100, 1000)
sel ect get _par ( ' OPTI MI ZER_MODE' ) f r omdual ;
- - ( 4) OPTI MI ZER_FEATURES_ENABLE must be 10. 0. 0 or hi gher
sel ect val ue f r omv$par amet er wher e upper ( name) =' OPTI MI ZER_FEATURES_ENABLE' ;
Page 156 Oracle DBA Code Examples


/ * Col umn Al i as */
- - f ai l ed exampl e
CREATE MATERI ALI ZED VI EWsal es_mv
ENABLE QUERY REWRI TE AS
SELECT s. t i me_i d sal es_t i d, c. t i me_i d cost s_t i d
FROM sal es s, pr oduct s p, cost s c
WHERE s. pr od_i d = p. pr od_i d AND c. pr od_i d = p. pr od_i d AND
p. pr od_name I N ( SELECT pr od_name FROM pr oduct s) ;
- - t he r i ght way
CREATE MATERI ALI ZED VI EWsal es_mv ( sal es_t i d, cost s_t i d)
ENABLE QUERY REWRI TE AS
SELECT s. t i me_i d, c. t i me_i d
FROM sal es s, pr oduct s p, cost s c
WHERE s. pr od_i d = p. pr od_i d AND c. pr od_i d = p. pr od_i d AND
p. pr od_name I N ( SELECT pr od_name FROM pr oduct s) ;

/ * Rewr i t e I nt egr i t y */
- - QUERY_REWRI TE_I NTEGRI TY: ENFORCED ( r et ur ned dat a i s 100%cor r ect ) , TRUSTED,
STALE_TOLERATED

/ * Ver i f yi ng t hat Quer y Rewr i t e has Occur r ed */
EXPLAI N PLAN FOR
sel ect d. depar t ment _i d, d. depar t ment _name,
count ( e. sal ar y) ,
avg( e. sal ar y)
f r omdepar t ment s d, empl oyees e
wher e d. depar t ment _i d = e. depar t ment _i d
gr oup by d. depar t ment _i d, d. depar t ment _name;

- - i f r ewr i t i ng occur r ed, you shoul d see oper at i on: MAT_VI EWREWRI TE ACCESS
SELECT OPERATI ON, OBJ ECT_NAME FROM PLAN_TABLE;

/ * Usi ng t he EXPLAI N_REWRI TE Pr ocedur e wi t h Quer y Rewr i t e */
- - t ar get : t o know why r ewr i t i ng di dn' t occur
- - 1) cr eat e EXPLAI N_REWRI TE t abl e
@/ or acl e/ or adb10g/ r dbms/ admi n/ ut l xr w. sql
- - 2) execut e
decl ar e
v var char 2( 4000) ;
begi n
v : = ' sel ect d. depar t ment _i d, d. depar t ment _name, count ( e. sal ar y) ,
avg( e. sal ar y) f r omdepar t ment s d, empl oyees e wher e d. depar t ment _i d =
e. depar t ment _i d gr oup by d. depar t ment _i d, d. depar t ment _name' ;
DBMS_MVIEW.EXPLAIN_REWRITE(
quer y => v,
mv =>' ' , - - you can speci f y t he comma- separ at ed mv( s) or NULL t o consi der al l
mvs
st at ement _i d => ' I D6' ) ; - - cl i ent - suppl i ed uni que i dent i f i er t o di st i ngui sh
out put messages
end;
/

SELECT message, or i gi nal _cost , r ewr i t t en_cost
FROM r ewr i t e_t abl e ORDER BY sequence;

- - al t er nat i vel y t o see neat out put use SYS. XRW( see War eshouse document at i on)
Page 157 Oracle DBA Code Examples

ReWrite Hints
/ * REWRI TE and NOREWRI TE Hi nt s */
SELECT / *+ NOREWRI TE */ . . .
SELECT / *+ REWRI TE ( sum_sal es_pscat _week_mv) */ . . .

/ * The Rewr i t e_or _Er r or Hi nt */
- - use t he mv or er r or
SELECT / *+ REWRI TE_OR_ERROR */
pr od_i d, SUM( quant i t y_sol d) AS sum_sal es_qt y
FROM sal es_dat a
GROUP BY pr od_i d;

/ * NO_MULTI MV_REWRI TE hi nt pr event s t he quer y f r ombei ng r ewr i t t en wi t h mor e
t han one mat er i al i zed
NO_BASETABLE_MULTI MV_REWRI TE hi nt pr event s t he quer y f r ombei ng r ewr i t t en
wi t h a combi nat i on of mat er i al i zed vi ews and t he base t abl es
*/
Using EXPLAIN_MVIEW Procedure: Viewing Materialized View Capabilities
Target: to determine if a materialized view is fast refreshable and what types of query
rewrite you can perform with a particular materialized view.

DBMS_MVI EW. EXPLAI N_MVI EW(
mv - - mv, a SELECT or a CREATE MATERI ALI ZED VI EWst at ement
st at ement _i d - - any i d

- - ( 1) cr eat e MV_CAPABI LI TI ES_TABLE
@/ or acl e/ or adb10g/ r dbms/ admi n/ ut l xmv. sql
- - ( 2) execut e
decl ar e
v var char 2( 4000) ;
begi n
v : = ' DEPT01_MV' ;
DBMS_MVIEW.EXPLAIN_MVIEW( V, ' I D01' ) ;
Commi t ;
end;
/

SELECT CAPABI LI TY_NAME, POSSI BLE, RELATED_TEXT, RELATED_NUM, MSGNO, MSGTXT
FROM MV_CAPABI LI TI ES_TABLE
WHERE STATEMENT_I D=' I D01'
ORDER BY SEQ
/

SELECT MSGTXT
FROM MV_CAPABI LI TI ES_TABLE
WHERE STATEMENT_I D=' I D01'
ORDER BY SEQ
/
Using DBMS_ADVISOR.TUNE_MVIEW
The TUNE_MVIEW procedure shows how to decompose a materialized view into two or
more materialized views or to restate the materialized view in a way that is more
advantageous for fast refresh and query rewrite. TUNE_MVIEW analyzes and processes
the input statement and generates two sets of output results: one for the materialized
view implementation and the other for undoing the CREATE materialized view operations.
Page 158 Oracle DBA Code Examples

ADVISOR privilege required to execute the procedure.
decl ar e
t ask_cust _mv VARCHAR2( 30) ;
cr eat e_mv_ddl VARCHAR2( 4000) ;
begi n
t ask_cust _mv : = ' cust _mv' ;
cr eat e_mv_ddl : = ' CREATE MATERI ALI ZED VI EWREPTEST. MP_OAS_BALANCE_MV
BUI LD I MMEDI ATE
REFRESH FORCE ON DEMAND
WI TH PRI MARY KEY
as
SELECT cmpcode | | LPAD ( TO_CHAR ( yr ) , 4, 0) " BAL_KEY" ,
CMPCODE,
YR,
PERI OD,
BALCODE,
CURCODE,
REPBASI S,
CURFLAG,
ACCODE,
DEBI T_VALUE,
CREDI T_VALUE,
1 UNMARKER,
ROWI D RI D
FROM OAS_BALANCE
WHERE CMPCODE NOT I N ( ' ' XYZ' ' , ' ' KH' ' , ' ' GUI ' ' ) ' ;
DBMS_ADVI SOR. TUNE_MVI EW( t ask_cust _mv, cr eat e_mv_ddl ) ;
end;
/

- - Access I MPLEMENTATI ON Out put
SELECT * FROM USER_TUNE_MVI EWWHERE TASK_NAME= ' cust _mv' AND
SCRI PT_TYPE=' I MPLEMENTATI ON' ;

- - Save I MPLEMENTATI ON Out put i n a Scr i pt Fi l e
CREATE DI RECTORY TUNE_RESULTS AS ' / myscr i pt '
GRANT READ, WRI TE ON DI RECTORY TUNE_RESULTS TO PUBLI C;
EXECUTE DBMS_ADVI SOR. CREATE_FI LE( DBMS_ADVI SOR. GET_TASK_SCRI PT( ' cust _mv' ) ,
' TUNE_RESULTS' , ' mv_cr eat e. sql ' ) ;
Registering a User-defined Table as Materialized View
- - t abl e and mv have t he same name
CREATE TABLE sum_sales_tab
PCTFREE 0 TABLESPACE demo
AS
SELECT s. pr od_i d, SUM( amount _sol d) AS dol l ar _sal es, SUM( quant i t y_sol d) AS
uni t _sal es FROM sal es s GROUP BY s. pr od_i d;

CREATE MATERI ALI ZED VI EWsum_sales_tab_mv
ON PREBUI LT TABLE WI THOUT REDUCED PRECI SI ON
ENABLE QUERY REWRI TE AS
SELECT s. pr od_i d, SUM( amount _sol d) AS dol l ar _sal es,
SUM( quant i t y_sol d) AS uni t _sal es
FROM sal es s GROUP BY s. pr od_i d;
Page 159 Oracle DBA Code Examples

Managing Clusters and Hash Clusters
Hashing is useful when you have the following conditions:
Most queries are equality queries on the cluster key:
SELECT ... WHERE cluster_key = ...;
The tables in the hash cluster are primarily static in size so that you can determine the
number of rows and amount of space required for the tables in the cluster.
- - obt ai ni ng i nf o on cl ust er s
sel ect * f r omDBA_CLUSTERS;
- - map t abl e col umns t o cl ust er col umns
sel ect * f r omDBA_CLU_COLUMNS;

- - cr eat e cl ust er
CREATE CLUSTER emp_dept ( dept no NUMBER( 3) )
SI ZE 600
TABLESPACE user s
STORAGE ( I NI TI AL 200K
NEXT 300K
MI NEXTENTS 2
MAXEXTENTS 20
PCTI NCREASE 33) ;
CREATE TABLE emp (
empno NUMBER( 5) PRI MARY KEY,
ename VARCHAR2( 15) NOT NULL,
. . .
dept no NUMBER( 3) REFERENCES dept )
CLUSTER emp_dept ( dept no) ;
CREATE TABLE dept (
dept no NUMBER( 3) PRI MARY KEY, . . . )
CLUSTER emp_dept ( dept no) ;

- - cr eat e cl ust er i ndex
CREATE I NDEX emp_dept _i ndex
ON CLUSTER emp_dept
TABLESPACE user s
STORAGE ( I NI TI AL 50K
NEXT 50K
MI NEXTENTS 2
MAXEXTENTS 10
PCTI NCREASE 33) ;

- - dr oppi ng a cl ust er
- - no t abl es
DROP CLUSTER emp_dept ;
- - t her e ar e t abl es
DROP CLUSTER emp_dept I NCLUDI NG TABLES;
DROP CLUSTER emp_dept I NCLUDI NG TABLES CASCADE CONSTRAI NTS;
- - dr op a t abl e i n t he cl ust er
dr op t abl e dept ;

/ * Managi ng Hash Cl ust er s */

- - obt ai n i nf o
sel et * f r omDBA_CLUSTERS ;
Page 160 Oracle DBA Code Examples

sel et * f r omDBA_CLU_COLUMNS;
sel et * f r omDBA_CLUSTER_HASH_EXPRESSI ONS;

- - Cr eat i ng Hash Cl ust er s
CREATE CLUSTER t r i al _cl ust er ( t r i al no NUMBER( 5, 0) )
TABLESPACE user s
STORAGE ( I NI TI AL 250K NEXT 50K
MI NEXTENTS 1 MAXEXTENTS 3
PCTI NCREASE 0)
HASH I S t r i al no HASHKEYS 150;
CREATE TABLE t r i al (
t r i al no NUMBER( 5, 0) PRI MARY KEY,
. . . )
CLUSTER t r i al _cl ust er ( t r i al no) ;

- - Cr eat i ng a Sor t ed Hash Cl ust er
CREATE CLUSTER cal l _det ai l _cl ust er (
t el ephone_number NUMBER,
cal l _t i mest amp NUMBER SORT,
cal l _dur at i on NUMBER SORT )
HASHKEYS 10000 HASH I S t el ephone_number
SI ZE 256;
CREATE TABLE cal l _det ai l (
t el ephone_number NUMBER,
cal l _t i mest amp NUMBER SORT,
cal l _dur at i on NUMBER SORT,
ot her _i nf o VARCHAR2( 30) )
CLUSTER cal l _det ai l _cl ust er (
t el ephone_number , cal l _t i mest amp, cal l _dur at i on ) ;
- - f ol l owi ng sel ect get s advant age f r omt he sor t ed hash cl ust er
SELECT * WHERE t el ephone_number = 6505551212;

- - Cr eat i ng Si ngl e- Tabl e Hash Cl ust er s
CREATE CLUSTER peanut ( var i et y NUMBER)
SI ZE 512 SI NGLE TABLE HASHKEYS 500;

- - Dr oppi ng Hash Cl ust er s
DROP CLUSTER emp_dept ;
Page 161 Oracle DBA Code Examples

Managing Views, Sequences, and Synonyms
- - cr eat e vi ews
CREATE VI EWsal es_st af f AS
SELECT empno, ename, dept no FROM emp WHERE dept no = 10
WI TH CHECK OPTI ON CONSTRAI NT sal es_st af f _cnst ;
- - Cr eat i ng Vi ews wi t h Er r or s
CREATE FORCE VI EWAS . . . ;

- - cr eat i ng sequence
CREATE SEQUENCE emp_sequence
I NCREMENT BY 1
START WI TH 1
NOMAXVALUE
NOCYCLE
CACHE 10;
- - al t er a sequence
ALTER SEQUENCE emp_sequence
I NCREMENT BY 10
MAXVALUE 10000
CYCLE
CACHE 20;

- - Cr eat i ng Synonyms
CREATE PUBLI C SYNONYM publ i c_emp FOR j war d. emp;
Page 162 Oracle DBA Code Examples

Managing Transactions
Implementing Oracles Concurrency Control
Oracle Isolaction Levels
There are four possible isolation levels:
o Serializable: doesnt allow any concurrent.
o Repeatable read
o Read uncommitted
o Read committed (Default): Oracle only guarantees statement-level isolation here
(changes between reads are seen), not transaction-level isolation.

command Its effect
SET TRANSACTI ON READ
ONLY
When set, the transaction that follows operates on essentially
a snapshot of the database at the time the command was
issued. This is especially useful when multiple select
statements are executed over the course of a transaction, and
data must be consistent.
SET TRANSACTI ON READ
WRI TE
Set the transactgion back to read write
SET TRANSACTI ON
I SOLATI ON LEVEL READ
COMMI TTED
if we try to modify a record that already has a DML Row
Exclusive lock on that record, the attempt to update will wait
until the locks are released.
SET TRANSACTI ON
I SOLATI ON LEVEL
SERI ALI ZABLE
if we try to modify a record that already has a DML Row
Exclusive lock on that record, the attempt to update will fail

- - must be t he f i r st command i n an t r ansact i on
- - t o enabl e t r ansact i on- l evel i sol at i on
ALTER SESSI ON SET I SOLATI ON LEVEL SERI ALI ZABLE;
SET TRANSACTI ON I SOLATI ON LEVEL SERI ALI ZABLE;
- - al t er nat i vel y ( r epeat abl e r eads )
SET TRANSACTI ON READ ONLY
Oracle Lock Types
DML Locks: Row-Level Lock: Exclusive Table-Level Lock: Row exclusive
DDL Locks: DDL is not allowed if DML Lock was there and "ORA-00054: resource bus" will
be returned unless DDL_LOCK_TIMEOUT is defined in seconds (11g).
Explicit Table Locking: DDL requires Table exclusive DML lock. You can specify that a DDL
command wait for a specific length of time before it fails:
LOCK TABLE . . . I N l ockmode MODE [ NOWAI T | WAI T i nt eger ]
lockmode: [ ROW] SHARE, [ [ SHARE] ROW] EXCLUSI VE, SHARE UPDATE
integer in seconds
Latches: are internal mechanisms that protect shared data structures in the SGA.
Data dictionary locks: whenever the dictionary objects are being modified.
Page 163 Oracle DBA Code Examples

Distributed locks: used in a distributed database system or in RAC.
Internal locks: are used by Oracle to protect access to structures such as datafiles,
tablespaces, and rollback segments.
- - cur r ent l ocks i n t he DB
sel ect SI D,
DECODE( TO_CHAR( BLOCK) , ' 0' , ' Not - Bl ocki ng' , ' 1' , ' Bl ocki ng' ) I S_BLOCKI NG,
DECODE( TYPE, ' TM' , ' DML enqueue' , ' TX' , ' Tr ansact i on enqueue' , ' UL' , ' User
suppl i ed' , TYPE) LOCK_TYPE,
DECODE( TO_CHAR( LMODE) , ' 0' , ' None' , ' 1' , ' Nul l ' , ' 2' , ' Row- S ( SS) ' , ' 3' , ' Row- X
( SX) ' , ' 4' , ' Shar e ( S) ' , ' 5' , ' S/ Row- X ( SSX) ' , ' 6' , ' Excl usi ve ( X) ' ) HELD_LMODE,
DECODE( TO_CHAR( REQUEST) , ' 0' , ' None' , ' 1' , ' Nul l ' , ' 2' , ' Row- S ( SS) ' , ' 3' , ' Row- X
( SX) ' , ' 4' , ' Shar e ( S) ' , ' 5' , ' S/ Row- X ( SSX) ' , ' 6' , ' Excl usi ve ( X) ' ) REQUEST_LMODE
f r omv$l ock;

- - Or acl e 11g: t o al l ow DDL wai t f or l ock i nst ead or r et ur ni ng er r or
ALTER SESSI ON SET ddl _l ock_t i meout = 30;

- - expl i ci t t abl e l ocki ng ( t o acqui r e an excl usi ve l ock=no updat es)
- - t o r el ease t he l ock: ROLLBACK, COMMI T
l ock t abl e emp i n EXCLUSI VE mode nowai t ;
Identifying Blocking Sessions
- - or acl e suppl i ed scr i pt pr i nt i ng bl ocki ng sessi ons i n t r ee- l i ke vi ew
@$ORACLE_HOME/ r dbms/ admi n/ ut l l ockt . sql

sel ect SI D,
DECODE( TYPE, ' TM' , ' DML enqueue' , ' TX' , ' Tr ansact i on enqueue' , ' UL' , ' User
suppl i ed' , TYPE) LOCK_TYPE,
DECODE( TO_CHAR( LMODE) , ' 0' , ' None' , ' 1' , ' Nul l ' , ' 2' , ' Row- S ( SS) ' , ' 3' , ' Row- X
( SX) ' , ' 4' , ' Shar e ( S) ' , ' 5' , ' S/ Row- X ( SSX) ' , ' 6' , ' Excl usi ve ( X) ' ) HELD_LMODE,
DECODE( TO_CHAR( REQUEST) , ' 0' , ' None' , ' 1' , ' Nul l ' , ' 2' , ' Row- S ( SS) ' , ' 3' , ' Row- X
( SX) ' , ' 4' , ' Shar e ( S) ' , ' 5' , ' S/ Row- X ( SSX) ' , ' 6' , ' Excl usi ve ( X) ' ) REQUEST_LMODE
f r omv$l ock
wher e BLOCK=1;

SELECT si d, user name, bl ocki ng_sessi on bl ocki ng_si d
FROM V$SESSI ON WHERE bl ocki ng_sessi on_st at us=' VALI D' ;
Using Autonomous Transaction
The autonomous transactions give you the ability to commit or roll back the subprograms
changes independent of the main program.
- - wr i t e er r or s l og
CREATE OR REPLACE PROCEDURE er r or _l og
( er r or __msg i n var char 2, pr ocedur e_name I N VARCHAR2) I S
PRAGMA AUTONOMOUS_TRANSACTI ON;
BEGI N
I NSERT I NTO l og_t abl e ( er r or _msg, pr ocedur e_name)
VALUES ( er r or _msg, pr ocedur e_name) ) ;
COMMI T;
EXCEPTI ON
WHEN OTHERS THEN
ROLLBACK;
END er r or _l og;
/
Page 164 Oracle DBA Code Examples


- - usi ng DDL st at ement s i n t r i gger s
- - per f or mi ng an audi t of dat abase quer i es
- - per f or mi ng an audi t of and f ai l ed ( unaut hor i zed) dat abase act i vi t y
CREATE OR REPLACE TRI GGER aud_bef _t r i g
BEFORE I NSERT ON emp FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTI ON
BEGI N
I NSERT I NTO audi t _empl oyee VALUES (
: new. user name, ' bef or e i nser t ' , sysdat e) ;
COMMI T;
END;
/
Managing Long Transactions with Workspace Manager
Workspace Manager is by default installed when you create a database using DBCA but
not manually. To check, make sure WMSYS exists in DBA_USERS.
With Workspace Manager, you can maintain multiple versions of data, which you can keep
or discard as necessary.
Its benifits:
o To enable simultaneous read and write access to data during long transactions.
o To create multiple data scenarios for what-if analyses.
The original table will be renamed to tableName_LT, new table tableName_AUX will be
created. Users be default are placed in LIVE workspace.
Refresh: update the data in the refreshed workspace with the changes made in its parent
workspace.
Merge: update the parent workspace with the changes made to the merged workspace.
Reference: Application Developers Guide - Workspace Manager
- - shoul d r et ur n LI VE
sel ect dbms_wm. get wor kspace f r omdual ;

/ * go back i n t i me wi t hi n a wor kspace */
- - t he exampl e i s usi ng t he LI VE wor kspace

- - pr i vs
begi n
dbms_wm. gr ant Syst emPr i v (
' ACCESS_ANY_WORKSPACE, ' | |
' MERGE_ANY_WORKSPACE, ' | |
' CREATE_ANY_WORKSPACE, ' | |
' REMOVE_ANY_WORKSPACE, ' | |
' ROLLBACK_ANY_WORKSPACE' ,
' USER1' ,
' YES' ) ;
end;
/


conn user 1

Page 165 Oracle DBA Code Examples

cr eat e t abl e dept
( DEPTNO NUMBER( 3) PRI MARY KEY,
DNAME VARCHAR2( 14) )
/

cr eat e t abl e EMP
( EMPNO NUMBER( 4) PRI MARY KEY, - - PK i s mandat or y
ENAME VARCHAR2( 10) ,
DEPTNO NUMBER( 3) r ef er ences dept ( dept no) )
/


- - set ver si on enabl ed t abl es
- - VI EW_WO_OVERWRI TE = wi t hout Over wr i t e
begi n
dbms_wm.enableVersioning( ' EMP' , ' VI EW_WO_OVERWRI TE' ) ;
dbms_wm. enabl eVer si oni ng( ' DEPT' , ' VI EW_WO_OVERWRI TE' ) ;
end;
/

sel ect TABLE_NAME, STATE, HI STORY
f r omUSER_WM_VERSI ONED_TABLES
or der by TABLE_NAME ;


- - t est i ng dat a
- - Not e: r ows cannot be i nser t ed i f t he Wor kspace i sn' t
- - i n i t s l at est ver si on by DBMS_WM. Got oSavePoi nt ( ) ;
i nser t i nt o dept val ues ( 1, ' d1' ) ;
commi t ;
i nser t i nt o emp val ues ( 1, ' e1' , 1) ;
i nser t i nt o emp val ues ( 2, ' e2' , 1) ;
commi t ;

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - save cur r ent t i me
var dt _1 var char 2( 21)

begi n
sel ect t o_char ( sysdat e, ' dd. mm. yyyy hh24: mi : ss' ) i nt o : dt _1 f r omdual ;
end;
/

- - i nser t ext r a r ows
i nser t i nt o dept val ues( 2, ' d2' ) ;
commi t ;
i nser t i nt o emp val ues( 3, ' e3' , 2) ;
i nser t i nt o emp val ues( 4, ' e4' , 2) ;
commi t ;

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - r et ur n t o dt _1 t i me
begi n
dbms_wm.gotoDate( t o_dat e( : dt _1, ' dd. mm. yyyy hh24: mi : ss' ) ) ;
end;
Page 166 Oracle DBA Code Examples

/
commi t ;

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - di sabl e ver si oni ng
begi n
dbms_wm.disableVersioning( ' DEPT' ) ;
dbms_wm. di sabl eVer si oni ng( ' EMP' ) ;
end;
/

/ * Cr eat i ng Wor kspaces and Mer gi ng/ Ref r eshi ng Dat a */
- - pr i vs
begi n
dbms_wm. gr ant Syst emPr i v (
' ACCESS_ANY_WORKSPACE, ' | |
' MERGE_ANY_WORKSPACE, ' | |
' CREATE_ANY_WORKSPACE, ' | |
' REMOVE_ANY_WORKSPACE, ' | |
' ROLLBACK_ANY_WORKSPACE' ,
' USER1' ,
' YES' ) ;
end;
/


conn user 1

cr eat e t abl e dept
( DEPTNO NUMBER( 3) PRI MARY KEY,
DNAME VARCHAR2( 14) )
/

cr eat e t abl e EMP
( EMPNO NUMBER( 4) PRI MARY KEY, - - PK i s mandat or y
ENAME VARCHAR2( 10) ,
DEPTNO NUMBER( 3) r ef er ences dept ( dept no) )
/

i nser t i nt o dept val ues ( 1, ' d1' ) ;
commi t ;
i nser t i nt o emp val ues ( 1, ' e1' , 1) ;
i nser t i nt o emp val ues ( 2, ' e2' , 1) ;
commi t ;

- - set ver si on enabl ed t abl es
- - VI EW_WO_OVERWRI TE = wi t hout Over wr i t e
- - t hi s opt i on make WAREHOUSES_HI ST vi ew cont ai n
- - compl et e hi st or y i nf or mat i on about dat a changes
begi n
- - bot h t abl e must be ver si on enabl ed because t hey ar e l i nked
dbms_wm. enabl eVer si oni ng( ' DEPT, EMP' , ' VI EW_WO_OVERWRI TE' ) ;
end;
/

- - cr eat e wor kspaces
Page 167 Oracle DBA Code Examples

begi n
dbms_wm. createworkspace ( ' WS1' ) ;
dbms_wm. createworkspace ( ' WS2' ) ;
end;
/

sel ect wor kspace, par ent _wor kspace f r omuser _wor kspaces;

- - move l ogged on user t o WS1
begi n
dbms_wm. gotoworkspace( ' WS1' ) ;
end;
/

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - i nser t ext r a r ows
i nser t i nt o dept val ues( 2, ' d2' ) ;
commi t ;
i nser t i nt o emp val ues( 3, ' e3' , 2) ;
i nser t i nt o emp val ues( 4, ' e4' , 2) ;
commi t ;

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - go back t o Li ve wor kspace
begi n
dbms_wm. gotoworkspace( ' LI VE' ) ;
end;
/

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - change some dat a wi t hi n t he LI VE wor kspaces
i nser t i nt o dept val ues( 3, ' d3' ) ;
commi t ;
i nser t i nt o emp val ues( 5, ' e5' , 3) ;
i nser t i nt o emp val ues( 6, ' e6' , 3) ;
commi t ;


sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - move t o Wor kspace WS2
begi n
dbms_wm. gotoworkspace( ' WS2' ) ;
end;
/

- - you won' t see changes made i n t he LI VE wor kspace nor t he changes
- - made i n t he WS1 wor kspace.
sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

i nser t i nt o dept val ues( 4, ' d3' ) ;
commi t ;
i nser t i nt o emp val ues( 7, ' e7' , 4) ;
i nser t i nt o emp val ues( 8, ' e8' , 4) ;
Page 168 Oracle DBA Code Examples

commi t ;

- - REFRESH WS1
begi n
dbms_wm. refreshworkspace( ' WS1' ) ;
end;
/

- - move t o WS1
begi n
dbms_wm. gotoworkspace( ' WS1' ) ;
end;
/

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;

- - MERGE WS2
begi n
dbms_wm. mergeworkspace( ' WS2' ) ;
end;
/

- - ver i f y mer ge succeeded
begi n
dbms_wm. gotoworkspace( ' LI VE' ) ;
end;
/

sel ect * f r omemp, dept wher e emp. dept no=dept . dept no;


- - cl eani ng up
begi n
dbms_wm. di sabl ever si oni ng ( ' dept , emp' , t r ue) ;
end;
/

begi n
dbms_wm. got owor kspace ( ' LI VE' ) ;
dbms_wm. removeworkspace( ' WS1' ) ;
dbms_wm. r emovewor kspace( ' WS2' ) ;
end;
/

/ * Resol vi ng Conf l i ct s */
- - pr i vs
begi n
dbms_wm. gr ant Syst emPr i v (
' ACCESS_ANY_WORKSPACE, ' | |
' MERGE_ANY_WORKSPACE, ' | |
' CREATE_ANY_WORKSPACE, ' | |
' REMOVE_ANY_WORKSPACE, ' | |
' ROLLBACK_ANY_WORKSPACE' ,
' USER1' ,
' YES' ) ;
end;
/
Page 169 Oracle DBA Code Examples


conn user 1

cr eat e t abl e dept
( DEPTNO NUMBER( 3) PRI MARY KEY,
DNAME VARCHAR2( 14) )
/

cr eat e t abl e EMP
( EMPNO NUMBER( 4) PRI MARY KEY, - - PK i s mandat or y
ENAME VARCHAR2( 10) ,
DEPTNO NUMBER( 3) r ef er ences dept ( dept no) )
/

i nser t i nt o dept val ues ( 1, ' d1' ) ;
i nser t i nt o dept val ues ( 2, ' d2' ) ;
commi t ;
i nser t i nt o emp val ues ( 1, ' e1' , 1) ;
i nser t i nt o emp val ues ( 2, ' e2' , 1) ;
i nser t i nt o emp val ues ( 3, ' e3' , 2) ;
i nser t i nt o emp val ues ( 4, ' e4' , 2) ;
commi t ;

- - set ver si on enabl ed t abl es
begi n
dbms_wm. enabl eVer si oni ng( ' DEPT, EMP' , ' VI EW_WO_OVERWRI TE' ) ;
end;
/


- - cr eat e wor kspace and got o i t
begi n
dbms_wm. cr eat ewor kspace( ' WS1' ) ;
end;
/
begi n
dbms_wm. got owor kspace( ' WS1' ) ;
end;
/

- - make an updat e
updat e emp set ename=' i n WS1' wher e empno=1;
commi t ;

- - go back t o LI VE wor kspace
begi n
dbms_wm. got owor kspace( ' LI VE' ) ;
end;
/

- - make an updat e
updat e emp set ename=' i n LI VE' wher e empno=1;
commi t ;

- - t o see t he conf l i ct s i n xxx_CONF, you shoul d l eave LI VE wor kspace
begi n
dbms_wm. got owor kspace( ' WS1' ) ;
Page 170 Oracle DBA Code Examples

end;
/

col umn wm_wor kspace f or mat a16
sel ect * f r omEMP_CONF;


/ * To r esol ve t he conf l i ct */
- - ( 1) cal l dbms_wm. begi nr esol ve
begi n
dbms_wm. BeginResolve( ' WS1' ) ;
end;
/

- - ( 2) cal l dbms_wm. r esol veconf l i ct s
begi n
- - Keep updat e f r omPar ent ( LI VE)
dbms_wm. resolveconflicts(
wor kspace => ' WS1' , - - wor kspace t o check f or conf l i ct s wi t h ot her s
t abl e_name => ' EMP' ,
wher e_cl ause => ' empno=1' ,
keep => 'PARENT') ;
end;
/
- - OR
begi n
dbms_wm. resolveconflicts(
wor kspace => ' WS1' ,
t abl e_name => ' EMP' ,
wher e_cl ause => ' empno=1' ,
keep => 'CHILD') ;
end;
/
commi t ;

- - ( 3) cal l dbms_wm. commi t r esol ve.
begi n
dbms_wm. CommitResolve( ' WS1' ) ;
end;
/


- - l et ' s see i f we st i l l have a conf l i ct :
sel ect * f r omemp_conf ;

- - check t he dat a
sel ect * f r omemp ;

- - l et ' s see what dat a i n LI VE
begi n
dbms_wm. got owor kspace( ' LI VE' ) ;
end;
/

sel ect * f r omemp ;

- - i f dat a modi f i ed i n WS1 was chosen, mer ge i t wi t h LI VE
Page 171 Oracle DBA Code Examples

begi n
dbms_wm. mer gewor kspace( ' WS1' ) ;
end;
/

- - Cl eani ng up
begi n
dbms_wm. got owor kspace( ' LI VE' ) ;
dbms_wm. r emovewor kspace( ' WS1' ) ;
dbms_wm. di sabl ever si oni ng( ' emp, dept ' ) ;
end;
/
Page 172 Oracle DBA Code Examples

Repairing Corrupted Data
Options for Repairing Data Block Corruption
Drop and re-create an object after the corruption is detected.
If data block corruption is limited to a subset of rows, then another option is to rebuild the
table by selecting all data except for the corrupt rows.
Use the DBMS_REPAIR package to detect and repair corrupt blocks in tables and indexes.
Use Flashback Versions Query to query values of a row over a period of time. Then
arrange undo plan.
Block Media Recovery BMR
Detecting Corruptions Methods
DB_VERIFY utility
ANALYZE TABLE .. VALIDATE STRUCTURE [CASCADE]
Setting the initialization parameters: DB_BLOCK_CHECKING and DB_BLOCK_CHECKSUM
exp utility
DBMS_REPAIR
Data Recovery Advisor automatically runs after any corruption is detected and can alos
proactively invoked. See Using Data Recovery Advisor in RMAN.
Using dbv (DBVerify) Utility
The utility checks only for logical corruption below the HWM.
dbv f i l e=D: \ ORACLE\ ORADATA\ ORA10G\ USERS01. DBF bl ocksi ze=4096
dbv f i l e=exampl e01. dbf bl ocksi ze=8192
. .
exami ne " Tot al Pages Mar ked Cor r upt "
Setting the Initialization Parameters for Detecting Corruption
Verifying Block Integrity in Real Time: DB_BLOCK_CHECKING
Block checking typically causes 1% to 10% overhead, depending on workload.
You should set DB_BLOCK_CHECKING to FULL if the performance overhead is acceptable.
Possible Values:
o OFF: No block checking (except for SYSTEM) (default)
o LOW: Basic block header checks are performed after block contents change in memory
o MEDIUM: All LOW checks, as well as block checking for all non-index-organized table
blocks, are performed.
o FULL: All LOW and MEDIUM checks, as well as checks on index blocks, are performed.
al t er syst emset DB_BLOCK_CHECKI NG=FULL;
Page 173 Oracle DBA Code Examples

al t er sessi on set DB_BLOCK_CHECKI NG=LOW;
Verifying Block Integrity in Real Time: DB_BLOCK_CHECKSUM
Can prevent corruption caused by underlying I/O systems
FULL setting causes 4-5% overhead
DB_BLOCK_CHECKSUM = { OFF | FALSE | TYPI CAL | TRUE | FULL }
sel ect val ue f r omv$par amet er wher e upper ( name) =' DB_BLOCK_CHECKSUM' ;
Detecting lost write: DB_LOST_WRITE_PROTECT
A data block lost write occurs when an I/O subsystem acknowledges the completion of the
block write, while in fact the write did not occur in the persistent storage.
DB_LOST_WRI TE_PROTECT = { NONE | TYPI CAL | FULL }
Settubg the DB_ULTRA_SAFE Parameter (In Oracle 11g)
This parameter is used to set the effective values of the parameters: DB_BLOCK_CHECKI NG,
DB_LOST_WRI TE_PROTECT, DB_BLOCK_CHECKSUM. This parameter takes one of the following values:

of f
this value means any values you set for any of the three parameters will not be
overridden.

dat a onl y
The effective value of the parameters will be as follows:

Parameter Active Value


DB_BLOCK_CHECKI NG medi um


DB_LOST_WRI TE_PROTECT t ypi cal


DB_BLOCK_CHECKSUM.
f ul l

dat a and i ndex
The effective value of the parameters will be as follows:

Parameter Active Value


DB_BLOCK_CHECKI NG f ul l


DB_LOST_WRI TE_PROTECT t ypi cal


DB_BLOCK_CHECKSUM.
f ul l
Using ANALYZE Command
Validates the structure of a table or table partitions, and index or index partitions.
Does not mark blocks as soft corrupt; only reports them
When corruption detected, an error message returned.
ANALYZE TABLE t abl e_name VALI DATE STRUCTURE CASCADE;
Using EXP to Detect Corruption
exp utility reports an errors when it encounters corruption.
$ exp hr / hr t abl es=depar t ment s
About t o expor t speci f i ed t abl es vi a Convent i onal Pat h . . .
. . .
EXP- 00056: ORACLE er r or 1578 encount er ed
ORA- 01578: ORACLE dat a bl ock cor r upt ed ( f i l e # 5, bl ock # 51)
Page 174 Oracle DBA Code Examples

ORA- 01110: dat a f i l e 5: ' / u01/ app/ or acl e/ or adat a/ . . '
Using DBMS_REPAIR
DBMS_REPAIR Limitations and Restrictions
DBMS_REPAIR procedures have the following limitations:
o Tables with LOB datatypes, nested tables, and varrays are supported, but the out of line
columns are ignored.
o Clusters are supported in the SKIP_CORRUPT_BLOCKS and REBUILD_FREELISTS
procedures, but not in the CHECK_OBJECT procedure.
o Index-organized tables and LOB indexes are not supported.
o The DUMP_ORPHAN_KEYS procedure does not operate on bitmap indexes or function-
based indexes.
o The DUMP_ORPHAN_KEYS procedure processes keys that are no more than 3,950bytes
long.
Evaluate the Costs and Benefits of Using DBMS_REPAIR
Before using DBMS_REPAIR you must weigh the benefits of its use in relation to the
liabilities. You should also examine other options available for addressing corrupt objects.
Begin by answering the following questions:
What is the extent of the corruption?
To determine if there are corruptions and repair actions, execute the CHECK_OBJECT
procedure and query the repair table.
What other options are available for addressing block corruptions? Consider the
following:
If the data is available from another source, then drop, re-create, and
repopulate the object.
Issue the CREATE TABLE...AS SELECT statement from the corrupt table to
create a new one.
Ignore the corruption by excluding corrupt rows from SELECT statements.
Perform media recovery.
What logical corruptions or side effects are introduced when you use DBMS_REPAIR to
make an object usable? Can these be addressed? What is the effort required to do so?
It is possible that you do not have access to rows in blocks marked corrupt. However, a block
can be marked corrupt even if there are rows that you can validly access.
It is also possible that referential integrity constraints are broken when blocks are marked
corrupt. If this occurs, then disable and reenable the constraint; any inconsistencies are
reported. After fixing all problems, you should be able to reenable the constraint.
Logical corruption can occur when there are triggers defined on the table. For example, if rows
are reinserted, should insert triggers be fired or not? You can address these issues only if you
understand triggers and their use in your installation.
If indexes and tables are not synchronized, then execute the DUMP_ORPHAN_KEYS procedure
to obtain information from the keys that might be useful in rebuilding corrupted data. Then
issue the ALTER INDEX...REBUILD ONLINE statement to synchronize the table with its indexes.
If repair involves loss of data, can this data be retrieved?
You can retrieve data from the index when a data block is marked corrupt. The
DUMP_ORPHAN_KEYS procedure can help you retrieve this information.
Page 175 Oracle DBA Code Examples

Detect and Report Corruptions using DBMS_REPAIR
- - Repor t s cor r upt i ons and i dent i f i es t he associ at ed r epai r di r ect i ves
- - 1. bui l d t he r epai r t abl e
BEGI N
DBMS_REPAI R. ADMI N_TABLES (
t abl e_name => ' REPAI R_TABLE' ,
t abl e_t ype => DBMS_REPAI R. REPAI R_TABLE,
act i on => DBMS_REPAI R. CREATE_ACTI ON,
t abl espace => ' USERS' ) ;
END;
/

SELECT OBJ ECT_NAME, BLOCK_I D, CORRUPT_TYPE, MARKED_CORRUPT,
CORRUPT_DESCRI PTI ON, REPAI R_DESCRI PTI ON FROM REPAI R_TABLE;

- - 2. r epor t cor r upt i ons
SET SERVEROUTPUT ON
DECLARE
num_cor r upt I NT;
BEGI N
num_cor r upt : = 0;
DBMS_REPAI R. CHECK_OBJ ECT (
schema_name => ' HR' ,
obj ect _name => ' DEPARTMENTS' ,
r epai r _t abl e_name => ' REPAI R_TABLE' ,
cor r upt _count => num_cor r upt ) ;
END;
/

- - 3. make t he obj ect usabl e: i gnor i ng cor r upt i ons dur i ng t abl e and i ndex
scans
- - mar k cor r upt ed bl ocks
SET SERVEROUTPUT ON
DECLARE num_f i x I NT;
BEGI N
num_f i x : = 0;
DBMS_REPAI R. FI X_CORRUPT_BLOCKS (
schema_name => ' HR' ,
obj ect _name => ' DEPARTMENTS' ,
obj ect _t ype => DBMS_REPAI R. TABLE_OBJ ECT,
r epai r _t abl e_name => ' REPAI R_TABLE' ,
f i x_count => num_f i x) ;
END;
/

SELECT OBJ ECT_NAME, BLOCK_I D, MARKED_CORRUPT FROM REPAI R_TABLE;

- - ski p bl ocks mar ked as cor r upt ed
BEGI N
DBMS_REPAI R. SKI P_CORRUPT_BLOCKS (
schema_name => ' HR' ,
obj ect _name => ' DEPARTMENTS' ,
obj ect _t ype => DBMS_REPAI R. TABLE_OBJ ECT,
f l ags => DBMS_REPAI R. SKI P_FLAG) ; - - or NOSKI P_FLAG
END;
/

Page 176 Oracle DBA Code Examples

sel ect SKI P_CORRUPT f r omDBA_TABLES
wher e t abl e_name=' DEPARTMENTS' and woner =' HR' ;

- - 4. r epor t s on i ndex ent r i es t hat poi nt t o r ows i n cor r upt dat a bl ocks
- - may be usef ul f or r ebui l di ng l ost r ows
BEGI N
DBMS_REPAI R. ADMI N_TABLES (
t abl e_name => ' ORPHAN_KEY_TABLE' ,
t abl e_t ype => DBMS_REPAI R. ORPHAN_TABLE,
act i on => DBMS_REPAI R. CREATE_ACTI ON,
t abl espace => ' USERS' ) ;
END;
/

SET SERVEROUTPUT ON
DECLARE num_or phans I NT;
BEGI N
num_or phans : = 0;
DBMS_REPAI R. DUMP_ORPHAN_KEYS(
schema_name => ' SCOTT' ,
obj ect _name => ' PK_DEPT' ,
obj ect _t ype => DBMS_REPAI R. I NDEX_OBJ ECT,
r epai r _t abl e_name => ' REPAI R_TABLE' ,
or phan_t abl e_name => ' ORPHAN_KEY_TABLE' ,
key_count => num_or phans) ;
DBMS_OUTPUT. PUT_LI NE( ' Or phan Key Count : ' | | TO_CHAR( num_or phans) ) ;
END;
/
Page 177 Oracle DBA Code Examples

Managing Automated Database Maintenance Tasks
Predefined Automated Maintenance Tasks
Automatic Optimizer Statistics Collection
Automatic Segment Advisor
Automatic SQL Tuning Advisor
Predefined Maintenance Windows
Window Name Description
MONDAY_WINDOW Starts at 10 p.m. on Monday and ends at 2 a.m.
TUESDAY_WINDOW Starts at 10 p.m. on Tuesday and ends at 2 a.m.
WEDNESDAY_WINDOW Starts at 10 p.m. on Wednesday and ends at 2 a.m.
THURSDAY_WINDOW Starts at 10 p.m. on Thursday and ends at 2 a.m.
FRIDAY_WINDOW Starts at 10 p.m. on Friday and ends at 2 a.m.
SATURDAY_WINDOW Starts at 6 a.m. on Saturday and is 20 hours long.
SUNDAY_WINDOW Starts at 6 a.m. on Sunday and is 20 hours long.
Obtaining Information about Predefined Maintenance Tasks
- - cur r ent l y r unni ng Schedul er j obs cr eat ed f or aut omat ed mai nt enance t asks
sel ect
CLI ENT_NAME, J OB_NAME, J OB_SCHEDULER_STATUS, TASK_NAME, TASK_TARGET_TYPE, TASK_TARG
ET_NAME, TASK_PRI ORI TY, TASK_OPERATI ON
Fr omDBA_AUTOTASK_CLI ENT_J OB ;

- - aut omat ed mai nt enance t ask st at i st i cs over 7- day and 30- day per i ods
sel ect
CLI ENT_NAME, STATUS, CONSUMER_GROUP, CLI ENT_TAG, PRI ORI TY_OVERRI DE, ATTRI BUTES, WI ND
OW_GROUP, SERVI CE_NAME, RESOURCE_PERCENTAGE, USE_RESOURCE_ESTI MATES, MEAN_J OB_DURA
TI ON, MEAN_J OB_CPU, MEAN_J OB_ATTEMPTS, MEAN_I NCOMI NG_TASKS_7_DAYS, MEAN_I NCOMI NG_T
ASKS_30_DAYS, TOTAL_CPU_LAST_7_DAYS, TOTAL_CPU_LAST_30_DAYS, MAX_DURATI ON_LAST_7_
DAYS, MAX_DURATI ON_LAST_30_DAYS, WI NDOW_DURATI ON_LAST_7_DAYS, WI NDOW_DURATI ON_LAS
T_30_DAYS
Fr omDBA_AUTOTASK_CLI ENT

- - hi st or y of aut omat ed mai nt enance t ask j ob r uns
sel ect
CLI ENT_NAME, WI NDOW_NAME, WI NDOW_START_TI ME, WI NDOW_DURATI ON, J OB_NAME, J OB_STATUS,
J OB_START_TI ME, J OB_DURATI ON, J OB_ERROR, J OB_I NFO
f r omDBA_AUTOTASK_J OB_HI STORY
or der by WI NDOW_START_TI ME desc;

- - Li st s t he wi ndows t hat bel ong t o MAI NTENANCE_WI NDOW_GROUP
sel ect
WI NDOW_NAME, WI NDOW_NEXT_TI ME, WI NDOW_ACTI VE, AUTOTASK_STATUS, OPTI MI ZER_STATS, SEG
MENT_ADVI SOR, SQL_TUNE_ADVI SOR, HEALTH_MONI TOR
f r omDBA_AUTOTASK_WI NDOW_CLI ENTS;
Page 178 Oracle DBA Code Examples


- - per - wi ndow hi st or y of j ob execut i on count s f or each
- - aut omat ed mai nt enance t ask
sel ect
CLI ENT_NAME, WI NDOW_NAME, WI NDOW_START_TI ME, WI NDOW_DURATI ON, J OBS_CREATED, J OBS_ST
ARTED, J OBS_COMPLETED, WI NDOW_END_TI ME
f r omDBA_AUTOTASK_CLI ENT_HI STORY;
Enabling and Disabling Maintenance Tasks
sel ect CLI ENT_NAME, STATUS, CONSUMER_GROUP, CLI ENT_TAG, PRI ORI TY_OVERRI DE,
ATTRI BUTES, WI NDOW_GROUP, SERVI CE_NAME, RESOURCE_PERCENTAGE,
USE_RESOURCE_ESTI MATES, MEAN_J OB_DURATI ON, MEAN_J OB_CPU, MEAN_J OB_ATTEMPTS,
MEAN_I NCOMI NG_TASKS_7_DAYS, MEAN_I NCOMI NG_TASKS_30_DAYS, TOTAL_CPU_LAST_7_DAYS,
TOTAL_CPU_LAST_30_DAYS, MAX_DURATI ON_LAST_7_DAYS, MAX_DURATI ON_LAST_30_DAYS,
WI NDOW_DURATI ON_LAST_7_DAYS, WI NDOW_DURATI ON_LAST_30_DAYS
f r omDBA_AUTOTASK_CLIENT;

- - di sabl e
BEGI N
DBMS_AUTO_TASK_ADMIN.DISABLE(
cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => NULL,
wi ndow_name => NULL) ; - - nul l means al l wi dows
END;
/

- - enabl e
BEGI N
DBMS_AUTO_TASK_ADMIN.ENABLE(
cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => NULL,
wi ndow_name => NULL) ;
END;
/

- - enabl e or di sabl e ALL aut omat ed mai nt enance t asks f or ALL wi ndows
EXECUTE DBMS_AUTO_TASK_ADMI N. DI SABLE;
EXECUTE DBMS_AUTO_TASK_ADMI N. ENABLE;

- - Enabl i ng and Di sabl i ng Mai nt enance Tasks f or Speci f i c Mai nt enance Wi ndows
BEGI N
DBMS_AUTO_TASK_ADMI N. DI SABLE(
cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => NULL,
wi ndow_name => ' MONDAY_WI NDOW' ) ;
END;
/
Configuring Maintenance Windows
- - Modi f yi ng a Mai nt enance Wi ndow
- - see Usi ng Wi ndows SECTI ON
BEGI N
dbms_schedul er . di sabl e( name => ' SATURDAY_WI NDOW' ) ;
Page 179 Oracle DBA Code Examples

dbms_schedul er . set _at t r i but e(
name => ' SATURDAY_WI NDOW' ,
at t r i but e => ' DURATI ON' ,
val ue => numt odsi nt er val ( 4, ' hour ' ) ) ;
dbms_schedul er . enabl e(
name => ' SATURDAY_WI NDOW' ) ;
END;
/

- - Cr eat i ng a New Mai nt enance Wi ndow
BEGI N
DBMS_SCHEDULER. CREATE_WI NDOW(
wi ndow_name => ' EARLY_MORNI NG_WI NDOW' ,
dur at i on => numt odsi nt er val ( 1, ' hour ' ) ,
r esour ce_pl an => ' DEFAULT_MAI NTENANCE_PLAN' ,
r epeat _i nt er val => ' FREQ=DAI LY; BYHOUR=5; BYMI NUTE=0; BYSECOND=0' ) ;
dbms_schedul er . add_wi ndow_gr oup_member (
gr oup_name => ' MAI NTENANCE_WI NDOW_GROUP' ,
wi ndow_l i st => ' EARLY_MORNI NG_WI NDOW' ) ;
END;
/


- - Removi ng a Mai nt enance Wi ndow
- - wi ndow cont i nues t o exi st but no l onger r uns aut omat ed mai nt enance t asks.
- - Any ot her Schedul er j obs assi gned t o t hi s wi ndow cont i nue t o r un as
usual .
BEGI N
DBMS_SCHEDULER. REMOVE_WI NDOW_GROUP_MEMBER(
gr oup_name => ' MAI NTENANCE_WI NDOW_GROUP' ,
wi ndow_l i st => ' EARLY_MORNI NG_WI NDOW' ) ;
END;
/
Page 180 Oracle DBA Code Examples

Managing Resources
The steps:
1. Create a pending area.
2. Create a resource consumer group.
3. Create a resource plan.
4. Create a plan directive.
5. Validate the pending area.
6. Submit the pending area
- - r equi r ed pr i vs
exec DBMS_RESOURCE_MANAGER_PRI VS. GRANT_SYSTEM_PRI VI LEGE -
( GRANTEE_NAME => ' scot t ' , PRI VI LEGE_NAME => ' ADMI NI STER_RESOURCE_MANAGER' ) ;

- - cr eat i ng demo user s
conn syst em
cr eat e user u1 i dent i f i ed by u1 def aul t t abl espace user s;
cr eat e user u2 i dent i f i ed by u2 def aul t t abl espace user s;
cr eat e user u3 i dent i f i ed by u3 def aul t t abl espace user s;
gr ant r esour ce, connect t o u1;
gr ant r esour ce, connect t o u2;
gr ant r esour ce, connect t o u3;

CREATE TABLE U1. EMP AS SELECT * FROM HR. EMPLOYEES;
CREATE TABLE U2. EMP AS SELECT * FROM HR. EMPLOYEES;
CREATE TABLE U3. EMP AS SELECT * FROM HR. EMPLOYEES;


- - Cr eat i ng a Pendi ng Ar ea
exec dbms_r esour ce_manager . cr eat e_pendi ng_ar ea( ) ;

- - i f you make mi st akes
exec dbms_r esour ce_manager . cl ear _pendi ng_ar ea;

- - Resour ce Consumer Gr oups
- - pr e- conf i gur ed CGs:
- - DEFAULT_CONSUMER_GROUP, OTHER_GROUPS, SYS_GROUP, LOW_GROUP

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup (
CONSUMER_GROUP => ' PROGRAMMERS' ,
COMMENT => ' I T pr ogr ammer s' ,
CPU_MTH => ' ROUND- ROBI N' - - ot her possi bl e val ue i s RUN_TO_COMPLETI ON
) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup (
CONSUMER_GROUP => ' CLERKS' ,
COMMENT => ' Gr oup of Cl er ks' ,
CPU_MTH => ' ROUND- ROBI N'
) ;
Page 181 Oracle DBA Code Examples

end;
/


set l i nesi ze 100
col umn consumer _gr oup f or mat a15
col umn comment s f or mat a40
col umn cpu_met hod f or mat a11
sel ect DI STI NCT consumer _gr oup, cpu_met hod, comment s
f r omdba_r sr c_consumer _gr oups
or der by 1
/

- - Consumer Gr oup Mappi ng
- - Assi gni ng User Sessi ons t o Consumer Gr oups
begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => dbms_r esour ce_manager . or acl e_user , - - i t i s const ant ( no
quot s)
VALUE => ' U1' ,
CONSUMER_GROUP => ' PROGRAMMERS' ) ;
end;
/

begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => dbms_r esour ce_manager . or acl e_user , - - i t i s const ant ( no
quot s)
VALUE => ' U2' ,
CONSUMER_GROUP => ' CLERKS' ) ;
end;
/

- - possi bl e at t r i but es ar e:
CLI ENT_OS_USER
CLI ENT_PROGRAM
CLI ENT_MACHI NE
MODULE_NAME
MODULE_NAME_ACTI ON
ORACLE_USER
SERVI CE_NAME
SERVI CE_MODULE

- - / * f or demo onl y
begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => CLI ENT_OS_USER,
VALUE => ' gr aci ej ' ,
CONSUMER_GROUP => ' OLAP_GROUP' ) ;
end;
/
*/


- - Est abl i shi ng Mappi ng Pr i or i t i es
begi n
dbms_r esour ce_manager . SET_CONSUMER_GROUP_MAPPI NG_PRI (
Page 182 Oracle DBA Code Examples

EXPLI CI T => 1,
CLI ENT_OS_USER => 5,
CLI ENT_MACHI NE => 3,
CLI ENT_PROGRAM => 4,
ORACLE_USER => 2,
MODULE_NAME => 6,
MODULE_NAME_ACTI ON => 7,
SERVI CE_NAME => 8,
SERVI CE_MODULE => 9,
SERVI CE_MODULE_ACTI ON => 10) ;
end;
/
- - ERROR
BEGI N
DBMS_RESOURCE_MANAGER. SET_MAPPI NG_PRI ORI TY(
EXPLI CI T => 1, CLI ENT_MACHI NE => 2, MODULE_NAME => 3, ORACLE_USER => 4,
SERVI CE_NAME => 5, CLI ENT_OS_USER => 6, CLI ENT_PROGRAM => 7,
MODULE_NAME_ACTI ON => 8, SERVI CE_MODULE=>9, SERVI CE_MODULE_ACTI ON=>10) ;
END;
/


- - Resour ce Pl ans
- - Si mpl e Resour ce Pl an ( si ngl e- l evel r esour ce pl ans f or al l ocat i ng CPU)
/ * 10g ( depr ecat ed i n 11g) */
BEGI N
DBMS_RESOURCE_MANAGER. CREATE_SI MPLE_PLAN(
SI MPLE_PLAN => ' J OBS_PLAN' ,
CONSUMER_GROUP1 => ' PROGRAMMERS' ,
GROUP1_CPU => 75,
CONSUMER_GROUP2 => ' CLERKS' ,
GROUP2_CPU => 25) ;
end;
/
- - Not e: t he f i nal out put i s st i l l mul t i - l evel
begi n
DBMS_RESOURCE_MANAGER. DELETE_PLAN ( ' J OBS_PLAN' ) ;
end;
/

/ * 11g : t o i mpl ement t he f ol l owi ng pl an:
CG Level 1 Level 2 Level 3
SYS_GROUP 100%
MYGROUP1 80%
MYGROUP2 20%
OTHER_GROUPS 100%
*/
BEGI N
DBMS_RESOURCE_MANAGER. CREATE_SI MPLE_PLAN( SI MPLE_PLAN => ' SI MPLE_PLAN1' ,
CONSUMER_GROUP1 => ' MYGROUP1' , GROUP1_PERCENT => 80,
CONSUMER_GROUP2 => ' MYGROUP2' , GROUP2_PERCENT => 20) ;
END;

- - *****************
/ * Compl ex Pl an: CG, Resour ce P. , Res. Pl an Di r . */

- - cr eat e r esour ce pl an ( 10g)
Page 183 Oracle DBA Code Examples

begi n
dbms_r esour ce_manager . cr eat e_pl an(
PLAN => ' NW_PLAN' ,
COMMENT => ' New Wor l d Pl an' ,
CPU_MTH => ' EMPHASI S' ) ; - - or RATI O
end;
/

- - cr eat e r esour ce pl an 11g
- - MGMT_MTH f or speci f yi ng how much CPU each consumer gr oup or subpl an get s.
- - ' EMPHASI S' , t he def aul t met hod, i s f or si ngl e- l evel or mul t i l evel pl ans
- - t hat use per cent ages. ' RATI O' i s f or si ngl e- l evel pl ans t hat use r at i os
BEGI N
DBMS_RESOURCE_MANAGER. CREATE_PLAN(
PLAN => ' NW_PLAN' ,
COMMENT => ' New Wor l d Pl an' ,
MGMT_MTH => ' EMPHASI S' ,
SUB_PLAN => FALSE - - I f TRUE, t he pl an cannot be used as t he t op pl an
) ;
END;
/

sel ect DI STI NCT pl an, num_pl an_di r ect i ves, cpu_met hod
f r omdba_r sr c_pl ans;


- - Resour ce Pl an Di r ect i ves
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' New Wor l d Di r ect i ve' ,
GROUP_OR_SUBPLAN => ' PROGRAMMERS' ,
MAX_I DLE_TI ME => ' 120' ) ;
end;
/

- - ot her par amet er s ar e
CPU_Pn wher e n f r om1 t o 8 ( 10g)
MGMT_Pn wher e n f r om1 t o 8 ( 11g)
ACTI VE_SESS_POOL_P1
QUEUEI NG_P1
PARALLEL_DEGREE_LI MI T_P1
SWITCH_GROUP - - CG t o swi t ch t o, al so accept ' CANCEL_SQL' ' KI LL_SESSI ON'
SWI TCH_TI ME - - t i me ( i n CPU seconds) f or a cal l bef or e SWI TCH_GROUP i s t aken
SWI TCH_ESTI MATE - - TRUE or FALSE.
MAX_EST_EXEC_TI ME
UNDO_POOL - - i n KB
MAX_I DLE_TI ME
MAX_I DLE_BLOCKER_TI ME - - i n seconds
SWI TCH_TI ME_I N_CALL - - ( 10g)
SWI TCH_FOR_CALL - - ( 11g)
SWI TCH_I O_MEGABYTES - - ( 11g) max megabyt es of I / O by a sessi on
SWI TCH_I O_REQS - - ( 11g) max number of I / O r equest s
SWI TCH_FOR_CALL - - ( 11g) I f TRUE, a sessi on t hat was aut omat i cal l y swi t ched
- - t o anot her consumer gr oup ( accor di ng t o SWI TCH_TI ME,
- - SWI TCH_I O_MEGABYTES, or SWI TCH_I O_REQS) i s r et ur ned t o
- - i t s or i gi nal consumer gr oup when t he t op l evel cal l
Page 184 Oracle DBA Code Examples

- - compl et es.
- - exampl es i n 11g
BEGI N
DBMS_RESOURCE_MANAGER. CREATE_PLAN_DI RECTI VE (
PLAN => ' DAYTI ME' ,
GROUP_OR_SUBPLAN => ' REPORTI NG' ,
COMMENT => ' Repor t i ng gr oup' ,
MGMT_P1 => 15,
PARALLEL_DEGREE_LI MI T_P1 => 8,
ACTI VE_SESS_POOL_P1 => 4) ;
DBMS_RESOURCE_MANAGER. CREATE_PLAN_DI RECTI VE (
PLAN => ' DAYTI ME' ,
GROUP_OR_SUBPLAN => ' OTHER_GROUPS' ,
COMMENT => ' Thi s one i s r equi r ed' ,
MGMT_P1 => 10) ;
END;
/

- - Cr eat i ng Mul t i - Level Pl an Di r ect i ves
- - 10g
- - 11g: r epl ace CPU_Pn wi t h MGMT_Pn
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' SYSTEM USERS' ,
GROUP_OR_SUBPLAN => ' SYS_GROUP' ,
CPU_P1=> 100) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' Cl er ks CPU quot a' ,
GROUP_OR_SUBPLAN => ' CLERKS' ,
CPU_P2=> 30) ;
end;
/

BEGI N
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' Pr ogs CPU quot a' ,
GROUP_OR_SUBPLAN => ' PROGRAMMERS' ,
CPU_P2=> 70) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' OTHER_GROUPS CPU ALLOCATI ON' ,
GROUP_OR_SUBPLAN => ' OTHER_GROUPS' ,
CPU_P3=> 100) ;
end;
/

Page 185 Oracle DBA Code Examples


- - Cr eat i ng Aut omat i c Consumer Gr oup Swi t chi ng Di r ect i ves
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' LI MI T CLERKS EXECUTI ON TI ME' ,
GROUP_OR_SUBPLAN => ' CLERKS' ,
SWI TCH_GROUP => ' CANCEL_SQL' ,
SWI TCH_TI ME => 3600) ; - - one hour
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
COMMENT => ' SWI TCH PROGRAMMERS TEMPORARI LY' ,
GROUP_OR_SUBPLAN => ' PROGRAMMERS' ,
SWI TCH_TI ME_I N_CALL => 900,
SWI TCH_GROUP => ' LOW_GROUP' ,
SWI TCH_ESTI MATE => TRUE) ;
end;
/

- - Updat i ng Resour ce Pl an Di r ect i ves
begi n
dbms_r esour ce_manager . updat e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
GROUP_OR_SUBPLAN => ' PROGRAMMERS' ,
NEW_SWI TCH_ESTI MATE => FALSE) ;
end;
/

- - Del et i ng Resour ce Pl an Di r ect i ves
begi n
dbms_r esour ce_manager . del et e_pl an_di r ect i ve(
PLAN => ' NW_PLAN' ,
GROUP_OR_SUBPLAN => ' PROGRAMMERS' ) ;
end;
/


- - val i dat i ng Pendi ng Ar ea
exec dbms_r esour ce_manager . val i dat e_pendi ng_ar ea;

- - submi t t i ng Pendi ng Ar ea
exec dbms_r esour ce_manager . submi t _pendi ng_ar ea;



- - Enabl i ng t he Dat abase Resour ce Manager
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = NW_PLAN;

- - Swi t chi ng Resour ce Consumer Gr oups
- - f or a sessi on
begi n
dbms_r esour ce_manager . swi t ch_consumer _gr oup_f or _sess (
SESSI ON_I D => ' 145' ,
Page 186 Oracle DBA Code Examples

SESSI ON_SERI AL=> ' 49' ,
CONSUMER_GROUP => ' SYS_GROUP' ) ;
end;
/

- - f or al l sessi ons of a speci f i c user
begi n
dbms_r esour ce_manager . swi t ch_consumer _gr oup_f or _user (
USER => ' HR' ,
CONSUMER_GROUP => ' LOW_GROUP' ) ;
end;
/


- - swi t ch C Gr oups by cl i ent
- - r equi r e pr i v
begi n
dbms_r esour ce_manager _pr i vs. gr ant _swi t ch_consumer _gr oup(
GRANTEE_NAME => ' U1' , - - a r ol e name can be gi ven as wel l
CONSUMER_GROUP => ' PROGRAMMERS' ,
GRANT_OPTI ON => FALSE) ;
end;
/

- - Enabl i ng User s or Appl i cat i ons t o Manual l y Swi t ch Consumer Gr oups
DECLARE
or i gi nal _gr oup var char 2( 30) ;
dummy var char 2( 30) ;
BEGI N
DBMS_SESSI ON. SWI TCH_CURRENT_CONSUMER_GROUP(
' MARKETI NG' , or i gi nal _gr oup, FALSE) ;
- - execut e some SQL
nul l ;
DBMS_SESSI ON. SWI TCH_CURRENT_CONSUMER_GROUP(
or i gi nal _gr oup, dummy, FALSE) ;
END;
/

- - Gr ant i ng and Revoki ng t he Swi t ch Pr i vi l ege
BEGI N
- - GRANT_. . or REVOKE_. .
DBMS_RESOURCE_MANAGER_PRI VS. GRANT_SWI TCH_CONSUMER_GROUP(
GRANTEE_NAME => ' SCOTT' ,
CONSUMER_GROUP => ' OLTP' ,
GRANT_OPTI ON => f al se) ;
END;
/

- - Enabl i ng Or acl e Dat abase Resour ce Manager and Swi t chi ng Pl ans
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' mydb_pl an' ;
- - t he r esour ce pl an can be changed onl y by set t i ng
- - t he RESOURCE_MANAGER_PLAN i ni t i al i zat i on par amet er .
- - I t di sal l ows changes by Wi ndow openi ng.
- - Thi s r est r i ct i on can be l i f t ed by r er unni ng t he command wi t hout FORCE
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' FORCE: mydb_pl an' ;
- - di sabl e t he Resour ce Manager
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' ' ;
Page 187 Oracle DBA Code Examples


- - ****************
/ * Put t i ng i t al l t oget her Exampl e i mpl ement at i on */

OFF_HOURS_PLAN
SYS_GROUP 10
NI GHT_GROUP 5
REPORTS_GROUP 2
OTHER_GROUPS 1

DAY_PLAN
LEVEL1 SYS_GROUP 100%
LEVEL2 OLTP_PLAN 100%
LEVEL1 OLTP_GROUP 90% DREPORTS_GROUP 10%
LEVEL2 OTHERS_GROUPS 100%
LEVEL3 OTHERS_GROUPS 100%


exec dbms_r esour ce_manager . cr eat e_pendi ng_ar ea( ) ;

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup( ' OLTP_GROUP' , ' I ncomi ng or der s' ) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup( ' DREPORTS_GROUP' , ' DAYTI ME
REPORTS' ) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup( ' NI GHT_GROUP' , ' BULK LOADS' ) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_consumer _gr oup( ' REPORTS_GROUP' , ' OFF HOURS
REPORTS' ) ;
end;
/

- - Cr eat i ng t he Resour ce Pl ans
begi n
dbms_r esour ce_manager . cr eat e_pl an(
PLAN => ' DAY_PLAN' ,
COMMENT => ' NORMAL WORKI NG HOURS ' ) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an
( PLAN => ' OLTP_PLAN' , COMMENT => ' ORDER ENTRY SUB- PLAN' ) ;
end;
/


Page 188 Oracle DBA Code Examples

begi n
dbms_r esour ce_manager . cr eat e_pl an(
PLAN => ' OFF_HOURS_PLAN' ,
COMMENT => ' GOVERNS NON- WORKI NG HOURS' ,
CPU_MTH => ' RATI O' ) ;
end;
/

- - PLAN DI RECTI VE
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OFF_HOURS_PLAN' ,
GROUP_OR_SUBPLAN => ' SYS_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR SYS_GROUP' ,
CPU_P1 => 10) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OFF_HOURS_PLAN' ,
GROUP_OR_SUBPLAN => ' NI GHT_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR NI GHTLY J OBS' ,
CPU_P1 => 5) ;
end;
/


begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OFF_HOURS_PLAN' ,
GROUP_OR_SUBPLAN => ' REPORTS_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR NI GHTLY REPORTS' ,
CPU_P1 => 2) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OFF_HOURS_PLAN' ,
GROUP_OR_SUBPLAN => ' OTHER_GROUPS' ,
COMMENT => ' CPU ALLOCATI ON FOR OTHER_GROUPS' ,
CPU_P1 => 1) ;
end;
/


- - Cr eat i ng t he OLTP_PLAN Pl an Di r ect i ves
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OLTP_PLAN' ,
GROUP_OR_SUBPLAN => ' OLTP_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR OLTP USERS' ,
CPU_P1 => 90) ;
end;
/

Page 189 Oracle DBA Code Examples

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OLTP_PLAN' ,
GROUP_OR_SUBPLAN => ' DREPORTS_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR DAYTI ME REPORTI NG' ,
CPU_P1 => 10) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' OLTP_PLAN' ,
GROUP_OR_SUBPLAN => ' OTHER_GROUPS' ,
COMMENT => ' CPU ALLOCATI ON FOR OTHER_GROUPS' ,
CPU_P2 => 100) ;
end;
/


- - DAY_PLAN Pl an Di r ect i ves
begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' DAY_PLAN' ,
GROUP_OR_SUBPLAN => ' SYS_GROUP' ,
COMMENT => ' CPU ALLOCATI ON FOR SYS_GROUP' ,
CPU_P1 => 100) ;
end;
/


begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' DAY_PLAN' ,
GROUP_OR_SUBPLAN => ' OLTP_PLAN' ,
COMMENT => ' CPU ALLOCATI ON FOR OLTP_PLAN SUB- PLAN' ,
CPU_P2 => 100) ;
end;
/

begi n
dbms_r esour ce_manager . cr eat e_pl an_di r ect i ve(
PLAN => ' DAY_PLAN' ,
GROUP_OR_SUBPLAN => ' OTHER_GROUPS' ,
COMMENT => ' CPU ALLOCATI ON FOR OTHER_GROUPS' ,
CPU_P3 => 100) ;
end;
/

exec dbms_r esour ce_manager . val i dat e_pendi ng_ar ea;

exec dbms_r esour ce_manager . submi t _pendi ng_ar ea;


- - Enabl i ng t he Resour ce Pl ans
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' DAY_PLAN' ;
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' OFF_HOURS_PLAN' ;
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = ' ' ;
Page 190 Oracle DBA Code Examples



- - t est i ng

exec dbms_r esour ce_manager . cr eat e_pendi ng_ar ea( ) ;
begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => dbms_r esour ce_manager . or acl e_user ,
VALUE => ' U1' ,
CONSUMER_GROUP => ' NI GHT_GROUP' ) ;
end;
/

begi n
dbms_r esour ce_manager _pr i vs. gr ant _swi t ch_consumer _gr oup(
GRANTEE_NAME => ' U1' , - - a r ol e name can be gi ven as wel l
CONSUMER_GROUP => ' NI GHT_GROUP' ,
GRANT_OPTI ON => FALSE) ;
end;
/

begi n
dbms_r esour ce_manager _pr i vs. gr ant _swi t ch_consumer _gr oup(
GRANTEE_NAME => ' U2' ,
CONSUMER_GROUP => ' REPORTS_GROUP' ,
GRANT_OPTI ON => FALSE) ;
end;
/

begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => dbms_r esour ce_manager . or acl e_user , - - i t i s const ant ( no
quot s)
VALUE => ' U2' ,
CONSUMER_GROUP => ' REPORTS_GROUP' ) ;
end;
/

begi n
dbms_r esour ce_manager _pr i vs. gr ant _swi t ch_consumer _gr oup(
GRANTEE_NAME => ' U3' ,
CONSUMER_GROUP => ' OLTP_GROUP' ,
GRANT_OPTI ON => FALSE) ;
end;
/

begi n
dbms_r esour ce_manager . set _consumer _gr oup_mappi ng(
ATTRI BUTE => dbms_r esour ce_manager . or acl e_user ,
VALUE => ' U3' ,
CONSUMER_GROUP => ' OLTP_GROUP' ) ;
end;
/

exec dbms_r esour ce_manager . submi t _pendi ng_ar ea;

SET SERVEROUTPUT ON
Page 191 Oracle DBA Code Examples

DECLARE
D DATE : = SYSDATE;
DUMMY NUMBER;
BEGI N
DBMS_OUTPUT. PUT_LI NE( ' St ar t Ti me: ' | | t o_char ( D, ' hh24: mi : ss' ) ) ;
FOR I I N 1. . 3000000 LOOP
DUMMY : = SQRT( DBMS_RANDOM. VALUE( 1, 8100) ) ;
END LOOP;
DBMS_OUTPUT. PUT_LI NE( ' End Ti me: ' | | t o_char ( sysdat e, ' hh24: mi : ss' ) ) ;
DBMS_OUTPUT. PUT_LI NE( ' El apsed : ' | | r ound( ( sysdat e- d) *24*60*60, 2) | | ' s' ) ;
END;
/
Obtaining Information on Database Resource Manager
- - r esour ce consumer gr oups t hat exi st i n t he dat abase
sel ect
CONSUMER_GROUP_I D, CONSUMER_GROUP, CPU_METHOD, MGMT_METHOD, I NTERNAL_USE, COMMENTS
, CATEGORY, STATUS, MANDATORY
f r omDBA_RSRC_CONSUMER_GROUPS;

- - r esour ce di r ect i ves
sel ect
PLAN, GROUP_OR_SUBPLAN, TYPE, CPU_P1, CPU_P2, CPU_P3, CPU_P4, CPU_P5, CPU_P6, CPU_P7, C
PU_P8, MGMT_P1, MGMT_P2, MGMT_P3, MGMT_P4, MGMT_P5, MGMT_P6, MGMT_P7, MGMT_P8, ACTI VE_
SESS_POOL_P1, QUEUEI NG_P1, PARALLEL_DEGREE_LI MI T_P1, SWI TCH_GROUP, SWI TCH_FOR_CAL
L, SWI TCH_TI ME, SWI TCH_I O_MEGABYTES, SWI TCH_I O_REQS, SWI TCH_ESTI MATE, MAX_EST_EXEC
_TI ME, UNDO_POOL, MAX_I DLE_TI ME, MAX_I DLE_BLOCKER_TI ME, SWI TCH_TI ME_I N_CALL, COMME
NTS, STATUS, MANDATORY
f r omDBA_RSRC_PLAN_DI RECTI VES;

- - t he gr oups t o whi ch a user or r ol e i s al l owed t o bel ong or be swi t ched
sel ect GRANTEE, GRANTED_GROUP, GRANT_OPTI ON, I NI TI AL_GROUP
f r omDBA_RSRC_CONSUMER_GROUP_PRI VS

- - Vi ewi ng Pl an I nf or mat i on
sel ect
PLAN_I D, PLAN, NUM_PLAN_DI RECTI VES, CPU_METHOD, MGMT_METHOD, ACTI VE_SESS_POOL_MTH,
PARALLEL_DEGREE_LI MI T_MTH, QUEUEI NG_MTH, SUB_PLAN, COMMENTS, STATUS, MANDATORY
f r omDBA_RSRC_PLANS

- - Vi ewi ng Cur r ent Consumer Gr oups f or Sessi ons
SELECT SI D, SERI AL#, USERNAME, RESOURCE_CONSUMER_GROUP FROM V$SESSI ON;

- - di spl ay t he cur r ent t op l evel pl an and al l of i t s descendent subpl ans
SELECT NAME, I S_TOP_PLAN FROM V$RSRC_PLAN;

- - mappi ng pai r s f or al l of t he sessi on at t r i but es
sel ect ATTRI BUTE, VALUE, CONSUMER_GROUP, STATUS
f r omDBA_RSRC_GROUP_MAPPI NGS;

- - cur r ent mappi ng pr i or i t y of each at t r i but e
sel ect ATTRI BUTE, PRI ORI TY, STATUS
f r omDBA_RSRC_MAPPI NG_PRI ORI TY;

- - hi st or i cal i nf or mat i on on r esour ce pl an act i vat i on: snapshot s of
V$RSRC_PLAN_HI STORY
Page 192 Oracle DBA Code Examples

sel ect
SNAP_I D, DBI D, I NSTANCE_NUMBER, SEQUENCE#, START_TI ME, END_TI ME, PLAN_I D, PLAN_NAME,
CPU_MANAGED
f r omDBA_HI ST_RSRC_PLAN;

- - hi st or i cal st at i st i cal i nf or mat i on on consumer gr oups. snapshot s of :
V$RSRC_CONS_GROUP_HI STORY
sel ect
SNAP_I D, DBI D, I NSTANCE_NUMBER, SEQUENCE#, CONSUMER_GROUP_I D, CONSUMER_GROUP_NAME,
REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CONSUMED_CPU_TI ME, YI ELDS, ACTI VE_SESS_LI MI T_H
I T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI ME, SWI TCHES_I N_I O_M
EGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS, SWI TCHES_OUT_I O_RE
QUESTS, SQL_CANCELED, ACTI VE_SESS_KI LLED, I DLE_SESS_KI LLED, I DLE_BLKR_SESS_KI LLED
, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI TS, SMALL_READ_MEGA
BYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI TE_MEGABYTES, SMALL_
READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARGE_WRI TE_REQUESTS
f r omDBA_HI ST_RSRC_CONSUMER_GROUP ;

- - f or each consumer gr oup i n t he pl an showi ng t he cumul at i ve st at i st i cs f or
t he consumer gr oup.
- - sequence# as as i n V$RSRC_PLAN_HI STORY
sel ect
SEQUENCE#, I D, NAME, REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CONSUMED_CPU_TI ME, YI ELDS, A
CTI VE_SESS_LI MI T_HI T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI M
E, SWI TCHES_I N_I O_MEGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS,
SWI TCHES_OUT_I O_REQUESTS, SQL_CANCELED, ACTI VE_SESS_KI LLED, I DLE_SESS_KI LLED, I DL
E_BLKR_SESS_KI LLED, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI
TS, SMALL_READ_MEGABYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI T
E_MEGABYTES, SMALL_READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARG
E_WRI TE_REQUESTS
f r omV$RSRC_CONS_GROUP_HI STORY;

sel ect
SEQUENCE#, I D, NAME, REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CONSUMED_CPU_TI ME, YI ELDS, A
CTI VE_SESS_LI MI T_HI T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI M
E, SWI TCHES_I N_I O_MEGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS,
SWI TCHES_OUT_I O_REQUESTS, SQL_CANCELED, ACTI VE_SESS_KI LLED, I DLE_SESS_KI LLED, I DL
E_BLKR_SESS_KI LLED, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI
TS, SMALL_READ_MEGABYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI T
E_MEGABYTES, SMALL_READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARG
E_WRI TE_REQUESTS
f r omV$RSRC_CONS_GROUP_HI STORY;

- - r esour ce usage and st at s dat a on cur r ent l y act i ve r esour ce consumer gr oups
sel ect
I D, NAME, ACTI VE_SESSI ONS, EXECUTI ON_WAI TERS, REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CO
NSUMED_CPU_TI ME, YI ELDS, QUEUE_LENGTH, CURRENT_UNDO_CONSUMPTI ON, ACTI VE_SESSI ON_L
I MI T_HI T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI ME, SWI TCHES_I
N_I O_MEGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS, SWI TCHES_OUT
_I O_REQUESTS, SQL_CANCELED, ACTI VE_SESSI ONS_KI LLED, I DLE_SESSI ONS_KI LLED, I DLE_BL
KR_SESSI ONS_KI LLED, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI
TS, SMALL_READ_MEGABYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI T
E_MEGABYTES, SMALL_READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARG
E_WRI TE_REQUESTS, V$RSRC_CONSUMER_GROUP
FROM v$r sr c_consumer _gr oup;

- - a hi st or y of r esour ces consumed and cumul at i ve CPU wai t t i me ( due t o
r esour ce management ) per consumer gr oup f or t he past mi nut e
sel ect
BEGI N_TI ME, END_TI ME, I NTSI ZE_CSEC, SEQUENCE#, CONSUMER_GROUP_I D, CONSUMER_GROUP_N
AME, CPU_CONSUMED_TI ME, CPU_WAI T_TI ME, I O_REQUESTS, I O_MEGABYTES
Page 193 Oracle DBA Code Examples

f r omV$RSRCMGRMETRI C;

- - when r esour ce pl ans wer e enabl ed or di sabl ed on t he i nst ance
SELECT sequence# seq, name pl an_name,
t o_char ( st ar t _t i me, ' DD- MON- YY HH24: MM' ) st ar t _t i me,
t o_char ( end_t i me, ' DD- MON- YY HH24: MM' ) end_t i me, wi ndow_name
FROM v$r sr c_pl an_hi st or y;

- - how t he sessi on has been af f ect ed by t he Resour ce Manager
sel ect
SI D, CURRENT_CONSUMER_GROUP_I D, ORI G_CONSUMER_GROUP_I D, MAPPI NG_ATTRI BUTE, MAPPED
_CONSUMER_GROUP, STATE, ACTI VE, CURRENT_I DLE_TI ME, CURRENT_CPU_WAI T_TI ME, CPU_WAI T
_TI ME, CURRENT_CPU_WAI TS, CPU_WAI TS, CURRENT_CONSUMED_CPU_TI ME, CONSUMED_CPU_TI ME
, CURRENT_ACTI VE_TI ME, ACTI VE_TI ME, CURRENT_QUEUED_TI ME, QUEUED_TI ME, CURRENT_YI EL
DS, YI ELDS, CURRENT_UNDO_CONSUMPTI ON, MAX_UNDO_CONSUMPTI ON, SQL_CANCELED, QUEUE_TI
ME_OUTS, ESTI MATED_EXECUTI ON_LI MI T_HI T, CURRENT_I O_SERVI CE_TI ME, I O_SERVI CE_TI ME
, CURRENT_I O_SERVI CE_WAI TS, I O_SERVI CE_WAI TS, CURRENT_SMALL_READ_MEGABYTES, SMALL
_READ_MEGABYTES, CURRENT_LARGE_READ_MEGABYTES, LARGE_READ_MEGABYTES, CURRENT_SMA
LL_WRI TE_MEGABYTES, SMALL_WRI TE_MEGABYTES, CURRENT_LARGE_WRI TE_MEGABYTES, LARGE_
WRI TE_MEGABYTES, CURRENT_SMALL_READ_REQUESTS, SMALL_READ_REQUESTS, CURRENT_SMALL
_WRI TE_REQUESTS, SMALL_WRI TE_REQUESTS, CURRENT_LARGE_READ_REQUESTS, LARGE_READ_R
EQUESTS, CURRENT_LARGE_WRI TE_REQUESTS, LARGE_WRI TE_REQUESTS
f r omv$r sr c_sessi on_i nf o;
Monitoring Oracle Database Resource Manager
- - di spl ay t he cur r ent l y act i ve r esour ce pl an and i t s subpl ans.
SELECT name, i s_t op_pl an FROM v$r sr c_pl an;

- - r esour ce usage and st at s dat a on cur r ent l y act i ve r esour ce consumer gr oups
sel ect
I D, NAME, ACTI VE_SESSI ONS, EXECUTI ON_WAI TERS, REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CO
NSUMED_CPU_TI ME, YI ELDS, QUEUE_LENGTH, CURRENT_UNDO_CONSUMPTI ON, ACTI VE_SESSI ON_L
I MI T_HI T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI ME, SWI TCHES_I
N_I O_MEGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS, SWI TCHES_OUT
_I O_REQUESTS, SQL_CANCELED, ACTI VE_SESSI ONS_KI LLED, I DLE_SESSI ONS_KI LLED, I DLE_BL
KR_SESSI ONS_KI LLED, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI
TS, SMALL_READ_MEGABYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI T
E_MEGABYTES, SMALL_READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARG
E_WRI TE_REQUESTS, V$RSRC_CONSUMER_GROUP
FROM v$r sr c_consumer _gr oup;

- - how t he sessi on has been af f ect ed by t he Resour ce Manager
sel ect
SI D, CURRENT_CONSUMER_GROUP_I D, ORI G_CONSUMER_GROUP_I D, MAPPI NG_ATTRI BUTE, MAPPED
_CONSUMER_GROUP, STATE, ACTI VE, CURRENT_I DLE_TI ME, CURRENT_CPU_WAI T_TI ME, CPU_WAI T
_TI ME, CURRENT_CPU_WAI TS, CPU_WAI TS, CURRENT_CONSUMED_CPU_TI ME, CONSUMED_CPU_TI ME
, CURRENT_ACTI VE_TI ME, ACTI VE_TI ME, CURRENT_QUEUED_TI ME, QUEUED_TI ME, CURRENT_YI EL
DS, YI ELDS, CURRENT_UNDO_CONSUMPTI ON, MAX_UNDO_CONSUMPTI ON, SQL_CANCELED, QUEUE_TI
ME_OUTS, ESTI MATED_EXECUTI ON_LI MI T_HI T, CURRENT_I O_SERVI CE_TI ME, I O_SERVI CE_TI ME
, CURRENT_I O_SERVI CE_WAI TS, I O_SERVI CE_WAI TS, CURRENT_SMALL_READ_MEGABYTES, SMALL
_READ_MEGABYTES, CURRENT_LARGE_READ_MEGABYTES, LARGE_READ_MEGABYTES, CURRENT_SMA
LL_WRI TE_MEGABYTES, SMALL_WRI TE_MEGABYTES, CURRENT_LARGE_WRI TE_MEGABYTES, LARGE_
WRI TE_MEGABYTES, CURRENT_SMALL_READ_REQUESTS, SMALL_READ_REQUESTS, CURRENT_SMALL
_WRI TE_REQUESTS, SMALL_WRI TE_REQUESTS, CURRENT_LARGE_READ_REQUESTS, LARGE_READ_R
EQUESTS, CURRENT_LARGE_WRI TE_REQUESTS, LARGE_WRI TE_REQUESTS
f r omv$r sr c_sessi on_i nf o;

SELECT se. si d sess_i d, co. name consumer _gr oup,
Page 194 Oracle DBA Code Examples

se. st at e, se. consumed_cpu_t i me cpu_t i me, se. cpu_wai t _t i me, se. queued_t i me
FROM v$r sr c_sessi on_i nf o se, v$r sr c_consumer _gr oup co
WHERE se. cur r ent _consumer _gr oup_i d = co. i d;

- - when r esour ce pl ans wer e enabl ed or di sabl ed on t he i nst ance
SELECT sequence# seq, name pl an_name,
t o_char ( st ar t _t i me, ' DD- MON- YY HH24: MM' ) st ar t _t i me,
t o_char ( end_t i me, ' DD- MON- YY HH24: MM' ) end_t i me, wi ndow_name
FROM v$r sr c_pl an_hi st or y;

- - how r esour ces wer e shar ed among t he consumer gr oups over t i me
sel ect sequence# seq, name, cpu_wai t _t i me, cpu_wai t s,
consumed_cpu_t i me f r omV$RSRC_CONS_GROUP_HI STORY;

- - sequence# as as i n V$RSRC_PLAN_HI STORY
sel ect
SEQUENCE#, I D, NAME, REQUESTS, CPU_WAI T_TI ME, CPU_WAI TS, CONSUMED_CPU_TI ME, YI ELDS, A
CTI VE_SESS_LI MI T_HI T, UNDO_LI MI T_HI T, SWI TCHES_I N_CPU_TI ME, SWI TCHES_OUT_CPU_TI M
E, SWI TCHES_I N_I O_MEGABYTES, SWI TCHES_OUT_I O_MEGABYTES, SWI TCHES_I N_I O_REQUESTS,
SWI TCHES_OUT_I O_REQUESTS, SQL_CANCELED, ACTI VE_SESS_KI LLED, I DLE_SESS_KI LLED, I DL
E_BLKR_SESS_KI LLED, QUEUED_TI ME, QUEUE_TI ME_OUTS, I O_SERVI CE_TI ME, I O_SERVI CE_WAI
TS, SMALL_READ_MEGABYTES, SMALL_WRI TE_MEGABYTES, LARGE_READ_MEGABYTES, LARGE_WRI T
E_MEGABYTES, SMALL_READ_REQUESTS, SMALL_WRI TE_REQUESTS, LARGE_READ_REQUESTS, LARG
E_WRI TE_REQUESTS
f r omV$RSRC_CONS_GROUP_HI STORY;
Page 195 Oracle DBA Code Examples

Using Oracle Scheduler
Using Jobs
For Batch Files in Windows:
o The OracleJobscheduler service must exist in a running state
o The user who runs this service should have the Logon as batch job privilege
o .bat file cannot be run directly, but should be called as an argument of cmd.exe
-- creating a job
begi n
dbms_schedul er . cr eat e_j ob (
j ob_name => ' Cal c_J ob' ,
j ob_t ype => ' st or ed_pr ocedur e' , - - st or ed_pr ocedur e, pl sql _bl ock,
execut abl e, chai n
j ob_act i on => ' POPULATE_DEPT_SALS' ,
st ar t _dat e => SYSDATE, - - or t o_dat e( ' 01- 08- 2006 17: 46' , ' dd- mm- yyyy
hh24: mi ' ) ,
r epeat _i nt er val => ' FREQ=MI NUTELY; I NTERVAL=2' ,
comment s => ' Annual Depar t ment Sal ar i es' ) ;
end;
/

BEGI N
DBMS_SCHEDULER. CREATE_J OB (
j ob_name => ' updat e_sal es' ,
j ob_t ype => ' STORED_PROCEDURE' ,
j ob_act i on => ' OPS. SALES_PKG. UPDATE_SALES_SUMMARY' ,
st ar t _dat e => ' 28- APR- 03 07. 00. 00 PM Aust r al i a/ Sydney' ,
r epeat _i nt er val => ' FREQ=DAI LY; I NTERVAL=2' , / * ever y ot her day */
end_dat e => ' 20- NOV- 04 07. 00. 00 PM Aust r al i a/ Sydney' ,
j ob_cl ass => ' bat ch_updat e_j obs' ,
comment s => ' My new j ob' ) ;
END;
/

- - f or SYSTEM=TRUE: aut omat i cal l y cr eat ed by Or acl e j obs
sel ect
OWNER, J OB_NAME, J OB_SUBNAME, J OB_STYLE, J OB_CREATOR, CLI ENT_I D, GLOBAL_UI D, PROGRAM
_OWNER, PROGRAM_NAME, J OB_TYPE, J OB_ACTI ON, NUMBER_OF_ARGUMENTS, SCHEDULE_OWNER, SC
HEDULE_NAME, SCHEDULE_TYPE, START_DATE, REPEAT_I NTERVAL, EVENT_QUEUE_OWNER, EVENT_
QUEUE_NAME, EVENT_QUEUE_AGENT, EVENT_CONDI TI ON, EVENT_RULE, END_DATE, J OB_CLASS, EN
ABLED, AUTO_DROP, RESTARTABLE, STATE, J OB_PRI ORI TY, RUN_COUNT, MAX_RUNS, FAI LURE_COU
NT, MAX_FAI LURES, RETRY_COUNT, LAST_START_DATE, LAST_RUN_DURATI ON, NEXT_RUN_DATE, S
CHEDULE_LI MI T, MAX_RUN_DURATI ON, LOGGI NG_LEVEL, STOP_ON_WI NDOW_CLOSE, I NSTANCE_ST
I CKI NESS, RAI SE_EVENTS, SYSTEM, J OB_WEI GHT, NLS_ENV, SOURCE, DESTI NATI ON, CREDENTI AL
_OWNER, CREDENTI AL_NAME, I NSTANCE_I D, DEFERRED_DROP, COMMENTS, FLAGS
f r omdba_SCHEDULER_J OBS;


- - Set t i ng Repeat I nt er val s
FREQ YEARLY, MONTHLY, WEEKLY, DAI LY, HOURLY, MI NUTELY, and SECONDLY.
I NTERVAL a number of maxi mum999
BYMONTH 1- 12 1, 4, 6
BYYEARDAY any posi t i ve or negat i ve number
BYMONTHDAY any posi t i ve or negat i ve number ( eg - 1 l ast day of t he mont h)
Page 196 Oracle DBA Code Examples

BYDAY ( MON, TUE, and so on) can be pr ef i xed wi t h a number - 1FRI
BYHOUR 0- 23
BYMI NUTE 0- 59
BYSECOND 0- 59

Ever y Monday FREQ=WEEKLY; BYDAY=MON;
Ever y ot her Monday FREQ=WEEKLY; BYDAY=MON; I NTERVAL=2;
Last day of each mont h FREQ=MONTHLY; BYMONTHDAY=- 1;
Ever y J anuar y 7 FREQ=YEARLY; BYMONTH=J AN; BYMONTHDAY=7;
Second Wednesday of FREQ=MONTHLY; BYDAY=2WED;
each mont h
Ever y hour FREQ=HOURLY;
Ever y 4 hour s FREQ=HOURLY; I NTERVAL=4;
Hour l y on t he f i r st FREQ=HOURLY; BYMONTHDAY=1;
day of each mont h
15t h day of ever y ot her FREQ=MONTHLY; BYMONTHDAY=15; I NTERVAL=2
mont h
- - MORE EXAMPLES
Dai l y at 4, 5, and 6PM: FREQ=DAI LY; BYHOUR=16, 17, 18;
15t h day of ever y ot her mont h: FREQ=MONTHLY; I NTERVAL=2; BYMONTHDAY=15;
29t h day of ever y mont h: FREQ=MONTHLY; BYMONTHDAY=29;
Second Wednesday of each mont h: FREQ=MONTHLY; BYDAY=2WED;
Last Fr i day of t he year : FREQ=YEARLY; BYDAY=- 1FRI ;
Ever y 50 hour s: FREQ=HOURLY; I NTERVAL=50;
Last day of ever y ot her mont h: FREQ=MONTHLY; I NTERVAL=2; BYMONTHDAY=- 1;
Hour l y f or t he f i r st t hr ee days of ever y mont h: FREQ=HOURLY;
BYMONTHDAY=1, 2, 3;
Last wor kday of ever y mont h ( assumi ng t hat wor kdays ar e Monday t hr ough
Fr i day) :
FREQ=MONTHLY; BYDAY=MON, TUE, WED, THU, FRI ; BYSETPOS=- 1
Last wor kday of ever y mont h, excl udi ng company hol i days. ( Thi s exampl e
r ef er ences an exi st i ng named schedul e cal l ed Company_Hol i days) :
FREQ=MONTHLY; BYDAY=MON, TUE, WED, THU, FRI ; EXCLUDE=Company_Hol i days;
BYSETPOS=- 1
Noon ever y Fr i day and on company hol i days:
FREQ=YEARLY; BYDAY=FRI ; BYHOUR=12; I NCLUDE=Company_Hol i days

- - Test i ng Repeat I nt er val s
set ser ver out put on
DECLARE
st ar t _dat e TI MESTAMP;
r et ur n_dat e_af t er TI MESTAMP;
next _r un_dat e TI MESTAMP;
BEGI N
st ar t _dat e : = t o_t i mest amp( ' 01- 01- 2006 00: 00: 00' , ' DD- MM- YYYY HH24: MI : SS' ) ;
DBMS_SCHEDULER. EVALUATE_CALENDAR_STRI NG(
CALENDAR_STRI NG => ' FREQ=MONTHLY; I NTERVAL=1' ,
START_DATE => st ar t _dat e,
RETURN_DATE_AFTER => nul l ,
NEXT_RUN_DATE => next _r un_dat e) ;
DBMS_OUTPUT. PUT_LI NE( ' next _r un_dat e: ' | | next _r un_dat e) ;
END;
/

al t er sessi on set nl s_dat e_l anguage=Engl i sh
/

DECLARE
Page 197 Oracle DBA Code Examples

st ar t _dat e TI MESTAMP;
r et ur n_dat e_af t er TI MESTAMP;
next _r un_dat e TI MESTAMP;
BEGI N
st ar t _dat e : = t o_t i mest amp( ' 10- 10- 2004 10: 00: 00' , ' DD- MM- YYYY HH24: MI : SS' ) ;
r et ur n_dat e_af t er : = st ar t _dat e;
FOR i I N 1. . 10 LOOP
DBMS_SCHEDULER. EVALUATE_CALENDAR_STRI NG(
' FREQ=MONTHLY; I NTERVAL=2; BYMONTHDAY=15' ,
st ar t _dat e, r et ur n_dat e_af t er , next _r un_dat e) ;
DBMS_OUTPUT. PUT_LI NE( ' Next Run Dat e: ' | | t o_char ( next _r un_dat e, ' Dy dd- MM-
RR HH24: MI ' ) ) ;
r et ur n_dat e_af t er : = next _r un_dat e;
END LOOP;
END;
/


-- Creating a Set of Regular Jobs
DECLARE
newj ob sys. j ob;
newj obar r sys. j ob_ar r ay;
BEGI N
- - Cr eat e an ar r ay of J OB obj ect t ypes
newj obar r : = sys. j ob_ar r ay( ) ;
- - Al l ocat e suf f i ci ent space i n t he ar r ay
newj obar r . ext end( 5) ;
- - Add def i ni t i ons f or 5 j obs
FOR i I N 1. . 5 LOOP
- - Cr eat e a J OB obj ect t ype
newj ob : = sys. j ob( j ob_name => ' TESTJ OB' | | t o_char ( i ) ,
j ob_st yl e => ' REGULAR' ,
j ob_t empl at e => ' PROG1' ,
r epeat _i nt er val => ' FREQ=MI NUTELY; I NTERVAL_15' ,
st ar t _dat e => syst i mest amp + i nt er val ' 600' second,
max_r uns => 2,
aut o_dr op => FALSE,
enabl ed _> TRUE ) ;
- - Add i t t o t he ar r ay
newj obar r ( i ) : = newj ob;
END LOOP;
- - Cal l CREATE_J OBS t o cr eat e j obs i n one t r ansact i on
DBMS_SCHEDULER. CREATE_J OBS( newj obar r , ' TRANSACTI ONAL' ) ;
END;
/


-- Creating a Set of Lightweight Jobs
DECLARE
newj ob sys. j ob;
newj obar r sys. j ob_ar r ay;
BEGI N
newj obar r : = sys. j ob_ar r ay( ) ;
newj obar r . ext end( 5) ;
FOR i I N 1. . 5 LOOP
newj ob : = sys. j ob( j ob_name => ' l wj ob_' | | t o_char ( i ) ,
j ob_st yl e => ' LI GHTWEI GHT' ,
Page 198 Oracle DBA Code Examples

j ob_t empl at e => ' PROG1' ,
r epeat _i nt er val => ' FREQ=MI NUTELY; I NTERVAL=15' ,
st ar t _dat e => syst i mest amp + i nt er val ' 10' second,
enabl ed => TRUE) ;
newj obar r ( i ) : = newj ob;
end l oop;
DBMS_SCHEDULER. CREATE_J OBS( newj obar r , ' TRANSACTI ONAL' ) ;
END;
/


-- Creating Jobs Using a Named Program
BEGI N
DBMS_SCHEDULER. CREATE_J OB (
j ob_name => ' my_new_j ob1' ,
pr ogr am_name => ' my_saved_pr ogr am' ,
r epeat _i nt er val => ' FREQ=DAI LY; BYHOUR=12' ,
comment s => ' Dai l y at noon' ) ;
END;
/


-- Creating Jobs Using a Named Schedule
BEGI N
DBMS_SCHEDULER. CREATE_J OB (
j ob_name => ' my_new_j ob2' ,
j ob_t ype => ' PLSQL_BLOCK' ,
j ob_act i on => ' BEGI N SALES_PKG. UPDATE_SALES_SUMMARY; END; ' ,
schedul e_name => ' my_saved_schedul e' ) ;
END;
/

-- Creating Jobs Using a Named Program and Schedule
BEGI N
DBMS_SCHEDULER. CREATE_J OB (
j ob_name => ' my_new_j ob3' ,
pr ogr am_name => ' my_saved_pr ogr am1' ,
schedul e_name => ' my_saved_schedul e1' ) ;
END;
/

-- Creating Remote External Jobs
- - Not e: check sect i on " Enabl i ng and Di sabl i ng Remot e Ext er nal J obs"
BEGI N
DBMS_SCHEDULER. CREATE_J OB(
j ob_name => ' CLEANLOGS' ,
j ob_t ype => ' EXECUTABLE' ,
j ob_act i on => ' / home/ l ogowner / cl eanl ogs' ,
r epeat _i nt er val => ' FREQ=DAI LY; BYHOUR=23' ,
enabl ed => FALSE) ;
DBMS_SCHEDULER. SET_ATTRI BUTE( ' CLEANLOGS' , ' cr edent i al _name' , ' LOGOWNER' ) ;
DBMS_SCHEDULER. SET_ATTRI BUTE( ' CLEANLOGS' , ' dest i nat i on' , ' app455: 12345' ) ;
DBMS_SCHEDULER. ENABLE( ' CLEANLOGS' ) ;
END;
/
- - i n mul t i pl e host s
decl ar e
Page 199 Oracle DBA Code Examples

j ob_pr ef i x var char 2( 30) : = ' r emot e_' ;
j ob_name var char 2( 30) ;
dest i nat i ons dbms_ut i l i t y. l name_ar r ay;
begi n
dest i nat i ons( 1) : = ' host 1: 1234' ;
dest i nat i ons( 2) : = ' host 2: 1234' ;
dest i nat i ons( 3) : = ' host 3: 1234' ;
dest i nat i ons( 4) : = ' host 4: 1234' ;
f or i i n 1. . dest i nat i ons. LAST l oop
j ob_name : = dbms_schedul er . gener at e_j ob_name( j ob_pr ef i x) ;
dbms_schedul er . cr eat e_j ob( j ob_name,
j ob_t ype=>' execut abl e' ,
j ob_act i on=>' / u01/ app/ ext _backup' ,
number _of _ar gument s=>0,
enabl ed=>f al se) ;
dbms_schedul er . set _at t r i but e( j ob_name, ' dest i nat i on' , dest i nat i ons( i ) ) ;
dbms_schedul er . set _at t r i but e( j ob_name, ' cr edent i al _name' , ' r emot e_cr ed' ) ;
dbms_schedul er . enabl e( j ob_name) ;
end l oop;
end;
/

- - r un a shel l scr i pt t hat uses SQL*Pl us t o submi t t he st at ement s
- - ext er nal aut hent i cat i on i s assumed
#! / bi n/ sh
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 11. 1. 0/ db_1
expor t ORACLE_SI D=or cl
expor t LD_LI BRARY_PATH=$LD_LI BRARY_PATH: $ORACLE_HOME/ l i b
# The f ol l owi ng command assumes ext er nal aut hent i cat i on
$ORACLE_HOME/ bi n/ sql pl us / << EOF
set ser ver out put on;
sel ect * f r omdual ;
EXI T;
EOF

-- Copying Jobs
- - t he new j ob i s cr eat ed di sabl ed
begi n
DBMS_SCHEDULER. COPY_J OB (
ol d_j ob =>' MY_OLD_J OB' ,
new_j ob =>' MY_NEW_J OB' ) ;
end;


-- altering jobs
- - val ue par amt er may be {VARCHAR2| TI MESTAMP WI TH TI MEZONE|
- - PLS_I NTEGER| BOOLEAN| I NTERVAL DAY TO SECOND}
begi n
DBMS_SCHEDULER. SET_ATTRI BUTE (
name =>' FULL_BAKCUP' ,
at t r i but e =>' aut o_dr op' , - - see possi bl e val ues bel ow
val ue =>TRUE) ;
end;
/

- - at t r i but e possi bl e val ues f or J OBS
aut o_dr op
Page 200 Oracle DBA Code Examples

comment s
cr edent i al _name cr edent i al t o use when r unni ng an ext er nal j ob
dat abase_r ol e Or acl e Dat a Guar d ' PRI MARY' or ' LOGI CAL STANDBY'
dest i nat i on host and por t on whi ch t o r un a r emot e ext er nal j ob
end_dat e i f no val ue, t he j ob r epeat s f or ever
event _spec
f ol l ow_def aul t _t i mezone
i nst ance_i d
i nst ance_st i cki ness TRUE or FALSE
j ob_act i on
j ob_cl ass
j ob_pr i or i t y t he or der i n whi ch j obs f r omt hat cl ass ar e pi cked up
by
t he j ob coor di nat or . 1( f i r st ) - 5, 3 def aul t
j ob_t ype ' PLSQL_BLOCK' , ' STORED_PROCEDURE' , ' EXECUTABLE' , ' CHAI N'
j ob_wei ght i n par al l el t echnol ogy, 1- 100
l oggi ng_l evel DBMS_SCHEDULER. LOGGI NG_OFF, LOGGI NG_FAI LED_RUNS,
LOGGI NG_RUNS, LOGGI NG_FULL
max_f ai l ur es number of t i mes a j ob can f ai l on consecut i ve
max_r un_dur at i on ( I NTERVAL DAY TO SECOND) i f j ob dur at i on exceeds t hi s
val ue, t he Schedul er r ai ses an event of t ype
J OB_OVER_MAX_DUR. I t i s t hen up t o your event handl er
t o
deci de whet her or not t o al l ow t he j ob t o cont i nue
max_r uns t he maxi mumnumber of consecut i ve schedul ed
r uns. di sabl ed t hen.
number _of _ar gument s The number of ar gument s i f t he pr ogr ami s i nl i ned
par al l el _i nst ances TRUE or FALSE
pr ogr am_name
r ai se_event s j ob_st ar t ed CONSTANT PLS_I NTEGER : = 1
j ob_succeeded CONSTANT PLS_I NTEGER : = 2
j ob_f ai l ed CONSTANT PLS_I NTEGER : =4
j ob_br oken CONSTANT PLS_I NTEGER : =8
j ob_compl et ed CONSTANT PLS_I NTEGER : =16
j ob_st opped CONSTANT PLS_I NTEGER : =32
j ob_sch_l i m_r eached CONSTANT PLS_I NTEGER : =64
j ob_di sabl ed CONSTANT PLS_I NTEGER : =128
j ob_chai n_st al l ed CONSTANT PLS_I NTEGER : =256
j ob_al l _event s CONSTANT PLS_I NTEGER : = 511
j ob_r un_compl et ed CONSTANT PLS_I NTEGER : =
j ob_succeeded + j ob_f ai l ed + j ob_st opped
r epeat _i nt er val Ei t her a PL/ SQL f unct i on r et ur ni ng t he next dat e
and t i me on whi ch t o r un, or cal endar i ng synt ax
expr essi on
r est ar t abl e
schedul e_l i mi t t i me l i mi t af t er whi ch t he j ob wi l l not st ar t
( f r om1 mi nut e t o 99 days )
schedul e_name
st ar t _dat e
st op_on_wi ndow_cl ose


-- Setting Multiple Job Attributes for a Set of Regular Jobs
DECLARE
newat t r sys. j obat t r ;
newat t r ar r sys. j obat t r _ar r ay;
j number ;
BEGI N
Page 201 Oracle DBA Code Examples

- - Cr eat e new J OBATTR ar r ay
newat t r ar r : = sys. j obat t r _ar r ay( ) ;
- - Al l ocat e enough space i n t he ar r ay
newat t r ar r . ext end( 20) ;
j : = 1;
FOR i I N 1. . 5 LOOP
- - Cr eat e and i ni t i al i ze a J OBATTR obj ect t ype
newat t r : = sys. j obat t r ( j ob_name => ' TESTJ OB' | | t o_char ( i ) ,
at t r _name => ' MAX_FAI LURES' ,
at t r _val ue => 5) ;
- - Add i t t o t he ar r ay.
newat t r ar r ( j ) : = newat t r ;
j : = j + 1;
newat t r : = sys. j obat t r ( j ob_name => ' TESTJ OB' | | t o_char ( i ) ,
at t r _name => ' COMMENTS' ,
at t r _val ue => ' Bogus comment ' ) ;
newat t r ar r ( j ) : = newat t r ;
j : = j + 1;
newat t r : = sys. j obat t r ( j ob_name => ' TESTJ OB' | | t o_char ( i ) ,
at t r _name => ' END_DATE' ,
at t r _val ue => syst i mest amp + i nt er val ' 24' hour ) ;
newat t r ar r ( j ) : = newat t r ;
j : = j + 1;
newat t r : = sys. j obat t r ( j ob_name => ' TESTJ OB' | | t o_char ( i ) ,
at t r _name => ' SCHEDULE_LI MI T' ,
at t r _val ue => i nt er val ' 1' hour ) ;
newat t r ar r ( j ) : = newat t r ;
j : = j + 1;
END LOOP;
- - Cal l SET_J OB_ATTRI BUTES t o set al l 20 set at t r i but es i n one t r ansact i on
DBMS_SCHEDULER. SET_J OB_ATTRI BUTES( newat t r ar r , ' TRANSACTI ONAL' ) ;
END;
/

-- stopping a job
- - st op j ob j ob1 and al l j obs i n t he j ob cl ass dw_j obs.
BEGI N
DBMS_SCHEDULER. STOP_J OB( ' j ob1, sys. dw_j obs' ) ;
END;
/


-- Dropping Jobs
BEGI N
DBMS_SCHEDULER. DROP_J OB ( ' j ob1, j ob3, sys. j obcl ass1, sys. j obcl ass2' ) ;
END;
/

-- Disabling Jobs
BEGI N
DBMS_SCHEDULER. DI SABLE( ' j ob1, j ob2, j ob3, sys. j obcl ass1' ) ;
END;
/

-- Enabling Jobs
BEGI N
DBMS_SCHEDULER. ENABLE ( ' j ob1, j ob2, j ob3, sys. j obcl ass1' ) ;
Page 202 Oracle DBA Code Examples

END;
/
Using Programs
- - Cr eat i ng Pr ogr ams
BEGI N
DBMS_SCHEDULER. CREATE_PROGRAM (
pr ogr am_name => ' my_pr ogr am1' ,
pr ogr am_act i on => ' / usr / l ocal / bi n/ dat e' ,
pr ogr am_t ype => ' EXECUTABLE' ,
comment s => ' My comment s her e' ) ;
END;
/

BEGI N
DBMS_SCHEDULER. CREATE_PROGRAM (
pr ogr am_name => ' oe. my_pr ogr am1' ,
pr ogr am_t ype => ' PLSQL_BLOCK' ,
pr ogr am_act i on => ' BEGI N DBMS_STATS. GATHER_TABLE_STATS( ' ' oe' ' , ' ' sal es' ' ) ;
END; ' ,
number _of _ar gument s => 0,
enabl ed => TRUE,
comment s => ' My comment s her e' ) ;
END;
/
SELECT PROGRAM_NAME FROM DBA_SCHEDULER_PROGRAMS
WHERE PROGRAM_NAME = ' MY_PROGRAM1' ;

- - Def i ni ng Pr ogr amAr gument s
BEGI N
DBMS_SCHEDULER. DEFI NE_PROGRAM_ARGUMENT (
pr ogr am_name => ' oper at i ons_r epor t i ng' ,
ar gument _posi t i on => 2,
ar gument _name => ' end_dat e' ,
ar gument _t ype => ' VARCHAR2' ,
def aul t _val ue => ' 12- DEC- 03' ) ;
END;
/

- - dr oppi ng a pr ogr amar gument
BEGI N
DBMS_SCHEDULER. DROP_PROGRAM_ARGUMENT (
pr ogr am_name => ' oper at i ons_r epor t i ng' ,
ar gument _posi t i on => 2) ;
DBMS_SCHEDULER. DROP_PROGRAM_ARGUMENT (
pr ogr am_name => ' oper at i ons_r epor t i ng' ,
ar gument _name => ' end_dat e' ) ;
END;
/

- - set s t he val ue ( non- Nul l ) of an ar gument of t he associ at ed PROGRAM OBJ ECT
f or a j ob
- - by ar gument posi t i on
BEGI N
DBMS_SCHEDULER. SET_J OB_ARGUMENT_VALUE(
Page 203 Oracle DBA Code Examples

j ob_name => ' ops_r epor t s' ,
ar gument _posi t i on => 2,
ar gument _val ue => ' 12- DEC- 03' ) ;
END;
/
- - by ar gument name
BEGI N
DBMS_SCHEDULER. SET_J OB_ARGUMENT_VALUE(
j ob_name => ' ops_r epor t s' ,
ar gument _name => ' END_DATE' ,
ar gument _val ue => ' 12- DEC- 03' ) ;
END;
/
- - set t i ng an ar gument t o NULL val ue
BEGI N
DBMS_SCHEDULER. SET_ATTRI BUTE_NULL (
j ob_name => ' ops_r epor t s' ,
ar gument _name => ' END_DATE' ) ;
END;
/

- - Dr oppi ng Pr ogr ams
BEGI N
DBMS_SCHEDULER. DROP_PROGRAM( ' pr ogr am1, pr ogr am2, pr ogr am3' ) ;
END;
/

- - Di sabl i ng Pr ogr ams
BEGI N
DBMS_SCHEDULER. DI SABLE (
name => ' ops_r epor t s' ,
f or ce =>FALSE, - - t he def aul t
commi t _semant i cs => ' STOP_ON_FI RST_ERROR' ) ; - - TRANSACTI ONAL or
ABSORB_ERRORS
END;
/

- - Enabl i ng Pr ogr ams
BEGI N
DBMS_SCHEDULER. ENABLE( ' pr ogr am1, pr ogr am2, pr ogr am3' ) ;
END;
/
Using Schedules
- - Cr eat i ng Schedul es
BEGI N
DBMS_SCHEDULER. CREATE_SCHEDULE (
schedul e_name => ' my_st at s_schedul e' ,
st ar t _dat e => SYSTI MESTAMP,
end_dat e => SYSTI MESTAMP + I NTERVAL ' 30' day,
r epeat _i nt er val => ' FREQ=HOURLY; I NTERVAL=4' ,
comment s => ' Ever y 4 hour s' ) ;
END;
/

Page 204 Oracle DBA Code Examples

- - al t er i ng schedul es
BEGI N
dbms_schedul er . set _at t r i but e(
name => ' my_st at s_schedul e' ,
at t r i but e => ' REPEAT_I NTERVAL' ,
val ue => ' FREQ=HOURLY; I NTERVAL=2' ) ;
END;
/
at t r i but e:
comment s
end_dat e
event _spec
r epeat _i nt er val
sour ce The host name t hat t he dat abase i s r unni ng on
st ar t _dat e

- - Dr oppi ng Schedul es
BEGI N
DBMS_SCHEDULER. DROP_SCHEDULE (
schedul e_name => ' my_st at s_schedul e' ,
f or ce => FALSE) ; - - DEFAULT
END;
/
Using Job Classes
Jobs classes provide a way to group jobs for resource allocation and prioritization, and a
way to easily assign a set of attribute values to member jobs.
- - Cr eat i ng J ob Cl asses
BEGI N
DBMS_SCHEDULER. CREATE_J OB_CLASS (
j ob_cl ass_name => ' f i nance_j obs_cl ass' ,
r esour ce_consumer _gr oup => ' f i nance_gr oup' ) ;
END;
/

BEGI N
dbms_schedul er . set _at t r i but e(
name => ' f i nance_j obs_cl ass' ,
at t r i but e => ' l oggi ng_l evel ' ,
val ue => DBMS_SCHEDULER. LOGGI NG_FAI LED_RUNS) ;
END;
/
ATTRI BUTE:
comment s
l oggi ng_l evel DBMS_SCHEDULER. LOGGI NG_OFF, LOGGI NG_FAI LED_RUNS,
LOGGI NG_RUNS, LOGGI NG_FULL
r esour ce_consumer _gr oup j obs r un under t hi s r esour ce consumer gr oup
ser vi ce

- - Dr oppi ng J ob Cl asses
BEGI N
DBMS_SCHEDULER. DROP_J OB_CLASS( ' j obcl ass1, j obcl ass2, j obcl ass3' ) ;
END;
/
Page 205 Oracle DBA Code Examples

Using Windows
- - Cr eat i ng Wi ndows
begi n
dbms_schedul er . cr eat e_wi ndow (
wi ndow_name => ' WORK_HOURS_WI NDOW' ,
r esour ce_pl an => ' DAY_PLAN' ,
st ar t _dat e => SYSTI MESTAMP, - - al so schedul e_name can be used
r epeat _i nt er val => ' FREQ=DAI LY; BYHOUR=8' ,
dur at i on => I NTERVAL ' 10' HOUR,
wi ndow_pr i or i t y => ' HI GH' ) ; - - or LOW
end;
/

BEGI N
DBMS_SCHEDULER. CREATE_WI NDOW(
wi ndow_name => ' my_wi ndow1' ,
r esour ce_pl an => ' my_r es_pl an1' ,
st ar t _dat e => ' 15- J UL- 03 1. 00. 00AM US/ Paci f i c' ,
r epeat _i nt er val => ' FREQ=DAI LY' ,
end_dat e => ' 15- SEP- 03 1. 00. 00AM US/ Paci f i c' ,
dur at i on => i nt er val ' 80' MI NUTE,
comment s => ' Thi s i s my f i r st wi ndow' ) ;
END;
/

BEGI N
DBMS_SCHEDULER. CREATE_WI NDOW(
wi ndow_name => ' my_wi ndow2' ,
schedul e_name => ' my_st at s_schedul e' ,
r esour ce_pl an => ' my_r esour cepl an1' ,
dur at i on => i nt er val ' 60' mi nut e,
comment s => ' My wi ndow' ) ;
END;
/
SELECT WI NDOW_NAME FROM DBA_SCHEDULER_WI NDOWS WHERE WI NDOW_NAME =
' MY_WI NDOW1' ;

- - Al t er i ng Wi ndows
BEGI N
dbms_schedul er . set _at t r i but e(
name => ' MYWI NDOW' ,
at t r i but e => ' wi ndow_pr i or i t y' ,
val ue => ' LOW' ) ;
END;
/
ATTRI BUTE:
comment s
dur at i on
end_dat e
r epeat _i nt er val
r esour ce_pl an
schedul e_name
st ar t _dat e
wi ndow_pr i or i t y

- - openi nng a wi ndow
begi n
Page 206 Oracle DBA Code Examples

dbms_schedul er . open_wi ndow (
wi ndow_name => ' WORK_HOURS_WI NDOW' ,
dur at i on => I NTERVAL ' 20' MI NUTE) ;
end;
/

- - cl osi ng a wi ndow
begi n
dbms_schedul er . cl ose_wi ndow ( ' WORK_HOURS_WI NDOW' ) ;
end;
/

- - dr oppi ng a wi ndow
BEGI N
DBMS_SCHEDULER. DROP_WI NDOW( ' wi ndow1, wi ndow2,
wi ndow3, wi ndowgr oup1, wi ndowgr oup2' ) ;
END;
/

- - Di sabl i ng Wi ndows
BEGI N
DBMS_SCHEDULER. DI SABLE ( ' sys. wi ndow1, sys. wi ndow2,
sys. wi ndow3, sys. wi ndowgr oup1, sys. wi ndowgr oup2' ) ;
END;
/

- - Enabl i ng Wi ndows
BEGI N
DBMS_SCHEDULER. ENABLE ( ' sys. wi ndow1, sys. wi ndow2, sys. wi ndow3' ) ;
END;
/

- - Wi ndow Loggi ng
col umn l og_i d f or mat a3
col umn wi ndow_name f or mat a20
col umn oper at i on f or mat a8
sel ect t r i m( l og_i d) l og_i d, t r unc( l og_dat e) l og_dat e,
wi ndow_name, oper at i on
f r omdba_schedul er _wi ndow_l og
/

col umn act ual _dur at i on f or mat a20
sel ect t r i m( l og_i d) l og_i d, t r unc( l og_dat e) l og_dat e,
wi ndow_name, act ual _dur at i on
f r omdba_schedul er _wi ndow_det ai l s
or der by 2 desc
/

begi n
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE( ' LOG_HI STORY' , ' 60' ) ;
end;
/
Using Window Groups
I f you cr eat e a wi ndow gr oup, add wi ndows t o i t , and t hen name t hi s wi ndow
Page 207 Oracle DBA Code Examples

gr oup i n a j ob' s schedul e_name at t r i but e, t he j ob r uns dur i ng al l t he wi ndows
i n t he wi ndow gr oup.
- - Cr eat i ng Wi ndow Gr oups
BEGI N
DBMS_SCHEDULER. CREATE_WI NDOW_GROUP (
gr oup_name => ' downt i me' ,
wi ndow_l i st => ' weekni ght s, weekends' ) ;
END;
/

- - Dr oppi ng Wi ndow Gr oups
BEGI N
DBMS_SCHEDULER. DROP_WI NDOW_GROUP( ' wi ndowgr oup1, wi ndowgr oup2' ) ;
END;
/

- - Addi ng a Member t o a Wi ndow Gr oup
BEGI N
DBMS_SCHEDULER. ADD_WI NDOW_GROUP_MEMBER ( ' wi ndow_gr oup1' , ' wi ndow1,
wi ndow2' ) ;
END;
/

- - Dr oppi ng a Member f r oma Wi ndow Gr oup
BEGI N
DBMS_SCHEDULER. REMOVE_WI NDOW_GROUP_MEMBER( ' wi ndow_gr oup1' ,
' wi ndow1, wi ndow2' ) ;
END;
/

- - Enabl i ng a Wi ndow Gr oup
BEGI N
DBMS_SCHEDULER. ENABLE( ' sys. wi ndowgr oup1' , ' sys. wi ndowgr oup2,
sys. wi ndowgr oup3' ) ;
END;
/

- - Di sabl i ng a Wi ndow Gr oup: but not t he member s
BEGI N
DBMS_SCHEDULER. DI SABLE( ' sys. wi ndowgr oup1, sys. wi ndowgr oup2' ) ;
END;
/
Monitoring Job State with Email Notifications
You can configure a job to send e-mail notifications when it changes state.
/ * Conf i gur at i on */
CONN / AS SYSDBA
BEGI N
- - def i ne t he SMTP ser ver
DBMS_SCHEDULER. set _schedul er _at t r i but e( ' emai l _ser ver ' , ' smt p. mydomai n. com: 25' ) ;

- - opt i onal l y def i ne def aul t sender addr ess, whi ch
- - i s used i f t he sender par amet er i s not speci f i ed
DBMS_SCHEDULER. set _schedul er _at t r i but e( ' emai l _sender ' , ' i nf o@mydomai n. com' ) ;
END;
/
Page 208 Oracle DBA Code Examples



- - t o enabl e/ di sabl e encr ypt i on i s f or t he SMTP ser ver connect i on
- - onl y ( 11. 2. 0. 2)
- - possi bl e val ues: NONE, SSL_TLS, STARTTLS
exec DBMS_SCHEDULER. set _schedul er _at t r i but e( ' emai l _ser ver _encr ypt i on' , ' SSL_TLS' )


- - Aut hent i cat i on
- - I f t he SMTP ser ver r equi r es aut hent i cat i on, t hen t he Schedul er uses t he
- - user name and passwor d st or ed i n t he speci f i ed cr edent i al obj ect
- - def aul t NULL
exec dbms_schedul er . cr eat e_cr edent i al ( ' hr cr edent i al ' , ' hr ' , ' hr passwor d' ) ;
exec DBMS_SCHEDULER. set _schedul er _at t r i but e( ' emai l _ser ver _cr edent i al ' , ' hr cr edent i al ' )



/ * Usi ng Emai l Not i f i cat i on */
- - You cal l ADD_J OB_EMAI L_NOTI FI CATI ON once f or each di f f er ent set of not i f i cat i ons
- - t hat you want t o conf i gur e f or a j ob.

- - associ at e an emai l not i f i cat i on wi t h t he j ob
- - usi ng t he def aul t subj ect and body
BEGI N
DBMS_SCHEDULER. add_j ob_emai l _not i f i cat i on (
j ob_name => ' emai l _not i f i cat i on_j ob' ,
r eci pi ent s => ' i nf o@ahmedbar aka. com' ,
event s => ' j ob_st ar t ed, j ob_succeeded' ) ;
END;

- - subj ect and body speci f i ed:
BEGI N
DBMS_SCHEDULER. ADD_J OB_EMAI L_NOTI FI CATI ON (
j ob_name => ' emai l _not i f i cat i on_j ob' ,
r eci pi ent s => ' i nf o@ahmedbar aka. com, al i ssa@mydomai n. com' ,
sender => ' do_not _r epl y@exampl e. com' ,
subj ect => ' Schedul er J ob Not i f i cat i on- %j ob_owner %. %j ob_name%- %event _t ype%' ,
body => ' %event _t ype%occur r ed at %event _t i mest amp%. %er r or _message%' ,
event s => ' J OB_FAI LED, J OB_BROKEN, J OB_DI SABLED, J OB_SCH_LI M_REACHED' ) ;
END;


- - conf i gur es an addi t i onal e- mai l not i f i cat i on f or t he same j ob
- - f or a di f f er ent event
BEGI N
DBMS_SCHEDULER. ADD_J OB_EMAI L_NOTI FI CATI ON (
j ob_name => ' emai l _not i f i cat i on_j ob' ,
r eci pi ent s => ' i nf o@ahmedbar aka. com' ,
event s => ' J OB_OVER_MAX_DUR' ) ;
END;


- - The not i f i cat i on f i r es onl y i f a j ob f ai l s wi t h " 600" " 700" er r or codes
BEGI N
DBMS_SCHEDULER. add_j ob_emai l _not i f i cat i on (
j ob_name => ' emai l _not i f i cat i on_j ob' ,
r eci pi ent s => ' i nf o@ahmedbar aka. com' ,
event s => ' j ob_f ai l ed' ,
f i l t er _condi t i on => ' : event . er r or _code=600 or : event . er r or _code=700' ) ;
END;



/ * Removi ng Emai l Not i f i cat i on */
Page 209 Oracle DBA Code Examples

- - r emove t he not i f i cat i on f r omspeci f i ed r eci pi ent / event
BEGI N
DBMS_SCHEDULER. r emove_j ob_emai l _not i f i cat i on (
j ob_name => ' emai l _not i f i cat i on_j ob' ,
r eci pi ent s => ' i nf o@ahmedbar aka. com' ,
event s => ' j ob_succeeded' ) ;
END;

- - r emove t he not i f i cat i on f r omal l r eci pi ent s and event s
BEGI N
DBMS_SCHEDULER. r emove_j ob_emai l _not i f i cat i on (
j ob_name => ' emai l _not i f i cat i on_j ob' ) ;
END;



/ * Obt ai n I nf o about Emai l Not i f i cat i ons */
SELECT j ob_name, r eci pi ent , event , f i l t er _condi t i on, subj ect , body
FROM user _schedul er _not i f i cat i ons;
Using File Watchers
/ * Obt ai n I nf o about FW*/
SELECT f i l e_wat cher _name, dest i nat i on, di r ect or y_pat h, f i l e_name, cr edent i al _name
FROM user _schedul er _f i l e_wat cher s;



/ * Conf i gur at i on */
- - by def aul t , a dest i nat i on i s checked ever y 10 mi ns. To change t hi s:
- - onl y sys can do i t :
CONN / AS SYSDBA
set ser ver out put on
decl ar e
v var char 2( 1000) ;
begi n
DBMS_SCHEDULER. GET_ATTRI BUTE ( ' FI LE_WATCHER_SCHEDULE' , ' REPEAT_I NTERVAL' , v) ;
DBMS_OUTPUT. PUT_LI NE( V) ;
end;
/
BEGI N
DBMS_SCHEDULER. set _at t r i but e(
' f i l e_wat cher _schedul e' ,
' r epeat _i nt er val ' ,
' f r eq=mi nut el y; i nt er val =5' ) ;
END;
/




/ * Cr eat i ng Fi l e Wat cher */
- - cr eat e OS cr edent i al :
BEGI N
DBMS_SCHEDULER. cr eat e_cr edent i al (
cr edent i al _name => ' f w_cr edent i al ' ,
user name => ' or acl e' ,
passwor d => ' or acl e' ) ;
END;
/

Page 210 Oracle DBA Code Examples


- - Gr ant EXECUTE on t he cr edent i al t o t he schema t hat owns t he
- - event - based j ob t hat t he f i l e wat cher wi l l st ar t :
GRANT EXECUTE ON f w_cr edent i al t o DSSUSER;


- - cr eat e f i l e wat cher :
BEGI N
DBMS_SCHEDULER. cr eat e_f i l e_wat cher (
f i l e_wat cher _name => ' dat a_f w' ,
di r ect or y_pat h => ' / t mp/ t est ' , - - i f ' ?' = ORACLE_HOME
f i l e_name => ' *. dat ' , - - wi l dcar d suppor t ed
cr edent i al _name => ' f w_cr edent i al ' ,
dest i nat i on => NULL, - - NULL=l ocal ser ver
enabl ed => FALSE) ;
END;
/


- - Gr ant EXECUTE on t he f i l e wat cher t o any schema t hat owns an event - based j ob
- - t hat r ef er ences t he f i l e wat cher .
GRANT EXECUTE ON dat a_f w t o DSSUSER;


- - cr eat e a pr ogr amr ai sed by t he f i l e wat cher
BEGI N
DBMS_SCHEDULER. cr eat e_pr ogr am(
pr ogr am_name => ' i mpor t _dat a_pr og' ,
pr ogr am_t ype => ' st or ed_pr ocedur e' ,
pr ogr am_act i on => ' i mpor t _dat a_pr oc' ,
number _of _ar gument s => 1,
enabl ed => FALSE) ;
END;
/


- - def i ne t he met adat a ar gument usi ng t he event _message at t r i but e
- - t he met adat a cont ai ns i nf o about t he f i l e, such as i t s name:
BEGI N
DBMS_SCHEDULER. def i ne_met adat a_ar gument (
pr ogr am_name => ' i mpor t _dat a_pr og' ,
met adat a_at t r i but e => ' event _message' ,
ar gument _posi t i on => 1) ;
END;
/


- - cr eat e t he def i ned pr ocedur e:
- - I t must accept an ar gument of t he SCHEDULER_FI LEWATCHER_RESULT t ype
CREATE TABLE r ecei ved_f i l es ( f i l ei nf o VARCHAR2( 4000) , r dat e dat e ) ;

CREATE OR REPLACE PROCEDURE i mpor t _dat a_pr oc
( p_sf wr SYS. SCHEDULER_FI LEWATCHER_RESULT) AS
v_message r ecei ved_f i l es. f i l ei nf o%t ype;
BEGI N
v_message : = p_sf wr . di r ect or y_pat h | | ' / ' | | p_sf wr . act ual _f i l e_name | | ' ( ' | |
p_sf wr . f i l e_si ze | | ' ) ' ;

I NSERT I NTO r ecei ved_f i l es
VALUES ( v_message, sysdat e) ;
COMMI T;
END;
/

Page 211 Oracle DBA Code Examples



- - cr eat e t he j ob:
BEGI N
DBMS_SCHEDULER. cr eat e_j ob(
j ob_name => ' i mpor t _dat a_j ob' ,
pr ogr am_name => ' i mpor t _dat a_pr og' ,
event _condi t i on => NULL, - - ' t ab. user _dat a. f i l e_si ze < 1024'
queue_spec => ' dat a_f w' , - - f i l e wat cher name
aut o_dr op => FALSE,
enabl ed => FALSE) ;
END;
/



- - By def aul t , t he ar r i val of new f i l es wi l l be i gnor ed i f t he j ob i s al r eady r unni ng.
- - I f you need t he j ob t o f i r e f or each new ar r i val , r egar dl ess of whet her t he j ob i s
al r eady
- - r unni ng or not , set t he PARALLEL_I NSTANCES at t r i but e f or t he j ob t o t r ue. The j ob
- - wi l l t hen be r un as a l i ght wei ght j ob:
BEGI N
DBMS_SCHEDULER. set _at t r i but e( ' i mpor t _dat a_j ob' , ' par al l el _i nst ances' , TRUE) ;
END;
/



- - Enabl e al l t he obj ect s:
EXEC DBMS_SCHEDULER. enabl e( ' dat a_f w' , ' i mpor t _dat a_pr og' , ' i mpor t _dat a_j ob' ) ;


- - t o t est :
echo " Thi s i s a t est " > / t mp/ t est / f 1. dat
echo " Thi s i s a t est t oo" > / t mp/ t est / f 2. dat
echo " Yes anot her t est " > / t mp/ t est / f 3. dat


sel ect * f r omr ecei ved_f i l es or der by r dat e desc;



/ * Managi ng Fi l e Wat cher s */
- - enabl e/ di sabl e
EXEC DBMS_SCHEDULER. enabl e( ' dat a_f w' ) ;
EXEC DBMS_SCHEDULER. di sabl e( ' dat a_f w' ) ;


- - change an at t r i but e:
begi n
DBMS_SCHEDULER. SET_ATTRI BUTE (
name => ' dat a_f w' ,
at t r i but e =>' di r ect or y_pat h' ,
val ue =>' / home/ or acl e/ r ecei vedf i l es' ) ;
end;
/

begi n
DBMS_SCHEDULER. SET_ATTRI BUTE (
name => ' dat a_f w' ,
at t r i but e =>' f i l e_name' ,
val ue =>' *. t xt ' ) ;
end;
/
Page 212 Oracle DBA Code Examples


begi n
DBMS_SCHEDULER. SET_ATTRI BUTE (
name => ' dat a_f w' ,
at t r i but e =>' cr edent i al _name' ,
val ue =>' f w_cr edent i al 2' ) ;
end;
/


- - t o dr op a f i l e wat cher s:
DBMS_SCHEDULER. DROP_FI LE_WATCHER( ' dat a_f w' ) ;
Using Events Raised by the Scheduler
- - by def aul t messages r ai sed by t he schedul er ar e
- - del et ed af t er 24 hour s: event _expi r y_t i me
SET SERVEROUTPUT ON
DECLARE
V VARCHAR2( 200) ;
BEGI N
DBMS_SCHEDULER. GET_SCHEDULER_ATTRI BUTE (
at t r i but e =>' EVENT_EXPI RY_TI ME' ,
val ue =>V) ;
DBMS_OUTPUT. PUT_LI NE( nvl ( V, ' 24 hour s' ) ) ; - - 24 hour s i f nul l
END;
/

decl ar e
n number : = 48*60*60;
begi n
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE(
at t r i but e =>' EVENT_EXPI RY_TI ME' ,
val ue =>n) ; - - i n seconds ( 24 hour s i f NULL)
end;
/

- - maki ng sur e t he r equi r ed pr i vs ar e gr ant ed
- - EXECUTE on bot h DBMS_AQ and DBMS_AQADM
CONN SYS
sel ect gr ant ee, pr i vi l ege, t abl e_name
f r om DBA_TAB_PRI VS
wher e t abl e_name i n ( ' DBMS_AQ' , ' DBMS_AQADM' )
and gr ant ee=' USER1' ;

GRANT EXECUTE ON DBMS_AQ TO USER1;
GRANT EXECUTE ON DBMS_AQADM TO USER1;
GRANT SELECT ON DBA_AQ_AGENTS TO USER1;
GRANT CREATE J OB TO USER1;
GRANT CREATE EXTERNAL J OB TO USER1;

begi n
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' ENQUEUE_ANY' , ' USER1' , FALSE) ;
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' DEQUEUE_ANY' , ' USER1' , FALSE) ;
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' MANAGE_ANY' , ' USER1' , FALSE) ;
end;
/
Page 213 Oracle DBA Code Examples


- - cr eat e t he j ob
BEGI N
DBMS_SCHEDULER. CREATE_J OB
( j ob_name => ' " USER1" . " U1J OB" ' ,
j ob_t ype => ' EXECUTABLE' ,
j ob_act i on => ' C: \ wi ndows\ syst em32\ cmd. exe' ,
number _of _ar gument s => 3,
st ar t _dat e => syst i mest amp,
r epeat _i nt er val => ' FREQ=SECONDLY; I NTERVAL=10' ,
comment s => ' Test i ng Event s r ai sed by schedul er ' ,
aut o_dr op => FALSE,
enabl ed => FALSE) ;
DBMS_SCHEDULER. set _j ob_ar gument _val ue( ' " USER1" . " U1J OB" ' , 1, ' / c' ) ;
DBMS_SCHEDULER. set _j ob_ar gument _val ue( ' " USER1" . " U1J OB" ' , 2,
' c: \ t emp\ t est me. bat ' ) ;
DBMS_SCHEDULER. set _j ob_ar gument _val ue( ' " USER1" . " U1J OB" ' , 3, ' passed t o bat ' ) ;
END;
/


- - al t er j ob t o r ai se event s
BEGI N
DBMS_SCHEDULER. SET_ATTRI BUTE(
name => ' " USER1" . " U1J OB" ' ,
at t r i but e => ' r ai se_event s' ,
val ue => dbms_schedul er . j ob_st ar t ed +
dbms_schedul er . j ob_succeeded +
dbms_schedul er . j ob_f ai l ed +
dbms_schedul er . j ob_br oken +
dbms_schedul er . j ob_compl et ed +
dbms_schedul er . j ob_st opped +
dbms_schedul er . j ob_sch_l i m_r eached +
dbms_schedul er . j ob_di sabl ed +
dbms_schedul er . j ob_chai n_st al l ed
) ;
END;
/

- - enabl e J ob
BEGI N
DBMS_SCHEDULER. ENABLE( ' " USER1" . " U1J OB" ' ) ;
END;
/


- - Consumi ng Schedul er - Rai sed Event s wi t h your Appl i cat i on
- - f ol l ow ei t her Pl an A or Pl an B
- - Plan A
- - 1. conn sys or wi t h user of MANAGE ANY QUEUE
- - 2. Subscr i be t o t he queue usi ng a new or exi st i ng agent
- - 3. Run t he pr ocedur e DBMS_AQADM. ENABLE_DB_ACCESS( agent _name, db_user name) ;
-- Plan B
/ * DBMS_SCHEDULER. ADD_EVENT_QUEUE_SUBSCRI BER( subscr i ber _name) ;
wher e subscr i ber _name i s t he name of t he Or acl e St r eams Advanced Queui ng
( AQ) agent t o be used t o subscr i be t o t he Schedul er event queue. ( I f i t i s
NULL, an agent i s cr eat ed whose name i s t he user name of t he cal l i ng user . )
Thi s cal l bot h cr eat es a subscr i pt i on t o t he Schedul er event queue and gr ant s
Page 214 Oracle DBA Code Examples

t he user per mi ssi on t o dequeue usi ng t he desi gnat ed agent . */
conn user 1
exec DBMS_SCHEDULER. ADD_EVENT_QUEUE_SUBSCRI BER
- - opposi t e: REMOVE_EVENT_QUEUE_SUBSCRI BER

- - Event s ar e dequeued f r omt he schedul er event queue usi ng t he DBMS_AQ
SET SERVEROUTPUT ON
DECLARE
l _dequeue_opt i ons DBMS_AQ. dequeue_opt i ons_t ;
l _message_pr oper t i es DBMS_AQ. message_pr oper t i es_t ;
l _message_handl e RAW( 16) ;
l _queue_msg sys. schedul er $_event _i nf o;
BEGI N
l _dequeue_opt i ons. consumer _name : = ' USER1' ;
DBMS_AQ. dequeue( queue_name => ' SYS. SCHEDULER$_EVENT_QUEUE' ,
dequeue_opt i ons => l _dequeue_opt i ons,
message_pr oper t i es => l _message_pr oper t i es,
payl oad => l _queue_msg,
msgi d => l _message_handl e) ;
COMMI T;

DBMS_OUTPUT. put _l i ne ( ' event _t ype : ' | | l _queue_msg. event _t ype) ;
DBMS_OUTPUT. put _l i ne ( ' obj ect _owner : ' | | l _queue_msg. obj ect _owner ) ;
DBMS_OUTPUT. put _l i ne ( ' obj ect _name : ' | | l _queue_msg. obj ect _name) ;
DBMS_OUTPUT. put _l i ne ( ' event _t i mest amp: ' | | l _queue_msg. event _t i mest amp) ;
DBMS_OUTPUT. put _l i ne ( ' er r or _code : ' | | l _queue_msg. er r or _code) ;
DBMS_OUTPUT. put _l i ne ( ' event _st at us : ' | | l _queue_msg. event _st at us) ;
DBMS_OUTPUT. put _l i ne ( ' l og_i d : ' | | l _queue_msg. l og_i d) ;
DBMS_OUTPUT. put _l i ne ( ' r un_count : ' | | l _queue_msg. r un_count ) ;
DBMS_OUTPUT. put _l i ne ( ' f ai l ur e_count : ' | | l _queue_msg. f ai l ur e_count ) ;
DBMS_OUTPUT. put _l i ne ( ' r et r y_count : ' | | l _queue_msg. r et r y_count ) ;
END;
/

- - r emove t he j ob and unsubscr i bes t he user f r omt he schedul er event queue
EXEC DBMS_SCHEDULER. dr op_j ob( ' " USER1" . " U1J OB" ' )
EXEC DBMS_SCHEDULER. r emove_event _queue_subscr i ber
Using Events Raised by an Application (Events-Based Jobs)
- - by def aul t messages r ai sed by t he schedul er ar e
- - del et ed af t er 24 hour s: event _expi r y_t i me
decl ar e
n number : = 48*60*60;
begi n
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE (
at t r i but e =>' event _expi r y_t i me' ,
val ue =>n) ; - - i n seconds ( 24 hour s i f NULL)
end;
/

- - maki ng sur e t he r equi r ed pr i vs ar e gr ant ed
- - EXECUTE on bot h DBMS_AQ and DBMS_AQADM
sel ect gr ant ee, pr i vi l ege, t abl e_name
f r omdba_t ab_pr i vs
wher e t abl e_name i n ( ' DBMS_AQ' , ' DBMS_AQADM' )
Page 215 Oracle DBA Code Examples

and gr ant ee=' TEST_USER' ;

GRANT EXECUTE ON DBMS_AQ TO t est _user ;
GRANT EXECUTE ON DBMS_AQADM TO t est _user ;
GRANT SELECT ON DBA_AQ_AGENTS TO t est _user ;
begi n
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' ENQUEUE_ANY' , ' t est _user ' , FALSE) ;
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' DEQUEUE_ANY' , ' t est _user ' , FALSE) ;
DBMS_AQADM. GRANT_SYSTEM_PRI VI LEGE( ' MANAGE_ANY' , ' t est _user ' , FALSE) ;
end;
/

- - CONNECT AS t est _user
- - cr eat e t ype f or t he message t o r ecei ve
connect mar vi n/ pani c
cr eat e or r epl ace t ype MY_MSGT as obj ect ( msg var char 2( 20) )
/

begi n
DBMS_AQADM. CREATE_QUEUE_TABLE
( QUEUQ_TABLE=>' MY_QT' ,
QUEUQ_PAYLOAD_TYPE => ' MY_MSGT' ,
MULTI PLE_CONSUMERS => TRUE ) ;
DBMS_AQADM. CREATE_QUEUE(
QUEUE_NAME => ' MY_Q' ,
QUEUE_TABLE => ' MY_QT' ) ;
DBMS_AQADM. START_QUEUE( QUEUE_NAME=>' MY_Q' ) ;
end;
/

- - exampl e of event _condi t i on = ' t ab. user _dat a. event _t ype = ' ' CARD_SWI PE' '
and ext r act hour f r omt ab. user _dat a. event _t i mest amp < 9'
BEGI N
dbms_schedul er . cr eat e_j ob
(
j ob_name => ' " TEST_USER" . " BCKUP_01" ' ,
j ob_t ype => ' EXECUTABLE' ,
j ob_act i on => ' / home/ or acl e/ bi n/ r man. sh' ,
event _condi t i on => ' t ab. user _dat a. msg=' ' GO' ' ' ,
queue_spec => ' " TEST_USER" . " MY_Q" ' , - - agent , queue name
st ar t _dat e => syst i mest amp,
j ob_cl ass => NULL,
comment s => ' backup a dat abase' ,
aut o_dr op => FALSE,
number _of _ar gument s => 1,
enabl e => FALSE
) ;
END;
/

- - Al t er i ng a J ob t o Rai se Event s
BEGI N
DBMS_SCHEDULER. SET_ATTRI BUTE( ' dw_r epor t s' , ' r ai se_event s' ,
DBMS_SCHEDULER. J OB_FAI LED + DBMS_SCHEDULER. J OB_SCH_LI M_REACHED) ;
END;
/
r ai se_event s j ob_st ar t ed CONSTANT PLS_I NTEGER : = 1
Page 216 Oracle DBA Code Examples

j ob_succeeded CONSTANT PLS_I NTEGER : = 2
j ob_f ai l ed CONSTANT PLS_I NTEGER : =4
j ob_br oken CONSTANT PLS_I NTEGER : =8
j ob_compl et ed CONSTANT PLS_I NTEGER : =16
j ob_st opped CONSTANT PLS_I NTEGER : =32
j ob_sch_l i m_r eached CONSTANT PLS_I NTEGER : =64
j ob_di sabl ed CONSTANT PLS_I NTEGER : =128
j ob_chai n_st al l ed CONSTANT PLS_I NTEGER : =256
j ob_al l _event s CONSTANT PLS_I NTEGER : = 511
j ob_r un_compl et ed : = j ob_succeeded + j ob_f ai l ed + j ob_st opped

- - i f r equi r ed, set ar gument s and at t r i but es
- - j ob ar gument passed t o t he j ob
DBMS_SCHEDULER. SET_J OB_ARGUMENT_VALUE
(
j ob_name => ' " TEST_USER" . " BCKUP_01" ' ,
ar gument _posi t i on => 1,
ar gument _val ue => ' db_01'
) ;
- - f or r emot e j ob
DBMS_SCHEDULER. SET_ATTRI BUTE
(
name => ' " TEST_USER" . " BCKUP_01" ' ,
at t r i but e => ' dest i nat i on' ,
val ue => ' pant zer : 15021'
) ;
DBMS_SCHEDULER. SET_ATTRI BUTE
(
name => ' " TEST_USER" . " BCKUP_01" ' ,
at t r i but e => ' cr edent i al _name' ,
val ue => ' " TEST_USER. " J OBS_CRED2" '
) ;
END;
/

- - enabl e J ob
BEGI N
DBMS_SCHEDULER. ENABLE( ' " TEST_USER" . " BCKUP_01" ' ) ;
END;
/

DECLARE
my_msgi d RAW( 16) ;
pr ops dbms_aq. message_pr oper t i es_t ;
enqopt s dbms_aq. enqueue_opt i ons_t ;
BEGI N
sys. dbms_aq. enqueue( ' mar vi n. bckup_q' , enqopt s, pr ops,
mar vi n. bckup_msgt ( ' GO' ) , my_msgi d) ;
end;
/
COMMI T;

- - * al t er nat i vel y schedul er can be used f or t he same
BEGI N
DBMS_SCHEDULER. CREATE_EVENT_SCHEDULE (
schedul e_name => ' ent r y_event s_schedul e' ,
st ar t _dat e => SYSTI MESTAMP,
Page 217 Oracle DBA Code Examples

event _condi t i on => ' t ab. user _dat a. event _t ype = ' ' CARD_SWI PE' ' ' ,
queue_spec => ' ent r y_event s_q, ent r y_agent 1' ) ;
END;
/

BEGI N
DBMS_SCHEDULER. SET_ATTRI BUTE ( ' ent r y_event s_schedul e' , ' event _spec' ,
' t ab. user _dat a. event _t ype = ' ' BAD_BADGE' ' ' , ' ent r y_event s_q, ent r y_agent 1' ) ;
END;
/

Using Chains
-- Creating Chains
BEGI N
DBMS_SCHEDULER. CREATE_CHAI N (
chai n_name => ' my_chai n1' ,
r ul e_set _name => NULL,
eval uat i on_i nt er val => NULL,
comment s => ' My f i r st chai n' ) ;
END;
/

- - Def i ni ng Chai n St eps
- - a st ep poi nt t o pr ogr am, anot her chai n, event
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP (
chai n_name => ' my_chai n1' ,
st ep_name => ' my_st ep1' ,
pr ogr am_name => ' my_pr ogr am1' ) ;

DBMS_SCHEDULER. DEFI NE_CHAI N_STEP (
chai n_name => ' my_chai n1' ,
st ep_name => ' my_st ep2' ,
pr ogr am_name => ' my_chai n2' ) ;
END;
/

- - event - based ( wai t s f or an event t o occur )
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_EVENT_STEP (
chai n_name => ' my_chai n1' ,
st ep_name => ' my_st ep3' ,
event _schedul e_name => ' my_event _schedul e' ) ;
END;
/

- - Addi ng Rul es t o a Chai n
- - Each r ul e has a condi t i on and an act i on
- - r ul e t hat st ar t s t he chai n al ways eval uat es t o TRUE
- - A chai n j ob does not compl et e unt i l one of t he r ul es cont ai ni ng t he END
act i on
- - eval uat es t o TRUE. I f no such a st ep, t he j ob ent er s t he CHAI N_STALLED
st at e.
BEGI N
Page 218 Oracle DBA Code Examples

DBMS_SCHEDULER. DEFI NE_CHAI N_RULE (
chai n_name => ' my_chai n1' ,
condi t i on => ' TRUE' ,
act i on => ' START st ep1' ,
r ul e_name => ' my_r ul e1' ,
comment s => ' st ar t t he chai n' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE (
chai n_name => ' my_chai n1' ,
condi t i on => ' st ep1 compl et ed' ,
act i on => ' START st ep2' ,
r ul e_name => ' my_r ul e2' ) ;
END;
/
/ *
: st ep_name. at t r i but e. ( st ep_name r ef er s t o a t yped obj ect . ) Possi bl e
at t r i but es ar e:
compl et ed, st at e, st ar t _dat e, end_dat e, er r or _code,
and dur at i on. Possi bl e val ues f or t he st at e at t r i but e
i ncl ude: ' NOT_STARTED' , ' SCHEDULED' , ' RUNNI NG' ,
' PAUSED' , ' STALLED' , ' SUCCEEDED' , ' FAI LED' , and
' STOPPED' . I f a st ep i s i n t he st at e ' SUCCEEDED' , ' FAI LED' ,
or ' STOPPED' , i t s compl et ed at t r i but e i s set t o ' TRUE' ,
ot her wi se compl et ed i s ' FALSE' .
*/
- - exampl es of condi t i ons
st ep3 succeeded
st ep3 f ai l ed

- - Exampl e: 2
BEGI N
DBMS_SCHEDULER. CREATE_CHAI N (
chai n_name => ' my_chai n1' ,
r ul e_set _name => NULL,
eval uat i on_i nt er val => NULL,
comment s => NULL) ;
END;
/
- - - def i ne t hr ee st eps f or t hi s chai n.
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n1' , ' st ep1' , ' my_pr ogr am1' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n1' , ' st ep2' , ' my_pr ogr am2' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n1' , ' st ep3' , ' my_pr ogr am3' ) ;
END;
/
- - - def i ne cor r espondi ng r ul es f or t he chai n.
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE( ' my_chai n1' , ' TRUE' , ' START st ep1' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE (
' my_chai n1' , ' st ep1 COMPLETED' , ' St ar t st ep2, st ep3' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE (
' my_chai n1' , ' st ep2 COMPLETED AND st ep3 COMPLETED' , ' END' ) ;
END;
/

- - Exampl e 3:
BEGI N
DBMS_SCHEDULER. CREATE_CHAI N (
Page 219 Oracle DBA Code Examples

chai n_name => ' my_chai n2' ,
r ul e_set _name => NULL,
eval uat i on_i nt er val => NULL,
comment s => NULL) ;
END;
/
- - - def i ne t hr ee st eps f or t hi s chai n.
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n2' , ' st ep1' , ' my_pr ogr am1' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n2' , ' st ep2' , ' my_pr ogr am2' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_STEP( ' my_chai n2' , ' st ep3' , ' my_pr ogr am3' ) ;
END;
/
- - - def i ne cor r espondi ng r ul es f or t he chai n.
BEGI N
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE ( ' my_chai n2' , ' TRUE' , ' START st ep1' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE ( ' my_chai n2' , ' st ep1 SUCCEEDED' , ' St ar t
st ep2' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE ( ' my_chai n2' , ' st ep1 COMPLETED AND st ep1
NOT SUCCEEDED' , ' St ar t st ep3' ) ;
DBMS_SCHEDULER. DEFI NE_CHAI N_RULE ( ' my_chai n2' , ' st ep2 COMPLETED OR st ep3
COMPLETED' , ' END' ) ;
END;
/

-- Enabling Chains
BEGI N
DBMS_SCHEDULER. ENABLE ( ' my_chai n1' ) ;
END;
/

- - Cr eat i ng J obs f or Chai ns
- - ei t her use t he RUN_CHAI N pr ocedur e or cr eat e a j ob of t ype
- - ' CHAI N' . j ob act i on r ef er s t o chai n name
- - a st ep j ob cr eat ed f or ever y st ep
BEGI N
DBMS_SCHEDULER. CREATE_J OB (
j ob_name => ' chai n_j ob_1' ,
j ob_t ype => ' CHAI N' ,
j ob_act i on => ' my_chai n1' ,
r epeat _i nt er val => ' f r eq=dai l y; byhour =13; bymi nut e=0; bysecond=0' ,
enabl ed => TRUE) ;
END;
/

- - Dr oppi ng Chai ns
BEGI N
DBMS_SCHEDULER. DROP_CHAI N (
chai n_name => ' my_chai n1' ,
f or ce => TRUE) ;
END;
/

- - Runni ng Chai ns
BEGI N
DBMS_SCHEDULER. RUN_CHAI N (
chai n_name => ' my_chai n1' ,
j ob_name => ' qui ck_chai n_j ob' ,
Page 220 Oracle DBA Code Examples

st ar t _st eps => ' my_st ep1, my_st ep2' ) ;
END;
/

- - Dr oppi ng Rul es f r oma Chai n
BEGI N
DBMS_SCHEDULER. DROP_CHAI N_RULE (
chai n_name => ' my_chai n1' ,
r ul e_name => ' my_r ul e1' ,
f or ce => TRUE) ;
END;
/

- - Di sabl i ng Chai ns
BEGI N
DBMS_SCHEDULER. DI SABLE ( ' my_chai n1' ) ;
END;
/

- - Dr oppi ng Chai n St eps
BEGI N
DBMS_SCHEDULER. DROP_CHAI N_STEP (
chai n_name => ' my_chai n2' ,
st ep_name => ' my_st ep2' ,
f or ce => TRUE) ;
END;
/

- - Al t er i ng Chai n St eps
BEGI N
DBMS_SCHEDULE. ALTER_CHAI N (
chai n_name => ' my_chai n1' ,
st ep_name => ' my_st ep3' ,
at t r i but e => ' SKI P' ,
val ue => TRUE) ;
END;
/
- - f or a r unni ng st ep
BEGI N
DBMS_SCHEDULER. ALTER_RUNNI NG_CHAI N (
j ob_name => ' my_j ob1' ,
st ep_name => ' my_st ep1' ,
at t r i but e => ' PAUSE' ,
val ue => TRUE) ;
END;
/

- - Handl i ng St al l ed Chai ns
- - opt i on1: al t er t he st at e of one of i t s st eps wi t h t he
- - check ALL_SCHEDULER_RUNNI NG_CHAI NS and ALL_SCHEDULER_CHAI N_RULES
BEGI N
DBMS_SCHEDULER. ALTER_RUNNI NG_CHAI N (
j ob_name => ' my_j ob1' ,
st ep_name => ' my_st ep1' ,
at t r i but e => ' SUCCEEDED' ,
val ue => TRUE) ;
END;
Page 221 Oracle DBA Code Examples

/
- - opt i on2:
- - i f one or mor e r ul es ar e i ncor r ect , you can use t he
- - DEFI NE_CHAI N_RULE pr ocedur e t o r epl ace t hem
- - check ALL_SCHEDULER_CHAI N_RULES
- - Af t er addi ng or updat i ng r ul es, you must r un EVALUATE_RUNNI NG_CHAI N
Allocating Resources Among Jobs
For jobs, resource allocation is specified by associating a job class with a consumer group,
or by associating a job class with a database service name and mapping that database
service to a consumer group.
BEGI N
DBMS_SCHEDULER. CREATE_J OB_CLASS (
j ob_cl ass_name => ' f i nance_j obs' ,
r esour ce_consumer _gr oup => ' f i nance_gr oup' ) ;
END;
/
Administering Oracle Scheduler
Configuring Oracle Scheduler
- - Set t i ng Schedul er Pr i vi l eges
GRANT SCHEDULER_ADMI N TO user name;
- - cr eat e j obs, schedul es, or pr ogr ams
GRANT CREATE J OB TO scot t ;
- - al t er , or dr op wi ndows, j ob cl asses, or wi ndow gr oups
GRANT MANAGE SCHEDULER TO adam;

- - Set t i ng Chai n Pr i vi l eges
- - cr eat e a chai n i n hi s own schema, cr eat e r ul es, r ul e set s,
- - and eval uat i on cont ext s i n hi s own schema
BEGI N
DBMS_RULE_ADM. GRANT_SYSTEM_PRI VI LEGE( DBMS_RULE_ADM. CREATE_RULE_OBJ ,
' user name' ) ;
DBMS_RULE_ADM. GRANT_SYSTEM_PRI VI LEGE ( DBMS_RULE_ADM. CREATE_RULE_SET_OBJ ,
' user name' ) ;
DBMS_RULE_ADM. GRANT_SYSTEM_PRI VI LEGE
( DBMS_RULE_ADM. CREATE_EVALUATI ON_CONTEXT_OBJ , ' user name' ) ;
END;
/

- - Set t i ng Schedul er At t r i but es
- - def aul t _t i mezone
sel ect dbms_schedul er . st i me f r omdual ;
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE( ' def aul t _t i mezone' , ' US/ East er n' ) ;
SELECT DI STI NCT TZNAME FROM V$TI MEZONE_NAMES;
- - l og_hi st or y
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE( ' l og_hi st or y' , ' 90' ) ;
- - max_j ob_sl ave_pr ocesses ( def aul t NULL)
- - event _expi r y_t i me
SET SERVEROUTPUT ON
DECLARE
Page 222 Oracle DBA Code Examples

V VARCHAR2( 200) ;
BEGI N
DBMS_SCHEDULER. GET_SCHEDULER_ATTRI BUTE (
at t r i but e =>' EVENT_EXPI RY_TI ME' ,
val ue =>V) ;
DBMS_OUTPUT. PUT_LI NE( nvl ( V, ' 24 hour s' ) ) ; - - 24 hour s i f nul l
END;
/
decl ar e
n number : = 48*60*60;
begi n
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE(
at t r i but e =>' EVENT_EXPI RY_TI ME' ,
val ue =>n) ; - - i n seconds ( 24 hour s i f NULL)
end;
/
Monitoring and Managing the Scheduler
-- Viewing the Currently Active Window and Resource Plan
SELECT WI NDOW_NAME, RESOURCE_PLAN
FROM DBA_SCHEDULER_WI NDOWS
WHERE ACTI VE=' TRUE' ;


-- Finding Information About Currently Running Jobs
SELECT J OB_NAME, STATE FROM DBA_SCHEDULER_J OBS
WHERE J OB_NAME = ' MY_EMP_J OB1' ;

SELECT J OB_NAME , STATE, START_DATE, END_DATE, LAST_START_DATE,
NEXT_RUN_DATE, LAST_RUN_DURATI ON, FAI LURE_COUNT
FROM USER_SCHEDULER_J OBS
ORDER BY START_DATE DESC;

- - pr ogr ess of cur r ent l y r unni ng j obs
SELECT * FROM ALL_SCHEDULER_RUNNI NG_J OBS;

- - j ob t hat i s par t of a r unni ng chai n
SELECT * FROM ALL_SCHEDULER_RUNNI NG_CHAI NS
WHERE J OB_NAME=' MY_J OB1' ;


-- Monitoring and Managing Window and Job Logs
SELECT J OB_NAME, OPERATI ON, OWNER FROM DBA_SCHEDULER_J OB_LOG;


-- Job Run History Details
sel ect l og_i d,
j ob_name, st at us,
t o_char ( l og_dat e, ' DD- MON- YYYY HH24: MI ' ) l og_dat e
f r omdba_schedul er _j ob_r un_det ai l s
wher e j ob_name = ' MY_J OB14' ;


-- Controlling Job Logging: at job or class levels
l oggi ng_l evel at t r i but e i n t he CREATE_J OB_CLASS:
DBMS_SCHEDULER. LOGGI NG_OFF, DBMS_SCHEDULER. LOGGI NG_RUNS,
DBMS_SCHEDULER. LOGGI NG_FULL
Page 223 Oracle DBA Code Examples

DBMS_SCHEDULER. SET_ATTRI BUTE (
' myt est j ob' , ' l oggi ng_l evel ' , DBMS_SCHEDULER. LOGGI NG_FULL) ;


-- Window Logs
SELECT LOG_I D, TO_CHAR( LOG_DATE, ' MM/ DD/ YYYY' ) , WI NDOW_NAME, OPERATI ON
FROM DBA_SCHEDULER_WI NDOW_LOG;
SELECT LOG_I D, WI NDOW_NAME, ACTUAL_START_DATE, ACTUAL_DURATI ON
FROM DBA_SCHEDULER_WI NDOW_DETAI LS;


-- Purging Logs
DBMS_SCHEDULER. SET_SCHEDULER_ATTRI BUTE( ' l og_hi st or y' , ' 90' ) ; - - days
- - can be speci f i ed at j ob cl ass cr eat e
DBMS_SCHEDULER. SET_ATTRI BUTE( ' cl ass2' , ' l og_hi st or y' , ' 30' ) ;
- - Pur gi ng Logs Manual l y
DBMS_SCHEDULER. PURGE_LOG( ) ;
- - ur ges al l ent r i es f r omt he j og l og t hat ar e
- - ol der t han t hr ee days. The wi ndow l og i s not af f ect ed
DBMS_SCHEDULER. PURGE_LOG( l og_hi st or y => 3, whi ch_l og => ' J OB_LOG' ) ;
DBMS_SCHEDULER. PURGE_LOG( l og_hi st or y => 10, j ob_name => ' j ob1, sys. cl ass2' ) ;


-- Changing Job Priorities
- - 1( hi gh) - 5
BEGI N
DBMS_SCHEDULER. SET_ATTRI BUTE (
name => ' my_emp_j ob1' ,
at t r i but e => ' j ob_pr i or i t y' ,
val ue => 1) ;
END;
/
SELECT J OB_NAME, J OB_PRI ORI TY FROM DBA_SCHEDULER_J OBS;


-- Monitoring Running Chains
SELECT *
FROM USER_SCHEDULER_RUNNI NG_CHAI NS
WHERE J OB_NAME = ' MY_CHAI N_J OB' ;
Enabling, Using and Disabling Remote External Jobs
- - 1) Set t i ng Up t he Dat abase
conn sys
- - ver i f y t hat t he XML DB opt i on i s i nst al l ed:
DESC RESOURCE_VI EW
- - Enabl e HTTP connect i ons t o t he dat abase:
- - por t bet ween 1 and 65536, and f or UNI X and Li nux gr eat er t han 1023
BEGI N
DBMS_XDB. SETHTTPPORT( por t ) ;
END;
/
- - r un scr i pt
SQL> @?/ r dbms/ admi n/ pr vt r sch. pl b
- - Set a r egi st r at i on passwor d
BEGI N
DBMS_SCHEDULER. SET_AGENT_REGI STRATI ON_PASS( ' mypasswor d' ) ;
END;
Page 224 Oracle DBA Code Examples

/

- - 2) I nst al l i ng, Conf i gur i ng, and St ar t i ng t he Schedul er Agent
- - i nst al l Schedul er agent f r omOr acl e Dat abase Gat eways i n
- - t he Dat abase Medi a Pack i n i t s own HOME
- - To i nst al l , conf i gur e, and st ar t t he Schedul er agent on a r emot e host :
- - Log i n t o t he r emot e host as or acl e
- - Run t he Or acl e Uni ver sal I nst al l er
- - - > Next
- - - > sel ect Or acl e Schedul er Agent - > Next
- - - > Home
- - - > enet er host name, por t
- - - > i nst al l
- - - > r un scr i pt _pat h/ r oot . sh as r oot
- - - > Exi t
- - cehck t he agent conf i gur at i on par amet er s i n t he f i l e: schagent . conf

- - Regi st er t he Schedul er agent wi t h a dat abase t hat i s t o r un r emot e
ext er nal j obs on
- - t he agent ' s host comput er . Use t he f ol l owi ng command:
AGENT_HOME/ bi n/ schagent - r egi st er dat abase db_host db_ht t p_por t
wher e:
db_host i s t he host name or I P addr ess of t he host on whi ch t he dat abase
r esi des.
db_ht t p_por t i s t he por t number t hat t he dat abase l i st ens on f or HTTP
connect i ons.
SELECT DBMS_XDB. GETHTTPPORT( ) FROM DUAL; - - zer o means di sabl ed

Repeat t he pr evi ous st ep f or each dat abase t hat i s t o r un r emot e ext er nal
j obs on t he agent ' s host .

St ar t t he Schedul er agent wi t h t he f ol l owi ng command:
AGENT_HOME/ bi n/ schagent - st ar t

- - 3) St oppi ng t he Schedul er Agent
On UNI X and Li nux:
AGENT_HOME/ bi n/ schagent - st op
On Wi ndows, st op t he ser vi ce Or acl eSchedul er Execut i onAgent

- - 4) Di sabl i ng Remot e Ext er nal J obs
DROP USER REMOTE_SCHEDULER_AGENT CASCADE;
Regi st r at i on of new schedul er agent s and execut i on of r emot e ext er nal j obs i s
di sabl ed unt i l you r un pr vt r sch. pl b agai n.



/ * t o cr eat e a r emot e ext er nal j ob */
- - cr eat e a cr edent i al obj ect
exec dbms_schedul er . cr eat e_cr edent i al ( ' hr cr edent i al ' , ' hr ' , ' hr passwor d' ) ;

- - Gr ant pr i vi l eges
gr ant execut e on syst em. hr cr dent i al t o someuser ;

- - cr eat e t he r emot e ext er nal j ob:
begi n
dbms_schedul er . cr eat e_j ob(
j ob_name => ' r emove_l ogs' ,
j ob_t ype => ' execut abl e' ,
Page 225 Oracle DBA Code Examples

j ob_act i on => ' / u01/ app/ or acl e/ l ogs/ r emovel ogs' ,
r epeat _i nt er val => ' f r eq=dai l y; byhour =23' ,
enabl ed => f al se) ;
end;
/

- - set t he CREDENTI AL_NAME at t r i but e
exec
dbms_schedul er . set _at t r i but e( ' r emove_l ogs' , ' cr edent i al _name' , ' hr cr edent i al ' ) ;

- - set t he DESTI NATI ON at t r i but e
exec dbms_schedul er . set _at t r i but e( ' r emove_l ogs' , ' dest i nat i on' ,
' l ocal host . l ocal domai n: 1521' ) ;

- - enabl e t he ext er nal j ob
exec dbms_schedul er . enabl e( ' r emove_l ogs' ) ;
Import/Export and the Scheduler
You must use the Data Pump utilities (impdp and expdp) to export Scheduler objects.
After you import Scheduler credentials, you must reset the passwords using the
SET_ATTRIBUTE procedure of the DBMS_SCHEDULER package.
Scheduler Privileges
System Privileges:
o CREATE JOB
o CREATE ANY JOB
o CREATE EXTERNAL JOB
o EXECUTE ANY PROGRAM
o EXECUTE ANY CLASS
o MANAGE SCHEDULER
Object Privileges: on jobs, programs, chains, schedules and job classes.
o EXECUTE
o ALTER
o ALL
Scheduler Data Dictionary Views
DBA_SCHEDULER_CHAINS
DBA_SCHEDULER_CHAIN_RULES
DBA_SCHEDULER_CHAIN_STEPS
DBA_SCHEDULER_CREDENTIALS
DBA_SCHEDULER_GLOBAL_ATTRIBUTE
DBA_SCHEDULER_JOBS
DBA_SCHEDULER_JOB_ARGS
DBA_SCHEDULER_JOB_CLASSES
DBA_SCHEDULER_JOB_LOG
DBA_SCHEDULER_JOB_ROLES
DBA_SCHEDULER_JOB_RUN_DETAILS
DBA_SCHEDULER_PROGRAMS
DBA_SCHEDULER_PROGRAM_ARGS
DBA_SCHEDULER_REMOTE_DATABASES
Page 226 Oracle DBA Code Examples

DBA_SCHEDULER_REMOTE_JOBSTATE
DBA_SCHEDULER_RUNNING_CHAINS
DBA_SCHEDULER_SCHEDULES
DBA_SCHEDULER_WINDOWS
DBA_SCHEDULER_WINDOW_DETAILS
DBA_SCHEDULER_WINDOW_GROUPS
DBA_SCHEDULER_WINDOW_LOG
DBA_SCHEDULER_WINGROUP_MEMBERS
Using the UTL_FILE Package
CREATE DI RECTORY MYDI R AS ' / home/ or acl e/ ' ;
GRANT READ, WRI TE ON DI RECTORY ut l _di r t o . . | publ i c;

DECLARE
f Handl e UTL_FI LE. FI LE_TYPE;
v_user name dba_user s. user name%TYPE;
CURSOR user s I S SELECT user name FROM dba_user s or der by user name;
n number : = 0;
BEGI N
- - opt i ons: r w a
f Handl e : = UTL_FI LE. FOPEN( ' MYDI R' , ' ut l f i l e. t xt ' , ' w' ) ;
UTL_FI LE. PUT_LI NE( f Handl e, ' SN' | | CHR( 9) | | ' User NAME' ) ;
UTL_FI LE. FCLOSE( f Handl e) ;

/ * r e- Open t he ut l f i l e. t xt f or append, and get i t s f i l e handl e */
f Handl e : = UTL_FI LE. FOPEN( ' MYDI R' , ' ut l f i l e. t xt ' , ' a' ) ;
OPEN user s;
LOOP
FETCH user s I NTO v_user name;
EXI T when user s%NOTFOUND;
n : = n + 1;
/ * Wr i t e a l i ne of t ext t o t he f i l e ut l f i l e. t xt */
UTL_FI LE. PUT_LI NE( f Handl e, n | | chr ( 9) | | v_user name) ;
/ * Read a l i ne f r omt he f i l e ut l t ext . t xt */
- - UTL_FI LE. GET_LI NE( f Handl e, v_user name| | v_f ai l ed| | v_l i f e| | v_l ock) ;
END LOOP;
CLOSE user s;
UTL_FI LE. FCLOSE( f Handl e) ;
EXCEPTI ON
WHEN UTL_FI LE. I NVALI D_PATH THEN
RAI SE_APPLI CATI ON_ERROR( - 20100, ' I nval i d Pat h' ) ;
WHEN UTL_FI LE. I NVALI D_MODE THEN
RAI SE_APPLI CATI ON_ERROR( - 20101, ' I nval i d Mode' ) ;
WHEN UTL_FI LE. I NVALI D_OPERATI ON t hen
RAI SE_APPLI CATI ON_ERROR( - 20102, ' I nval i d Oper at i on' ) ;
WHEN UTL_FI LE. I NVALI D_FI LEHANDLE t hen
RAI SE_APPLI CATI ON_ERROR( - 20103, ' I nval i d Fi l ehandl e' ) ;
WHEN UTL_FI LE. WRI TE_ERROR t hen
RAI SE_APPLI CATI ON_ERROR( - 20104, ' Wr i t e Er r or ' ) ;
WHEN UTL_FI LE. READ_ERROR t hen
RAI SE_APPLI CATI ON_ERROR( - 20105, ' Read Er r or ' ) ;
WHEN UTL_FI LE. I NTERNAL_ERROR t hen
RAI SE_APPLI CATI ON_ERROR( - 20106, ' I nt er nal Er r or ' ) ;
WHEN OTHERS THEN
UTL_FI LE. FCLOSE( f Handl e) ;
Page 227 Oracle DBA Code Examples

END;
/

Page 228 Oracle DBA Code Examples

Data Loading and Transforming Tools
Oracles ETL (Extraction-Transformation-Loading) solution includes the following components:
SQL*Loader: see the section Using SQL*Loader Utility in Oracle Database Utilities part.
External tables: see Managing External Tables
Multitable inserts
Merging Data
Table functions: Table functions produce a set of rows as output. Instead of defining the
transform declaratively in SQL, you define it procedurally in PL/SQL. See Table Functions.
Transportable tablespaces: see Transporting Tablespaces Between Databases
Oracle Warehouse Builder (OWB): OWB offers you a wizard-driven facility to load data into
the database through SQL*Loader, load data from an Oracle database or other databases
such as Sybase, Informix, and Microsoft SQL Server via Oracle Transparent Gateways.
Page 229 Oracle DBA Code Examples

Using Database Links
/ * I nf o about DB Li nks */
sel ect OWNER, DB_LI NK, USERNAME, HOST, CREATED f r omDBA_DB_LI NKS;


/ * Pr i vs */
gr ant CREATE DATABASE LI NK t o hr ;

gr ant CREATE PUBLI C DATABASE LI NK t o hr ;


/ * Pr i vat e */
CONNECT syst em/ syst em_passwd@mydb

CREATE DATABASE LI NK MONI TOR
CONNECT TO hr I DENTI FI ED BY hr
USI NG ' moni t or ' ;

Cr eat e dat abase l i nk or cl 2. net connect t o sa i dent i f i ed by a
usi ng ' ( DESCRI PTI ON=( ADDRESS = ( PROTOCOL = TCP) ( HOST =10. 4. x. x) ( PORT=1521) )
( connect _dat a=( ser vi ce_name=or cl ) ) ) ' ;

/ * Publ i c */
CREATE PUBLI C DATABASE LI NK MONI TOR
CONNECT TO hr I DENTI FI ED BY hr USI NG ' moni t or ' ;
Page 230 Oracle DBA Code Examples

Managing Diagnostic Data
Setting the Automatic Diagnostic Repository Directory
It replaces USER_DUMP_DEST, BACKGROUND_DUMP_DEST and CORE_DUMP_DEST parameters.
Default value: $ORACLE_BASE/diag/rdbms/$INSTANCE_NAME/$ORACLE_SID
If you havent set the ORACLE_BASE variable, the value of the DIAGNOSTIC_DEST parameter defaults
to $ORACLE_HOME/log.
show par amet er DI AGNOSTI C_DEST

SELECT VALUE FROM V$PARAMETER WHERE NAME =' di agnost i c_dest ' ;

ALTER SYSTEM SET DI AGNOSTI C_DEST =' C: \ ORACLE\ di ag' ;

SELECT NAME, VALUE FROM V$DI AG_I NFO;
Using adrci Tool
General usage of adrci
adr ci hel p
adr ci >hel p

adr ci >hel p show i nci dent

- - r unni ng adr ci i n bat ch mode
adr ci exec ' command [ ; comamnd] . . . '
adr ci scr i pt =f i l e_name


adr ci >show base

adr ci >show homes
adr ci >show homepat h
adr ci >set homepat h di ag\ r dbms\ or a11g\ or a11g


- - spool i ng
adr ci >spool / u01/ myf i l es/ myadr ci . t xt
adr ci > . . .
adr ci >spool of f


- - vi ew al er t l og
set edi t or not epad. exe
show al er t
Page 231 Oracle DBA Code Examples

show al er t t ai l 30
show al er t p " MESSAGE TEXT LI KE ' %ORA- 600%' *


- - Li st Tr ace Fi l es
show t r acef i l e


- - Vi ew I nci dent s
show i nci dent
show i nci dent mode det ai l p " i nci dent _i d=112564"
Using adrci to Package Incidents
With adr ci tool, you can package all the diagnostic files related to specific problems into a ZIP file to
submit it to Oracle support. To do so, you use special commands called IPS as shown in the following
steps:
1. Create a logical package: use i ps cr eat e package command to create an empty logical package as
shown in the example below. The package will be given a serially generated number.
adr ci >i ps cr eat e package
2. Add diagnostic data to the logical package: this is done by i ps add i nci dent command as shown
below:
adr ci >i ps add i nci dent 112564 package 1
Actually, there are formats of the i ps cr eat e package command which enables you to perform the
steps 1 and 2 in one command. Following are those command formats:
o i ps cr eat e package pr obl em
o i ps cr eat e package pr obl emkey
o i ps cr eat e package i nci dent
o i ps cr eat e package t i me
3. Generate the physical package. The files related to the incident will be collected in a ZIP file. The
following example shows the command to perform this task:
adr ci >i ps gener at e package 1 i n / u01/ myf i l es/ i nci dent s
If you decide to add or change any diagnostic data later, you can do so by generating an incremental
ZIP file. Modify the command as follows to achieve that:
adr ci >i ps gener at e package 1 i n / u01/ myf i l es/ i nci dent s i ncr ement al
You will notice that the generated file has the phase INC in its name indicating that it is an
incremental ZIP file.
i ps commands behavior is controlled by various configuration options. To display those configuration
options, use the command i ps show conf i gur at i on.
Managing Database Health Monitor
To display list of the check that can be performed, issue the following query:
SELECT NAME, DESCRI PTI ON, OFFLI NE_CAPABLE FROM V$HM_CHECK;
Page 232 Oracle DBA Code Examples

The OFFLI NE_CAPABLE column defines whether you can perform the check when the database is offline or
not.
Running Health Checks Using the DBMS_HM
A DBA can use DBMS_HMto manually invoke the database check. To retrieve the list of checks that can be
run manually by users, issue the following query:
SELECT NAME FROM V$HM_CHECK WHERE I NTERNAL_CHECK = ' N' ;
Use the procedure RUN_CHECK to perform a database health check. Its first parameter CHECKNAME is
mandatory and it takes one of the returned names by the query above.
exec DBMS_HM. RUN_CHECK( CHECK_NAME=>' DB St r uct ur e I nt egr i t y Check' , RUN_NAME=>' HM01' ) ;
Most health checks accept input parameters. You can view parameter names and descriptions with the
V$HM_CHECK_PARAMview. Some parameters are mandatory while others are optional. The following query
displays parameter information for all health checks:
sel ect C. NAME CHECK_NAME, P. NAME PARAMETER_NAME, P. TYPE,
P. DEFAULT_VALUE, P. DESCRI PTI ON
f r om V$HM_CHECK_PARAM P, V$HM_CHECK C
wher e P. CHECK_I D = C. I D and C. I NTERNAL_CHECK = ' N'
or der by C. NAME;
Input parameters are passed to the I NPUT_PARAMS argument of the RUN_CHECK procedure as name/value
pairs separated by semicolons (;). The following example illustrates how to pass the transaction ID as a
parameter to the Transaction Integrity Check:
begi n
DBMS_HM. RUN_CHECK (
CHECK_NAME => ' Tr ansact i on I nt egr i t y Check' , - - passed val ue i s case
sensi t i ve
RUN_NAME => ' MY_RUN' , I NPUT_PARAMS => ' TXN_I D=7. 33. 2' ) ;
end;
Database Health checks executions are stored in ADR and can be viewed by either querying the
V$HM_RUN:
SELECT * FROM V$HM_RUN;
Another option is to run the adr ci command show hm_r un:
adr ci >show hm_r un
You can view a report of a particular Health check by using the following adr ci command:
adr ci >show r epor t hm_r un HM01
Alternatively, you can DBMS_HMpackage as shown in the following code example:
decl ar e
v_r pt cl ob;
begi n
v_r pt : = DBMS_HM. GET_RUN_REPORT( ' HM01' ) ;
end;
Findings, if any, detected by the checks can be obtained from V$HM_FI NDI NG and recommendations from
V$HM_RECOMMENDATI ON.
Running Health Checks Using the Enterprise Manager
After connecting as SYSDBA, under the Advisor Central page, you will see Checkers link which can be
used to manually invoke any Health check.
Page 233 Oracle DBA Code Examples

Managing Data Recovery Advisor
Data Recovery Advisor is an Oracle Database 11g tool that automatically diagnoses data failures,
determines and presents appropriate repair options, and executes repairs at the user's request. Data
Recovery Advisor can diagnose failures such as the following:
Inaccessible components like datafiles and control files.
Physical corruptions such as block checksum failures and invalid block header
Field values
Inconsistent datafiles (online and offline)
I/O failures
The advisor however doe not recover from failures on standby databases or RAC environment. This
advisor can be used through RMAN or the Enterprise Manager.
Using Data Recovery Advisor with RMAN
Following are the RMAN commands to use Data Recovery Advisor:
1. List failures by running the LI ST FAI LURE command. Following are variations of using the command:
RMAN>LI ST FAI LURE;
RMAN>LI ST OPEN;
RMAN>LI ST CLOSED;
2. Optionally, execute LI ST FAI LURE . . . DETAI L to list details of an individual failure.
RMAN>LI ST FAI LURE 105 DETAI L;
3. If you suspect that failures exist that have not been automatically diagnosed by the database, then
run VALI DATE DATABASE to check for corrupt blocks and missing files. If a failure is detected, then
RMAN logs it into the ADR, where it can be accessed by the Data Recovery Advisor.
4. Determine repair options by running the ADVI SE FAI LURE command.
RMAN>ADVI SE FAI LURE;
5. Choose a repair option. You can repair the failures manually or run the REPAI R FAI LURE command to
fix them automatically. By default, the REPAI R FAI LURE command prompts the user to confirm the
repair, but this can be prevented using the NOPROMPT keyword. Be aware that the previous command
must be issued before using REPAI R FAI LURE command.
The following form of the command informs you how RMAN plans to repair the failure:
RMAN>REPAI R FAI LURE PREVI EW
6. You may wish to change the priority of a failure (to HI GH or LOW), if it does not represent a problem to
you, or even manually close it. This can be done by the CHANGE FAI LURE command:
RMAN> CHANGE FAI LURE 202 PRI ORI TY LOW;

Note
Data Recovery Advisor may detect or handle some logical corruptions. But in general,
corruptions of this type require help from Oracle Support Services.
Using Data Recovery Advisor with the Enterprise Manager
Access the Data Recovery Advisor in the Enterprise Manager by following the links: Availability>
Manage> Perform Recovery> Perform Automated Repair
Using SQL Test Case Builder
The SQL Test Case Builder aims at capturing the information pertaining to a SQL-related problem, along
with the exact environment under which the problem occurred, so that the problem can be reproduced
Page 234 Oracle DBA Code Examples

and tested on a separate Oracle database instance. Once the test case is ready, you can upload the
problem to Oracle Support to enable support personnel to reproduce and troubleshoot the problem.
The information gathered by SQL Test Case Builder includes the query being executed, table and index
definitions (but not the actual data), PL/SQL functions, procedures, and packages, optimizer statistics,
and initialization parameter settings.
The output of the SQL Test Case Builder is a SQL script that contains the commands required to recreate
all the necessary objects and the environment.
Accessing SQL Test Case Builder Using DBMS_SQLDIAG
The DBMS_SQLDI AG has a procedure named EXPORT_SQL_TESTCASE which is used to generate a SQL test
case for a given SQL statement, SQL Id (taken from V$SQL) or an incident id. Following steps should be
followed:
1. Create directory to hold the SQL test case files.
CREATE DI RECTORY sql _t es_di r AS ' C: \ Or acl e\ Test Case' ;
2. Execute the proper form of EXPORT_SQL_TESTCASE procedure. Following is an example using a passed
SQL statement.
DECLARE
V_SQL CLOB : = ' SELECT * FROM HR. NAMES WHERE I D BETWEEN 100 AND 1000' ;
V_TESTCASE CLOB;
BEGI N
DBMS_SQLDI AG. EXPORT_SQL_TESTCASE (
DI RECTORY =>' SQL_TES_DI R' ,
SQL_TEXT =>V_SQL,
USER_NAME =>' HR' ,
BI ND_LI ST =>NULL,
EXPORTENVI RONMENT =>TRUE,
EXPORTMETADATA =>TRUE,
EXPORTDATA =>TRUE,
SAMPLI NGPERCENT =>100,
CTRLOPTI ONS =>NULL,
TI MELI MI T =>0,
TESTCASE_NAME =>' RETURN_NAMES' , - - gener at ed scr i pt s pr ef i x
TESTCASE =>V_TESTCASE) ;
END;
Accessing SQL Test Case Builder Using the Enterprise Manager
From Enterprise Manager, the SQL Test Case Builder is accessible only when a SQL incident occurs. SQL-
related problem is referred to as a SQL incident.
To access the SQL Test Case Builder, follow the links the Support Workbench page> Click on an
incident ID> Investigate and Resolve section> Oracle Support> Generate Additional Dumps
and Test Cases> click on the icon in the Go To Task.
Page 235 Oracle DBA Code Examples

Patching Oracle Products
Using Oracle Opatch
References
Oracle Universal Installer and OPatch User's Guide
On metalink: OPatch Utility Guide - 10.2 [ID 554417.1]

How to Download It
On metalink, search Patch 6880880.
At document writing, it is on:
https://updates.oracle.com/ARULink/PatchDetails/process_form?patch_num=6880880

Environment Variables OPatch Uses
ORACLE_HOME - Oracle home location.
OPATCH_DEBUG - Log level that specifies the amount of logging OPatch should perform.
OPATCH_PLATFORM_ID - Unique platform ID.
PATH - Path information.

Backup Recommendations
It is highly recommended that you back up the ORACLE_HOME before any patch operation. You can use
any method, such as zip, cp -r, tar, and cpio.

Info about a Utility
To find out more about the options available with each command, please use the following syntax:
opat ch ut i l <Ut i l i t y_Name> - hel p

lsinventory
It is used to check what is currently installed on the system.

opat ch l si nvent or y - det ai l
t o l i st al l avai l abl e Or acl e homes:
opat ch l si nvent or y - al l

NApply
It is used to apply a set of patches under a directory.
opatch napply <patch_location> -id 1,2,3 -skip_subset -skip_duplicate

This will apply patches 1, 2, and 3 which are under < the patch_location> directory. OPatch will skip
duplicate patches and subset patches (patches under <patch_location> that are subsets of patches
installed in the ORACLE_HOME)

NRollback
It is used to rollback a set of patches installed in an ORACLE_HOME. You can invoke the command using
"opatch nrollback" or "opatch util nrollback".

opatch nrollback -id 1,2,3

UpdateRemoteNodes (RAC)
It is used to propagate/remove files/directories to/from remote nodes using files under
ORACLE_HOME/.patch_storage/<ID>/rac/*.

The directories listed in copy_dirs.txt will be copied to remote nodes.
The files listed in copy_files.txt wil be copied to remote nodes.
The directories listed in remove_dirs.txt will be deleted from remote nodes.
Page 236 Oracle DBA Code Examples

The files listed in remove_files.txt will be deleted from remote nodes.

Cleanup
It is used to clean up 'restore.sh, make.txt' files and 'rac, scratch, backup' directories in the
ORACLE_HOME/.patch_storage directory. If -ps option is used, then it cleans the above specified areas
only for that patch, else for all patches under ORACLE_HOME/.patch_storage. You will be still able to
rollback patches after this cleanup.

opatch util cleanup -ps 6121193_Jun_21_2008_04_19_82

CopyListedFiles (RAC)
It is used to copy all files listed in ORACLE_HOME/.patch_storage/<ID>/rac/copy_files.txt to remote
nodes. If -fp option is used, then one can specify the path of the file containing the list of files to be
copied. The files mentioned in this file will be copied to the remote nodes.

opatch util copylistedfiles -fp a -remote_nodes ceintcb-a5

CopyListedFilesTest (RAC)
It is used to copy a single file to remote nodes. The usage remains the same as CopyListedFiles.

opatch util copylistedfilestest -fp /home/oracle/a -remote_nodes ceintcb-a5

CopyListedDirs (RAC)
It is used to recursively copy all directories listed in
ORACLE_HOME/.patch_storage/<ID>/rac/copy_dirs.txt to remote nodes. If -dp option is used, then one
can specify the path of the file containing the list of directories to be copied. The directories mentioned in
this file will be copied to the remote nodes.

CopyListedDirsTest (RAC)
It is used to copy a single file to remote nodes. The usage remains the same as CopyListedDirs.

RemoveListedFiles (RAC)
It is used to remove files listed in ORACLE_HOME/.patch_storage/<ID>/rac/remove_files.txt on remote
nodes. If -fr option is used, then one can specify the path of the file containing the list of files to be
removed. The files mentioned in this file will be removed from the remote nodes.

RemoveListedFilesTest (RAC)
It is used to remove a single file from remote nodes. The usage remains the same as RemoveListedFiles.

RemoveListedDirs (RAC)
It is used to recursively remove directories listed in
ORACLE_HOME/.patch_storage/<ID>/rac/remove_dirs.txt from remote nodes. If -dr option is used, then
one can specify the path of the file containing the list of directories to be removed. The directories
mentioned in this file will be removed from the remote nodes.

RemoveListedDirsTest (RAC)
It is used to remove a single directory from remote nodes. The usage remains the same as
RemoveListedDirs.

RunLocalMake
It is used to invoke re-link on the local node. The make commands are stored in
ORACLE_HOME/.patch_storage/<ID>/make.txt. You need to use the -ps option to specify the Patch ID
with timestamp. A directory by this name will be present under ORACLE_HOME/.patch_storage. The
make.txt file present under ORACLE_HOME/.patch_storage/Patch ID with timestamp/ will be used to
perform the local make operation. This command cannot be run if you have already run Cleanup as it
would have removed these make.txt files.

Page 237 Oracle DBA Code Examples

opatch util runlocalmake -ps 6121250_Jun_21_2007_04_16_11

RunRemoteMake (RAC)
It is used to invoke re-link on remote nodes. The make commands are stored in
ORACLE_HOME/.patch_storage/<ID>/rac/makes_cmd.txt. The usage remains the same as RunLocalMake.

RunAnyCommand (RAC)
It is used to run any command on remote nodes. The command should be specified using the -cmd option.

opatch util runanycommand -remote_nodes ceintcb-a5 -cmd ls

Verify
It is used to run the patch verification process to ensure that the patch was applied to the ORACLE_HOME.
It uses the defined ORACLE_HOME and the given patch location via -ph, to run the check.

opatch util verify -ph ~/6646853/6121183
LoadXML
It is used to check the validity of an XML file. The -xmlInput option can be used to specify the path of the
xml file.

opatch util loadxml -xmlInput $ORACLE_HOME/inventory/ContentsXML/comps.xml


Page 238 Oracle DBA Code Examples

Part 2 Oracle Database Net Services
Page 239 Oracle DBA Code Examples

Connectivity Naming Methods
The Local Naming Method
The TNS_ADMIN environment variable tells Oracle where to locate tnsnames.ora and
sqlnet.ora files.
/ * St ar t i ng Or acl e Net Conf i gur at i on Assi st ant */
expor t DI SPLAY=172. 16. 14. 15: 0. 0
net ca
The Easy Connect Naming Method
The EZCONNECT keyword should be in the NAMES.DIRECTORY_PATH variable in the
sqlnet.ora file
You cant use any advanced features of Oracle networking such as connection pooling,
external procedure calls, or Heterogeneous Services.
sql pl us syst em/ syst em_passwd@myhost . myor g. or g: 1521/ mydb. myor g. or g
# t he def aul t por t number i s 1521
sql pl us syst em/ syst em_passwd@myhost . myor g. or g/ mydb. myor g. or g
The External Naming Method
The external naming method uses external naming services such as the Network Information
Service (NIS), originally developed by Sun Microsystems, to resolve net service names.
1. Have your system administrator configure NIS if it isnt already in place.
2. Create a tnsnames.ora file as you would in the local naming method.
3. Convert the tnsnames.ora file to a tnsnames map, which youll need for the NIS server
later
on. You can derive the tnsnames map from the tnsnames.ora file by having your system
administrator use the tns2nis command, as shown here:
# t ns2ni s t nsnames. or a
4. Copy the tnsnames map file to the server on which the NIS is running.
5. Install the tnsnames map file on the NIS server using the makedbm NIS program, as
shown
here:
# makedbmt nsnames / var / yp/ ' domai nname' / t nsnames
6. Test the NIS installation of the tnsnames map by using the following command:
# ypmat ch net _ser vi ce_name t nsnames
You should get a confirmation back in the following form:
descr i pt i on=( addr ess=( pr ot ocol =t cp)
( host =host _name) ( por t =por t _number ) ) )
( connect _dat a=( ser vi ce_name=ser vi ce_name) ) )
Page 240 Oracle DBA Code Examples

7. Edit the sqlnet.ora file as follows:
NAMES_DI RECTORY_PATH=( ni s, host name, t nsnames)
The nis method should be listed first inside the brackets so that Oracle Net will attempt to
resolve the service name using NIS first. Apart from that, the order of the items in the
brackets doesnt matter.
The Directory Naming Method
The directory naming method stores database connection information in a Lightweight
Directory Access Protocol (LDAP)compliant directory server (like Oracle Internet Directory).
The connect identifiers are stored under an Oracle context that contains entries for use with
OID.
Database Resident Connection Pooling (DRCP)
DRCP (11g) is especially designed to help architectures such as PHP with the Apache
server, that cant take advantage of middle-tier connection pooling because they used
multiprocess single-threaded application servers. DRCP enables applications such as these
to easily scale up to server connections in the tens of thousands.
DRCP is controlled by the following configuration parameters:
INACTIVITY_TIMEOUT maximum idle time for a pooled server before it is terminated.
MAX_LI FETI ME_SESSI ON time to live TTL duration for a pooled session.
MAX_USE_SESSI ON maximum number of times a connection can be taken and released to the
pool.
MAX_SI ZE and MI N_SZI E the maximum and minimum number of pooled servers in the connections
pool.
I NCRSI ZE pool would increment by this number of pooled server when pooled server
are unavailable at application request time.
MAX_THI NK_TI ME maximum time of inactivity by the client after getting a server from the
pool. If the client does not issue a database call after grabbing a server
from the pool, the client will be forced to relinquish control of the pooled
server and will get an error. The freed up server may or may not be
returned to the pool.
SESSION_CACHED_CURSORS turn on SESSI ON_CACHED_CURSORS for all connections in the pool. This is
an existing initialization parameter
/ * Enabl i ng and Di sabl i ng DRCP */
conn sys as sysdba
- - t he r ami ns open af t er DB r est ar t
exec dbms_connect i on_pool . st ar t _pool ( ) ;
sel ect connect i on_pool , st at us, maxsi ze f r omdba_cpool _i nf o;
exec dbms_connect i on_pool . st op_pool ( ) ;

- - speci f y usi ng DRCP
- - i n EZCONNECT met hod ( . Net 11g)
myhost . comany. com: 1521/ mydb. company. com: POOLED
- - t nsnames
mydb = ( DESCRI PTI ON=( ADDRESS=( PROTOCOL=t cp) ( HOST=myhost . company. com)
( SERVER=POOLED) ) )
Page 241 Oracle DBA Code Examples


/ * Conf i gur i ng DRCP */
begi n
DBMS_CONNECTI ON_POOL. ALTER_PARAM( PARAM_NAME =>' I NACTI VI TY_TI MEOUT' ,
PARAM_VALUE=>' 3600' ) ;
end;
/
- - r est or e par amet er val ues t o t hei r def aul t s
exec dbms_connect i on_pool . r est or e_def aul t s( )

/ * Moni t or DRCP */
SELECT
STATUS, MI NSI ZE, MAXSI ZE, I NCRSI ZE, SESSI ON_CACHED_CURSORS, I NACTI VI TY_TI MEOUT
FROM DBA_CPOOL_I NFO;

SELECT NUM_OPEN_SERVERS, NUM_BUSY_SERVERS, NUM_REQUESTS, NUM_HI TS
NUM_MI SSES, NUM_WAI TS, NUM_PURGED, HI STORI C_MAX
FROM V$CPOOL_STATS;
- - cl ass- l evel st at s
Sel ect * Fr omV$CPOOL_CC_STATS
Page 242 Oracle DBA Code Examples

Oracle and Java Database Connectivity
Establishing Database Connectivity
JDBC driver types:
o JDBC thin driver
o JDBC OCI driver
o JDBC server-side thin driver
o JDBC server-side internal driver
- - l oad t he dr i ver s
- - met hod 1
Dr i ver Manager . r egi st er Dr i ver ( " new or acl e. j dbc. Or acl eDr i ver ( ) " ) ;
- - met hod 2
Cl ass. f or Name( " or acl e. j dbc. dr i ver . Or acl eDr i ver " ) ;

- - est abl i sh t he connect i on
connect i on conn=Dr i ver Manager . get Connect i on(
" j dbc: or acl e: t hi n: @pr od1: 1521: f i npr od" , user name, passwd) ;

- - Cr eat i ng t he St at ement Obj ect
st at ement st mt = conn. cr eat eSt at ement ( ) ;

- - Handl i ng Quer i es
st r i ng f i r st _name, l ast _name;
number sal ar y;
r esul t Set r s = st mt . execut eQuer y( " SELECT * FROM Empl oyees" ) ;
whi l e ( r s. next ( ) ) {
f i r st _name = r s. get St r i ng( " f i r st _name" ) ;
l ast _name = r s. get St r i ng( " l ast _name" ) ;
sal ar y = r s. get Number ( " sal ar y" ) ;
syst em. out . pr i nt l n( f i r st _name + l ast _name +" wi t h sal ar y of : " + sal ar y) ;
}

- - Handl i ng DDL and Nonquer y DML St at ement s
st at ement st mt = conn. cr eat eSt at ement ( ) ;
st mt . execut eUpdat e( " CREATE TABLE Emp" + " ( l ast _name VARCHAR2( 30) , f i r st _name
VARCHAR2( 20) , sal ar y number " ) ;
- - aut o commi t t ed by def aul t
st mt . execut eUpdat e( " I NSERT I NTO Emp " +
" VALUES ( ' Lname' , ' Fname' , sal ar y) " ) ;

- - t r ansact i on cont r ol
conn. set Aut oCommi t ( f al se) ;
conn. commi t ( ) ;
conn. r ol l back( ) ;

- - Er r or Handl i ng
Page 243 Oracle DBA Code Examples

t r y { conn. set Aut oCommi t ( f al se) ;
st mt . execut eUpdat e( " . . " ) ;
conn. commi t ( ) ;
conn. set Aut oCommi t ( t r ue) ;
}
cat ch( SQLExcept i on ex) {
syst em. er r . pr i nt l n( " SQLExcept i on: " + ex. get Message( ) ) ;
conn. r ol l back( ) ;
conn. set Aut oCommi t ( t r ue) ;
}
Page 244 Oracle DBA Code Examples

Miscellaneous Connectivity Options
Setting the Default Connect String
- - i n uni x
expor t TWO_TASK=mydb
- - i n wi ndows: set LOCAL key t o mydb val ue i n t he r egi st r y or :
SET LOCAL=<mydb>

- - l at er you don' t have t o speci f y t he connect st r i ng
sql pl us scot t / t i ger
sql pl us [ [ <opt i on>] [ <l ogon>] [ <st ar t >] ]
Installing the Instant Client
Oracles new Instant Client software allows you to run your applications without installing
the standard Oracle Client or having an ORACLE_HOME.
( 1) Downl oad and i nst al l Or acl e I nst ant Cl i ent sof t war e. You must i nst al l t he
Basi c cl i ent package and t ehn you can al so i ncl ude any of t he advanced
opt i onal packages.
ht t p: / / www. or acl e. com/ t echnol ogy/ sof t war e/ t ech/ oci / i nst ant cl i ent / i ndex. ht ml
( 2) Unzi p t he downl oaded package and copy i t wher ever you l i ke.
( 3) I n Li nux, set LD_LI BRARY_PATH t o i nst ant cl i ent di r ect or y. On Wi ndows, set
PATH t o i nst ant cl i ent
Setting Listener Options
/ * Queue Si ze */
- - concur r ent connect i on r equest s can be made
LI STENER=
( DESCRI PTI ON=
( ADDRESS=( PROTOCOL=t cp) ( HOST=myser ver ) ( PORT=1521) ( QUEUESI ZE=10) ) )

/ * Passwor d */
- - ask f or a passwor d bef or e execut i ng any admi n command
LSNRCTL> set passwor d
LSNRCTL> change_passwor d
Setting Access Controls
- - i n t he sql net . or a
- - onl y t he addr esses i n t he l i st ar e al l owed t o make connect i ons
t cp. val i dnode_checki ng = yes
t cp. i nvi t ed_nodes = ( ser ver 1. us. mycompany. com, 172. 14. 16. 152)
- - addr esses i n t he l i st ar e excl uded
Page 245 Oracle DBA Code Examples

t cp. excl uded_nodes = ( ser ver 1. us. mycompany. com, 172. 14. 16. 152)
Changing Windows Hostname
Step 1 Create Hosts Entry for Old Hostname
Locate your hosts file, typically located at %WINDIR%\system32\drivers\etc\hosts and add an entry for
the old (current) hostname.
#
# HOSTS f i l e
#

wi n2k3r 2 172. 16. 10. 10

Note the IP address this is the address of a Loopback Adapter installed on the guest machine. As
outlined by the Oracle Installer, a Loopback Adapter is required on systems that do not have a static IP
address (as do virtual machines using NAT, etc.)
Step 2 Uninstall Enterprise Manager Console
Because there are configuration settings stored with Enterprise Manager Console that reference the
hostname, the same must be uninstalled.
emca - deconf i g dbcont r ol db - r epos dr op

Note, before executing this command, ensure that the Oracle instance is running it has to be in order for
Enterprise Manager Configuration Assistance to drop the repository and de-configure the Console.
Step 3 Stop All Oracle Services
Once the uninstall of Enterprise Manage Console has completed, stop all Oracle Services on the guest
machine.
iSQL*Plus Service typically named Oracle<OracleHomeName>iSQL*Plus
Oracle Listener Service typically named Oracle<OracleHomeName>TNSListener
Oracle Database Instance Service typically named OracleServer<SID>
Step 4 Update listener.ora and tnsnames.ora
Once all the Oracle services have stopped, update the listener.ora and tnsnames.ora files, located in
%ORACLE_HOME%\network\admin to reflect the desired (new) hostname.
LI STENER =
( DESCRI PTI ON_LI ST =
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = I PC) ( KEY = EXTPROC1) )
( ADDRESS = ( PROTOCOL = TCP) ( HOST = wi n2k3r 2) ( PORT = 1521) )
)
)
DEVBOX =
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = wi n2k3r 2) ( PORT = 1521) )
( CONNECT_DATA =
Page 246 Oracle DBA Code Examples

( SERVER = DEDI CATED)
( SERVI CE_NAME = devbox)
)
)
Step 5 Rename Host and Restart
Now, rename the computer and restart the guest machine.
Step 6 Ensure Oracle Instance is Running
Once the guest machine has started up, log in and ensure the Oracle instance is running using the
following command line (typically required, unless the instance, not the Windows Service, is configured to
auto-start.)
or adi m- st ar t up si d devbox
Step 7 Reinstall Enterprise Manager Console
After ensuring the Oracle instance is running, reinstall Enterprise Manager Console using the following
command line:
emca - conf i g dbcont r ol db - r epos cr eat e
Step 8 Validate Enterprise Manager Console Installation
Lastly, after the successful installation of Enterprise Manager Console, validate the installation by
navigating to the logon page typically http://<hostname>:1158/em/.
Page 247 Oracle DBA Code Examples

Part 3 Oracle Database Backup and
Recovery
Page 248 Oracle DBA Code Examples

Backup Guidelines
Causes of Unplanned Down Time
Software Failures
o Operating system
o Database
o Middleware
o Application
o Network
Hardware Failures
o CPU
o Memory
o Power supply
o Bus
o Disk
o Tape
o Controllers
o Network
o Power
Human Errors
o Operator error
o User error
o DBA
o System admin.
o Sabotage
Disasters
o Fire
o Flood
o Earthquake
o Power failure
o Bombing

Causes of Planned Down Time
Routine Operations
o Backups
o Performance mgmt
o Security mgmt
o Batches
Periodic Maintenance
o Storage maintenance
o Initialization parameters
Page 249 Oracle DBA Code Examples

o Software patches
o Schema management
o Operating system
o Middleware
o Network
New deployments
o HW upgrade
o OS upgrades
o DB upgrades
o MidW upgrades
o App upgrades
o Net upgrades
Oracles Solution to Down Time
Failure Category Failure Sub-Category Solutions
System Failures RAC Data Guard Streams
Fast-start Fault Recovery
RAC Data Guard Streams
Unplanned Down
Time
Data Failures RMAN backup/recovery
ASM
Flashback
Hardware Assisted Resilient Data (HARD)
Data Guard and Streams
System Changes Rolling upgrades
Dynamic provisioning
Planned Down
Time
Data Changes Online redefinition
Minimizing Unplanned Downtime Guidelines
Use RAID data storage with mirroring ( 1+0 is a good choice).
Maintain offsite storage of your backups with a reliable vendor. Make is part of your
recovery testing program.
Normally, for a production database, operating in Archivelog mode is a must.
Multiplex the control files on separate disk drives managed by different disk controllers.
Oracle strongly recommends that you multiplex the redo log file.
After every major structural change, back up the control file. You can take backup of the
control file every hour.
If you backup to a tape, backup to two copies. The media might be defective.
Make auxiliary files part of your backup: (SPFILE) or the init.ora, sqlnet.ora,
tnsnames.ora, password and wallet files.
Log your backup operations.
Make every application has its own tablespace.
Use Data Pump utility for supplemental protection.
Make a plan to make sure that the backups are actually readable and valid.
Page 250 Oracle DBA Code Examples

Make database recovery testing plan.
Always keep a redundancy set online (use flash recovery area for this purpose) so you can
recover faster. A redundancy set has:
o Last backup of all datafiles
o Last backup of the control file
o Multiplexed copies of the current redo log files
o Copies of the current control file
o The archived redo logs since the last backup
o Auxilary files: SPFILE or the init.ora, listener.ora, and tnsnames.ora, pwsd

SLA Sample
Standard Processing Services. The Provider shall furnish and allow access to the processing
environments
listed below:
a. Mid-tier processing.
(1) Applications to be processed:
Financial Information Systems (FIS) to include:
LIST OF FIS APPLICATIONS
Other Departmental Applications
(2) Hours of Availability.
Interactive: Monday-Friday* 07:00-17:00*
Saturday, Sunday and Holidays Not Applicable
*Application will be a web-based 247365 system WITH the exception of the
scheduled
maintenance periods (see below)
Batch: Not applicable
Maintenance: Monthly, Fourth Weekend of Every Month
(3) Standard Processing/Service Requirements.
All of the systems/applications listed in paragraph (1) above are required to be
operational 98% of the total time listed in paragraph (2) above. The Information Systems
Department will provide a method for the Department of Finance to monitor operational
percentages.
(4) Processing of data will be limited to the functionality/processing that was being conducted
at the time of handing over the operations to the Information Services Department.

List Database failure possible reasons or scenarios and the time required to recover for each
reason.
Planning a Backup Strategy Guidelines
If possible, have your required backup files on disks (faster than tapes).
Automatically delete obsolete backups.
If DML load makes it feasible, use incremental backups.
Page 251 Oracle DBA Code Examples

Examples of Backup Schedules for a Database
/ * Exampl e 1 */
# you' l l have: i mage copy of t he dat abase ( L0) ,
# i ncr ement al backup L1
# Ar chi ved r edo l ogs bet ween cur r ent t i me and L0
RUN {
# appl y L1 t o t he speci f i ed dat af i l e i mages
RECOVER COPY OF DATABASE WI TH TAG ' i ncr _updat e' ;
# cr eat e L0 dat af i l e i mages ( f i r st t i me) t hen L1
BACKUP I NCREMENTAL LEVEL 1 FOR RECOVER OF COPY WI TH TAG ' i ncr _updat e'
DATABASE;
}


/ * Exampl e 2 */
# you' l l have i mage copy of db L0, 3 L1s,
# ar chi ved l og bet ween cur r ent t i me and L0
# assumpt i on: Si ze t he f l ash r ecover y ar ea so i t hol ds t hr ee days wor t h of
i ncr ement al backups.
RUN
{
RECOVER COPY OF DATABASE TAG " whol e_db_copy" UNTI L TI ME ' SYSDATE- 3' ;
BACKUP I NCREMENTAL LEVEL 1
FOR RECOVER OF COPY WI TH TAG " whol e_db_copy" DATABASE;
}
Page 252 Oracle DBA Code Examples

User-Managed Backups
Obtaining Database File Information
SELECT name, st at us FROM v$dat af i l e;

SELECT t . name t abl espace, f . name dat af i l e
FROM v$t abl espace t , v$dat af i l e f
WHERE t . t s# = f . t s#
ORDER BY t . name;

SELECT name FROM v$cont r ol f i l e;

sel ect member f r omV$LOGFI LE
Making Whole Closed Database Backups
# 1) shut down t he db
# 2) copy al l db physi cal f i l es: dat af i l es, cont r ol f i l es, r edo l og f i l es,
par amet er f i l e, passwor d f i l e, wal l et f i l e ( i f t her e' s a one) .
Ensur e t hat t he compl et e pat hnames of t he f i l es ar e not ed

#! / bi n/ ksh
ORACLE_SI D=$1
expor t ORACLE_SI D
expor t ORAENV_ASK=NO
BACKUP_DI R=/ u02/ app/ or acl e
. or aenv
sql pl us - s syst em/ mypsswr d << EOF
SET HEAD OFF FEED OFF ECHO OFF TRI MSPOOL ON LI NESI ZE 200
SPOOL / u01/ app/ or acl e/ dba/ col d_backup. ksh
SELECT ' cp ' | | f i l e_name| | ' ${BACKUP_DI R}' f r omsys. dba_dat a_f i l es;
SELECT ' cp ' | | name | | ' ${BACKUP_DI R}' f r omV$cont r ol f i l e;
SELECT ' cp ' | | member | | ' ${BACKUP_DI R}' f r omV$l ogf i l e;
SPOOL OFF;
EXI T;
EOF

# 3) open t he db
Making a Whole Open Backup
#! / bi n/ ksh
ORACLE_SI D=$1
expor t ORACLE_SI D
expor t ORACLE_ASK=NO
BACKUP_DI R=/ u01/ app/ or acl e/ backup
expor t BACKUP_DI R
sql pl us - s " sys/ sys_passwor d as sysdba" << EOF
set l i nesi ze 200
set head of f
set f eed of f
SPOOL / u01/ app/ or acl e/ dba/ hot _backup. ksh
BEGI N
dbms_out put . put _l i ne ( ' al t er dat abase begi n backup; ' ) ;
f or f 1 i n ( sel ect f i l e_name f n f r omsys. dba_dat a_f i l es)
Page 253 Oracle DBA Code Examples

l oop
dbms_out put . put _l i ne( ' host cp ' | | f 1. f n| | ' $BACKUP_DI R' ) ;
end l oop;
dbms_out put . put _l i ne ( ' al t er dat abase end backup; ' ) ;
dbms_out put . put _l i ne( ' al t er dat abase backup cont r ol f i l e t o ' | | '
$BACKUP_DI R/ cont r ol ' | | ' ; ' ) ;
dbms_out put . put _l i ne( ' al t er syst emswi t ch l ogf i l e; ' ) ;
END;
/
SPOOL OFF;
EXI T
EOF
Making Tablespace Backups
# of f l i ne
ALTER TABLESPACE user s OFFLI NE;
copy dat af i l es
ALTER TABLESPACE user s ONLI NE;

# onl i ne
ALTER TABLESPACE sysaux BEGI N BACKUP;
copy dat af i l es
ALTER TABLESPACE sysaux END BACKUP;
Obtaining Backup Status Information
SELECT * FROM v$backup;
Checking Datafiles Taken as Backup
The utility checks only for logical corruption below the HWM.
dbv f i l e=D: \ ORACLE\ ORADATA\ ORA10G\ USERS01. DBF bl ocksi ze=4096
dbv f i l e=D: \ ORACLE\ ORADATA\ ORA10G\ USERS01. DBF bl ocksi ze=8192
Handling Crash Before User-Manged Backup Ends
#1) make sur e t hat one or mor e dat af i l es l ef t i n onl i ne backup mode:
SELECT * FROM v$backup;

#2)
ALTER DATABASE END BACKUP;

#3)
SELECT * FROM v$backup;

#4)
ALTER DATABASE OPEN;
Page 254 Oracle DBA Code Examples

Backing up Control File
# cr eat e a t ext t r ace f i l e:
ALTER DATABASE BACKUP CONTROLFI LE TO TRACE

# bi nar y copy of t he cont r ol f i l e
ALTER DATABASE BACKUP CONTROLFI LE t o ' c: \ t emp\ cont r ol f i l e. ct l '
Backing Up Initialization Files
# cr eat e pf i l e
CREATE SPFI LE=' / u01/ or acl e/ dbs/ t est _spf i l e. or a' FROM
PFI LE=' / u01/ or acl e/ dbs/ t est _i ni t . or a'

# I n Or acl e 11g, wr i t e cur r ent val ues of i nst ance par amet er s
CREATE PFI LE FROM MEMORY;
CREATE SPFI LE FROM MEMORY;
Page 255 Oracle DBA Code Examples

User-Managed Complete Recovery
User-Managed Recovery in NOARCHIVELOG Mode
#( 1
SHUTDOWN ABORT

#( 2
copy dat af i l es, cont r ol f i l es and r edo l og f i l es f r ombackup l ocat i on i nt o t he
or i gi nal dest i nat i ons

#( 3
STARTUP
User-Managed Recovery in NOARCHIVELOG Mode Without Redo Log File
#( 1
SHUTDOWN I MMEDI ATE

#( 2
Rest or e t he most r ecent whol e dat abase backup wi t h oper at i ng syst emcommands.

#( 3 mi mi c i ncompl et e r ecover y:
SQL>RECOVER DATABASE UNTI L CANCEL USI NG BACKUP CONTROLFI LE;
SQL>CANCEL

#4)
SQL> ALTER DATABASE OPEN RESETLOGS;
User-Managed Complete Recovery in ARCHIVELOG Mode
If the lost file is the SYSTEM, UNDO or SYSAUX, the databse will be mostly closed.
# Checki ng st eps:
#I dent i f yi ng dat af i l es t hat need r ecover y
SELECT * FROM v$r ecover _f i l e;
SELECT f i l e_i d f #, f i l e_name,
t abl espace_name t abl espace, st at us
FROM dba_dat a_f i l es;
# Locat i ng Ar chi ved Log Fi l es t o Appl y
SELECT * FROM v$r ecover y_l og;

#1) i f t he dat abase i s cl osed, open mount
STARTUP MOUNT

#2) make sur e t he dat af i l e i s of f l i ne
sel ect f i l e#, name , st at us f r omv$dat af i l e;
ALTER DATABASE dat af i l e ' / di sk2/ dat a/ df 2. dbf ' of f l i ne;

#3) r est or e t he damaged or l ost dat af i l e usi ng os commands
i f i t shoul d be r esot r ed i n a new l ocat i on:
Page 256 Oracle DBA Code Examples

ALTER DATABASE RENAME FI LE ' / ORADATA/ u03/ user s01. dbf '
TO ' / ORADATA/ u04/ user s01. dbf ' ;

#4) i f ar chi ve r edo l og f i l e ar e st or ed i n l ocat i on di f f er ent f r om
l og_ar chi ve_dest _n:
#4. 1) Speci f yi ng t he l ocat i on and name at t he r ecover pr ompt :
Speci f y l og: {<RET>=suggest ed | f i l ename | AUTO | CANCEL}
#4. 2) Usi ng t he ALTER SYSTEM ARCHI VE command:
SQL> ALTER SYSTEM ARCHI VE LOG START TO <new l ocat i on>;
#4. 3) Usi ng t he RECOVER FROM <LOCATI ON> command:
SQL> RECOVER FROM ' <new l ocat i on>' DATABASE
#4. 4)
SQL>SET LOGSOURCE / new_di r ect or y
#4. 5)
ALTER DATABASE RECOVER FROM ' / new_di r ect or y' ;

#5) r ecover t he dat af i l e( s)
RECOVER [ AUTOMATI C] DATABASE
RECOVER [ AUTOMATI C] TABLESPACE <NUMBER> | <NAME>
RECOVER [ AUTOMATI C] DATAFI LE <' f i l ename' > | <NAME>

#6) i f db i s open, t ake t he dat af i l e onl i ne:
ALTER DATABASE DATAFI LE ' / di sk2/ dat a/ df 2. dbf ' ONLI NE;
ALTER TABLESPACE user _dat a ONLI NE;

#7) i f r equi r ed:
ALTER DATABASE OPEN;
Re-Creating Lost Datafiles Without Backup
# i f t he dat abase open:
ALTER TABLESPACE t abl e_dat a OFFLI NE I MMEDI ATE;
# i f t he dat abase i s cl osed, open mount
STARTUP MOUNT
ALTER DATABASE DATAFI LE 4 OFFLI NE;

# r e- cr eat e t he dat af i l e wi t h t he same name:
ALTER DATABASE CREATE DATAFI LE ' / ORADATA/ u03/ user s01. dbf ' ;
#or
#r e- cr eat e t he dat af i l e but wi t h a new f i l ename or l ocat i on:
ALTER DATABASE CREATE DATAFI LE ' / ORADATA/ u03/ user s01. dbf ' AS
' / ORADATA/ u04/ user s01. dbf ' ;

RECOVER TABLESPACE t abl e_dat a;
RECOVER DATAFI LE ' / ORADATA/ u03/ user s01. dbf ' ;

ALTER TABLESPACE t abl e_dat a ONLI NE;
ALTER DATABASE DATAFI LE ' / ORADATA/ u03/ user s01. dbf ' ONLI NE;
Page 257 Oracle DBA Code Examples

User-Managed Incomplete Recovery
Common Situations Requiring Incomplete Recovery
Missing archive
Loss of redo logs
User error
Loss of control files: but you have a backup of an old binary copy
User-Managed Incomplete Recovery Steps
You must have the following to recover:
A valid offline or online backup containing all datafiles.
All archived redo logs, from the restored backup to before the time of failure.
1. Per f or ma f ul l cl osed backup of t he exi st i ng dat abase.

2. Rest or e al l dat af i l es. You may need t o r est or e ar chi ved l ogs.
I f ar chi ve l og changed t o di f f er ent dest i nat i on:
SET LOGSOURCE <LOCATI ON>
STARTUP MOUNT

3. Pl ace t he dat abase i n mount mode and i nsur e t hat t he dat af i l es ar e onl i ne.
SELECT f i l e_i d f #, f i l e_name,
t abl espace_name t abl espace, st at us
FROM dba_dat a_f i l es;

4. Recover t he dat abase.
RECOVER [ AUTOMATI C] DATABASE unt i l . .
unt i l t i me ' YYYY- MM- DD: HH: MI : SS'
unt i l cancel
unt i l scn <i nt eger >
usi ng backup cont r ol f i l e

r ecover dat abase unt i l t i me ' 2002- 03- 09: 11: 44: 00'


5. Open t he dat abase by usi ng t he RESETLOGS opt i on and ver i f y t he r ecover y.
al t er dat abase open r eset l ogs;

Not e: I f l og f i l es need t o be r e- cr eat ed on anot her di sk due t o medi a f ai l ur e,
use t he ALTER DATABASE DROP LOG GROUP and ALTER DATABASE ADD LOG GROUP
commands t o cr eat e t he l og f i l es manual l y.

6. Per f or ma whol e cl osed backup of t he dat abase.
Recovering from Lost Control File by Re-Creating the Control File
ALTER DATABASE BACKUP CONTROLFI LE TO TRACE;
t he command gener at es f i l e i n
<ORACLE_ADR>\ r dbms\ <GSI D>\ <SI D>\ t r ace\ <SI D>_or a_nnn. t r c
The exact f i l e name wi l l al so be f ound i n
<ORACLE_ADR>\ r dbms\ <GSI D>\ <SI D>\ t r ace\ al er t _<SI D>. l og

Page 258 Oracle DBA Code Examples

- - The f ol l owi ng ar e cur r ent Syst em- scope REDO Log Ar chi val r el at ed
- - par amet er s and can be i ncl uded i n t he dat abase i ni t i al i zat i on f i l e.
- -
- - LOG_ARCHI VE_DEST=' '
- - LOG_ARCHI VE_DUPLEX_DEST=' '
- -
- - LOG_ARCHI VE_FORMAT=ARC%S_%R. %T
- -
- - DB_UNI QUE_NAME=" or a11g"
- -
- - LOG_ARCHI VE_CONFI G=' SEND, RECEI VE, NODG_CONFI G'
- - LOG_ARCHI VE_MAX_PROCESSES=4
- - STANDBY_FI LE_MANAGEMENT=MANUAL
- - STANDBY_ARCHI VE_DEST=%ORACLE_HOME%\ RDBMS
- - FAL_CLI ENT=' '
- - FAL_SERVER=' '
- -
- - LOG_ARCHI VE_DEST_10=' LOCATI ON=USE_DB_RECOVERY_FI LE_DEST'
- - LOG_ARCHI VE_DEST_10=' OPTI ONAL REOPEN=300 NODELAY'
- - LOG_ARCHI VE_DEST_10=' ARCH NOAFFI RM NOEXPEDI TE NOVERI FY SYNC'
- - LOG_ARCHI VE_DEST_10=' REGI STER NOALTERNATE NODEPENDENCY'
- - LOG_ARCHI VE_DEST_10=' NOMAX_FAI LURE NOQUOTA_SI ZE NOQUOTA_USED
NODB_UNI QUE_NAME'
- - LOG_ARCHI VE_DEST_10=' VALI D_FOR=( PRI MARY_ROLE, ONLI NE_LOGFI LES) '
- - LOG_ARCHI VE_DEST_STATE_10=ENABLE
- -
- - LOG_ARCHI VE_DEST_1=' LOCATI ON=C: \ or acl e\ or acl edb11g\ RDBMS'
- - LOG_ARCHI VE_DEST_1=' MANDATORY NOREOPEN NODELAY'
- - LOG_ARCHI VE_DEST_1=' ARCH NOAFFI RM EXPEDI TE NOVERI FY SYNC'
- - LOG_ARCHI VE_DEST_1=' NOREGI STER NOALTERNATE NODEPENDENCY'
- - LOG_ARCHI VE_DEST_1=' NOMAX_FAI LURE NOQUOTA_SI ZE NOQUOTA_USED
NODB_UNI QUE_NAME'
- - LOG_ARCHI VE_DEST_1=' VALI D_FOR=( PRI MARY_ROLE, ONLI NE_LOGFI LES) '
- - LOG_ARCHI VE_DEST_STATE_1=ENABLE
- -
- - Bel ow ar e t wo set s of SQL st at ement s, each of whi ch cr eat es a new
- - cont r ol f i l e and uses i t t o open t he dat abase. The f i r st set opens
- - t he dat abase wi t h t he NORESETLOGS opt i on and shoul d be used onl y i f
- - t he cur r ent ver si ons of al l onl i ne l ogs ar e avai l abl e. The second
- - set opens t he dat abase wi t h t he RESETLOGS opt i on and shoul d be used
- - i f onl i ne l ogs ar e unavai l abl e.
- - The appr opr i at e set of st at ement s can be copi ed f r omt he t r ace i nt o
- - a scr i pt f i l e, edi t ed as necessar y, and execut ed when t her e i s a
- - need t o r e- cr eat e t he cont r ol f i l e.
- -
- - Set #1. NORESETLOGS case
- -
- - The f ol l owi ng commands wi l l cr eat e a new cont r ol f i l e and use i t
- - t o open t he dat abase.
- - Dat a used by Recover y Manager wi l l be l ost .
- - Addi t i onal l ogs may be r equi r ed f or medi a r ecover y of of f l i ne
- - Use t hi s onl y i f t he cur r ent ver si ons of al l onl i ne l ogs ar e
- - avai l abl e.
- - Af t er mount i ng t he cr eat ed cont r ol f i l e, t he f ol l owi ng SQL
- - st at ement wi l l pl ace t he dat abase i n t he appr opr i at e
- - pr ot ect i on mode:
- - ALTER DATABASE SET STANDBY DATABASE TO MAXI MI ZE PERFORMANCE
Page 259 Oracle DBA Code Examples

STARTUP NOMOUNT
CREATE CONTROLFI LE REUSE DATABASE " ORA11G" NORESETLOGS NOARCHI VELOG
MAXLOGFI LES 16
MAXLOGMEMBERS 3
MAXDATAFI LES 100
MAXI NSTANCES 8
MAXLOGHI STORY 292
LOGFI LE
GROUP 1 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO01. LOG' SI ZE 50M,
GROUP 2 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO02. LOG' SI ZE 50M,
GROUP 3 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO03. LOG' SI ZE 50M
- - STANDBY LOGFI LE
DATAFI LE
' C: \ ORACLE\ ORADATA\ ORA11G\ SYSTEM01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ SYSAUX01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ UNDOTBS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ USERS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ FDA_TBS. DBF'
CHARACTER SET AR8MSWI N1256
;
- - Commands t o r e- cr eat e i ncar nat i on t abl e
- - Bel ow l og names MUST be changed t o exi st i ng f i l enames on
- - di sk. Any one l og f i l e f r omeach br anch can be used t o
- - r e- cr eat e i ncar nat i on r ecor ds.
- - ALTER DATABASE REGI STER LOGFI LE
' C: \ ORACLE\ FLASH_RECOVERY_AREA\ ORA11G\ ARCHI VELOG\ 2010_03_19\ O1_MF_1_1_%U_. ARC'
;
- - Recover y i s r equi r ed i f any of t he dat af i l es ar e r est or ed backups,
- - or i f t he l ast shut down was not nor mal or i mmedi at e.
RECOVER DATABASE
- - Dat abase can now be opened nor mal l y.
ALTER DATABASE OPEN;
- - Commands t o add t empf i l es t o t empor ar y t abl espaces.
- - Onl i ne t empf i l es have compl et e space i nf or mat i on.
- - Ot her t empf i l es may r equi r e adj ust ment .
ALTER TABLESPACE TEMP ADD TEMPFI LE ' C: \ ORACLE\ ORADATA\ ORA11G\ TEMP01. DBF'
SI ZE 20971520 REUSE AUTOEXTEND ON NEXT 655360 MAXSI ZE 32767M;
- - End of t empf i l e addi t i ons.
- -
- - Set #2. RESETLOGS case
- -
- - The f ol l owi ng commands wi l l cr eat e a new cont r ol f i l e and use i t
- - t o open t he dat abase.
- - Dat a used by Recover y Manager wi l l be l ost .
- - The cont ent s of onl i ne l ogs wi l l be l ost and al l backups wi l l
- - be i nval i dat ed. Use t hi s onl y i f onl i ne l ogs ar e damaged.
- - Af t er mount i ng t he cr eat ed cont r ol f i l e, t he f ol l owi ng SQL
- - st at ement wi l l pl ace t he dat abase i n t he appr opr i at e
- - pr ot ect i on mode:
- - ALTER DATABASE SET STANDBY DATABASE TO MAXI MI ZE PERFORMANCE
STARTUP NOMOUNT
CREATE CONTROLFI LE REUSE DATABASE " ORA11G" RESETLOGS NOARCHI VELOG
MAXLOGFI LES 16
MAXLOGMEMBERS 3
MAXDATAFI LES 100
MAXI NSTANCES 8
MAXLOGHI STORY 292
Page 260 Oracle DBA Code Examples

LOGFI LE
GROUP 1 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO01. LOG' SI ZE 50M,
GROUP 2 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO02. LOG' SI ZE 50M,
GROUP 3 ' C: \ ORACLE\ ORADATA\ ORA11G\ REDO03. LOG' SI ZE 50M
- - STANDBY LOGFI LE
DATAFI LE
' C: \ ORACLE\ ORADATA\ ORA11G\ SYSTEM01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ SYSAUX01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ UNDOTBS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ USERS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G\ FDA_TBS. DBF'
CHARACTER SET AR8MSWI N1256
;
- - Commands t o r e- cr eat e i ncar nat i on t abl e
- - Bel ow l og names MUST be changed t o exi st i ng f i l enames on
- - di sk. Any one l og f i l e f r omeach br anch can be used t o
- - r e- cr eat e i ncar nat i on r ecor ds.
- - ALTER DATABASE REGI STER LOGFI LE
' C: \ ORACLE\ FLASH_RECOVERY_AREA\ ORA11G\ ARCHI VELOG\ 2010_03_19\ O1_MF_1_1_%U_. ARC'
;
- - Recover y i s r equi r ed i f any of t he dat af i l es ar e r est or ed backups,
- - or i f t he l ast shut down was not nor mal or i mmedi at e.
RECOVER DATABASE USI NG BACKUP CONTROLFI LE
- - Dat abase can now be opened zer oi ng t he onl i ne l ogs.
ALTER DATABASE OPEN RESETLOGS;
- - Commands t o add t empf i l es t o t empor ar y t abl espaces.
- - Onl i ne t empf i l es have compl et e space i nf or mat i on.
- - Ot her t empf i l es may r equi r e adj ust ment .
ALTER TABLESPACE TEMP ADD TEMPFI LE ' C: \ ORACLE\ ORADATA\ ORA11G\ TEMP01. DBF'
SI ZE 20971520 REUSE AUTOEXTEND ON NEXT 655360 MAXSI ZE 32767M;
- - End of t empf i l e addi t i ons.
- -
Page 261 Oracle DBA Code Examples

Flash Recovery Area
Obtaining Information on Flash Recovery Area
- - FRA Conf i gur at i on
show par amet er DB_RECOVERY_FI LE_DEST_SI ZE
show par amet er DB_RECOVERY_FI LE_DEST
- - r el at ed par amet er s
show par amet er DB_CREATE_FI LE_DEST
show par amet er LOG_ARCHI VE_DEST_1
show par amet er LOG_ARCHI VE_DEST_2

- - space usage
sel ect NAME, r ound( SPACE_LI MI T/ 1024/ 1024/ 1024, 4) SPACE_LI MI T_GB,
r ound( SPACE_USED/ 1024/ 1024/ 1024, 4) SPACE_USED_GB,
r ound( SPACE_RECLAI MABLE/ 1024/ 1024/ 1024, 4) SPACE_RECLAI MABLE_GB,
NUMBER_OF_FI LES
f r omV$RECOVERY_FILE_DEST;

sel ect FI LE_TYPE, PERCENT_SPACE_USED, PERCENT_SPACE_RECLAI MABLE,
NUMBER_OF_FI LES
f r omV$FLASH_RECOVERY_AREA_USAGE
or der by PERCENT_SPACE_USED desc
Configuring Flash Recovery Area
If configured, LOG_ARCHIVE_DEST and LOG_ARCHIVE_DUPLEX_DEST parameters cannot
be used.
- - conf i gur i ng FRA
ALTER SYSTEM SET DB_RECOVERY_FI LE_DEST_SI ZE = 4G SCOPE=BOTH;
ALTER SYSTEM SET DB_RECOVERY_FI LE_DEST = ' C: \ ORACLE\ RECOVERY_AREA' SCOPE=BOTH
ALTER SYSTEM SET DB_RECOVERY_FI LE_DEST = ' +dskgr p1'

- - r el at ed par amet er s
DB_CREATE_FI LE_DEST = / u02/ t est / or adat a/ dbf i l es/
LOG_ARCHI VE_DEST_1 = ' LOCATI ON=/ u03/ t est / ar c_dest 1'
LOG_ARCHI VE_DEST_2 = ' LOCATI ON=USE_DB_RECOVERY_FI LE_DEST'

- - di sabl e FRA
ALTER SYSTEM SET DB_RECOVERY_FI LE_DEST = ' '

- - 85%war ni ng and 79%cr i t i cal t hr eshol d ar e by def aul t conf i gur ed
Backing Up the Flash Recovery Area
In order to back up the flash recovery area itself using RMAN, you must set CONFIGURE
BACKUP OPTIMIZATION to ON.
Neither of the two commands, BACKUP RECOVERY AREA nor BACKUP RECOVERY FILES,
will back up any permanent files or the flashback logs in the flash recovery area
You can back up the flash recovery area only to a tape device using the following backup
commands:
BACKUP RECOVERY AREA
Page 262 Oracle DBA Code Examples

o This command backs up all flash recovery files in the current or previous flash recovery
area destinations.
o It backs up only those files that have never been backed up to tape before.
o The files that the command will back up include full backups, incremental backups, control
file autobackups, archive logs, and datafile copies.
BACKUP RECOVERY FI LES
This command backs up all the files that the BACKUP RECOVERY AREA command does, but
from all areas on your file system, not just from the flash recovery area.
BACKUP RECOVERY FI LE DESTI NATI ON
Use this command to move disk backups created in the flash recovery area to tape.
Moving the Flash Recovery Area
ALTER SYSTEM SET DB_RECOVERY_FI LE_DEST=' / u01/ app/ or acl e/ new_ar ea' SCOPE=BOTH
Eventually, Oracle will delete all the transient files from the previous flash recovery area
location, when each of them becomes eligible for deletion. However, if you want to move
your current permanent files, transient files, or flashback logs to the new flash recovery
area, you can do so by using the standard file-moving procedures.
If the database flashback logs are enabled and you moved the flash recovery area, the
flashback option should be switched off and on.
Page 263 Oracle DBA Code Examples

Recovery Manager (RMAN)
Using A Media Management Layer (MML) with RMAN
Oracle maintains the Oracle Backup Solutions Program (BSP). The partners are listed in
http://otn.oracle.com/deploy/availability/htdocs/bsp.htm#MMV
Some of the important one are Legato Systems (NetWorker) and VERITAS (NetBackup).
Obtaining Information about and related to RMAN using Dictionary Views
/ * ar chi ves l og f i l es */
- - cr eat ed, backed up, and cl ear ed i n t he dat abase
sel ect
RECI D,
NAME,
DEST_I D,
THREAD#,
SEQUENCE#,
RESETLOGS_CHANGE#,
RESETLOGS_TI ME,
RESETLOGS_I D,
FI RST_CHANGE#,
FI RST_TI ME,
NEXT_CHANGE#,
NEXT_TI ME,
r ound( BLOCKS * BLOCK_SI ZE/ 1024/ 1024, 2) MB ,
CREATOR,
ARCHI VED,
DELETED,
STATUS,
COMPLETI ON_TI ME,
END_OF_REDO,
BACKUP_COUNT,
ARCHI VAL_THREAD#,
I S_RECOVERY_DEST_FI LE,
COMPRESSED,
FAL,
BACKED_BY_VSS
f r omV$ARCHI VED_LOG ;


/ * Backup Set s */
sel ect
RECI D,
STAMP,
SET_STAMP,
SET_COUNT,
BACKUP_TYPE,
CONTROLFI LE_I NCLUDED,
I NCREMENTAL_LEVEL,
PI ECES,
START_TI ME,
COMPLETI ON_TI ME,
ELAPSED_SECONDS,
Page 264 Oracle DBA Code Examples

BLOCK_SI ZE,
I NPUT_FI LE_SCAN_ONLY,
KEEP,
KEEP_UNTI L,
KEEP_OPTI ONS,
MULTI _SECTI ON
f r omV$BACKUP_SET
or der by RECI D;


/ * Backup Pi eces*/
SELECT RECI D,
STAMP,
SET_STAMP, - - l i nk t o V$BACKUP_SET
SET_COUNT,
PI ECE#,
COPY#,
DEVI CE_TYPE,
HANDLE,
COMMENTS,
MEDI A,
MEDI A_POOL,
CONCUR,
TAG,
STATUS,
START_TI ME,
COMPLETI ON_TI ME,
ELAPSED_SECONDS,
DELETED,
BYTES,
I S_RECOVERY_DEST_FI LE,
RMAN_STATUS_RECI D,
RMAN_STATUS_STAMP,
COMPRESSED,
BACKED_BY_VSS,
ENCRYPTED,
BACKED_BY_OSB,
FROM V$BACKUP_PI ECE
ORDER BY SET_STAMP;


/ * Fi l es i n Backup Set s */
- - cont r ol f i l es and dat af i l es i n backup set s f r omt he cont r ol f i l e
sel ect
RECI D,
STAMP,
SET_STAMP,
SET_COUNT BACKUPSET_COUNT,
B. FI LE#,
d. NAME DATAFI LE_NAME,
B. CREATI ON_CHANGE#,
B. CREATI ON_TI ME,
RESETLOGS_CHANGE#,
RESETLOGS_TI ME,
I NCREMENTAL_LEVEL,
I NCREMENTAL_CHANGE#,
B. CHECKPOI NT_CHANGE#,
Page 265 Oracle DBA Code Examples

B. CHECKPOI NT_TI ME,
ABSOLUTE_FUZZY_CHANGE#,
MARKED_CORRUPT,
MEDI A_CORRUPT,
LOGI CALLY_CORRUPT,
DATAFI LE_BLOCKS,
B. BLOCKS,
B. BLOCK_SI ZE,
OLDEST_OFFLI NE_RANGE,
COMPLETI ON_TI ME,
CONTROLFI LE_TYPE,
USED_CHANGE_TRACKI NG,
BLOCKS_READ,
USED_OPTI MI ZATI ON,
B. FOREI GN_DBI D,
B. PLUGGED_READONLY,
B. PLUGI N_CHANGE#,
B. PLUGI N_RESETLOGS_CHANGE#,
B. PLUGI N_RESETLOGS_TI ME,
SECTI ON_SI ZE,
UNDO_OPTI MI ZED
f r omV$BACKUP_DATAFI LE b, V$DATAFI LE d
wher e B. FI LE# ( +) = D. FI LE#
ORDER BY b. CREATI ON_TI ME DESC;


/ * Ar chi ve Log f i l es i n t he Backup Set s */
SELECT
RECI D,
STAMP,
SET_STAMP,
SET_COUNT,
THREAD#,
SEQUENCE#,
RESETLOGS_CHANGE#,
RESETLOGS_TI ME,
FI RST_CHANGE#,
FI RST_TI ME,
NEXT_CHANGE#,
NEXT_TI ME,
r ound( BLOCKS * BLOCK_SI ZE/ 1024/ 1024, 2) MB ,
TERMI NAL
FROM V$BACKUP_REDOLOG
ORDER BY RECI D DESC;

/ * Cor r upt i on */
- - bl ocks have been f ound cor r upt dur i ng a backup of a backup set
sel ect * f r omV$BACKUP_CORRUPTI ON;

- - dat abase bl ocks t hat wer e cor r upt ed af t er t he l ast backup
sel ect * f r om V$DATABASE_BLOCK_CORRUPTI ON
Starting RMAN
expor t ORACLE_SI D=mydb
r man t ar get /
Page 266 Oracle DBA Code Examples

r man t ar get sys/ psw cmdf i l e D: \ . . \ dbl evel 0. or a l og D: \ . . \ dbl evel 0. l og append
r man t ar get / @myr manscr i pt . or a
r man t ar get or cl cat al og r man/ r man@ni ck

# l og par amet er doesn t di spl ay out put t o you. To wor k ar ound:
r man | t ee / u01/ app/ or acl e/ r man. l og

# usi ng dynami c scr i pt : passi ng par amet er s t o command f i l e
# command f i l e may cont ai n:
BACKUP DATABASE TAG &1
FORMAT ' / u02/ or acl e/ bck/ &2%U. bck'
# t he scr i pt r unni ng r man may cont ai n:
expor t f or mat =$2
expor t myt ag=$3
r man @' / u01/ app/ or acl e/ scr i pt s/ my_backup. cmd' USI NG $f or mat $myt ag
# you may r un t he scr i pt as:
myscr i pt . sh db01012010 HR01012010
Using rlwrap Utility with RMAN in Unix-Based Systems
/ * I nst al l */
# Opt i on 1: f or r pmver si on:
# can be downl oaded f r om:
# ht t p: / / r pm. pbone. net
# ht t p: / / i van. kar t i k. sk
r pm- i vh r l wr ap*. r pm


# Opt i on 2: f or t ar ver si on
# downl oad r l wr ap- 0. 30. t ar . gz ( sear ch t he net or f r om
ht t p: / / www. ahmedbar aka. com/ downl oad/ or acl e/ r l wr ap- 0. 30. t ar . gz )
# unzi p t he f i l e and i nst al l
su -
gunzi p r l wr ap- 0. 30. t ar . gz
t ar - xvf r l wr ap- 0. 30. t ar
cd r l wr ap- 0. 30
. / conf i gur e
make
make i nst al l

#
echo " al i as r man2=' r l wr ap r man' " >> / home/ or acl e/ . bashr c
Configuring the RMAN Environment
/ * Handl i ng Conf i gur at i on i n Gener al */
# To l i st cur r ent conf i gur at i on
SHOWALL
# To set val ue f or a conf i gur at i on set t i ng
CONFI GURE CHANNEL DEVI CE TYPE DI SK FORMAT ' / ?/ %U' ;
CONFI GURE CONTROL FI LE AUTOBAKCUP ON
# To r eset t he set t i ng val ue
CONFI GURE CONTROL FI LE AUTOBAKCUP CLEAR

Page 267 Oracle DBA Code Examples

/ * Backup Ret ent i on Pol i cy */
CONFI GURE RETENTI ON POLI CY TO REDUNDANCY 2;
CONFI GURE RETENTI ON POLI CY TO RECOVERY WI NDOWOF 14 DAYS;


/ * Def aul t Devi ce Type */
CONFI GURE DEFAULT DEVI CE TYPE TO sbt ;


/ * Encr ypt i on */
- - Tr anspar ent or Dual mode
CONFI GURE ENCRYPTI ON FOR DATABASE ON


/ * Compr essi on */
CONFI GURE DEVI CE TYPE DI SK BACKUP TYPE TO COMPRESSED BACKUPSET


/ * Def i ni ng Par al l el i sm*/
CONFI GURE DEVI CE TYPE DI SK PARALLELI SM 4;


/ * Conf i gur i ng Def aul t Channel s */
- - number of channel s t o use depends on DI SK PARALLELI SM
CONFI GURE CHANNEL 1 DEVI CE TYPE DI SK FORMAT
' / u01/ or acl e/ or adat a/ backup/ %U' ;
CONFI GURE CHANNEL 2 DEVI CE TYPE DI SK FORMAT
' / u02/ or acl e/ or adat a/ backup/ %U' ;


/ * Backup Opt i mi zat i on */
- - dat af i l e of a ver si on i dent i cal t o i t s backup won' t be backuped up
CONFI GURE BACKUP OPTI MI ZATI ON ON;


/ * Cont r ol Fi l e Aut o- Backup */
CONFI GURE CONTROLFI LE AUTOBACKUP ON;
- - Cont r ol Fi l e Backup Locat i on and For mat
CONFI GURE CONTROLFI LE AUTOBACKUP FORMAT FOR DEVI CE TYPE DI SK TO
' / u01/ or acl e/ or adt a/ backup/ cf _%F' ;


/ * Ar chi vel og Del et i on Pol i cy */
- - al l dest i nat i ons ar e af f ect ed i ncl udi ng f l ash r ecover y ar ea
CONFI GURE ARCHI VELOG DELETI ON POLI CY TO BACKED UP 2 TI MES TO SBT;
RMAN Channel Commands
# Manual Channel Al l ocat i on
RUN {
ALLOCATE CHANNEL c1 TYPE di sk
FORMAT = ' / db01/ BACKUP/ usr 0520. bak' ;
BACKUP DATAFI LE ' / db01/ ORADATA/ user s01. dbf ' ; }

# Aut omat i c Channel Al l ocat i on
CONFI GURE DEFAULT DEVI CE TO DI SK | SBT ;
Page 268 Oracle DBA Code Examples

CONFI GUE DEVI CE TYPE DI SK PARALLELI SM n ;

# Aut omat i c Channel Opt i ons
CONFI GURE CHANNEL DEVI CE TYPE DI SK FORMAT = ' / BACKUP/ RMAN/ %U' ;
CONFI GURE CHANNEL DEVI CE TYPE DI SK MAXPI ECESI ZE 2G ;
Duration in days of RMAN information in Control File
- - i n days
sel ect val ue f r omv$par amet er wher e
upper ( name) =' CONTROL_FI LE_RECORD_KEEP_TI ME' ;

al t er syst emset CONTROL_FI LE_RECORD_KEEP_TI ME=30 ;
Monitoring RMAN Jobs
SELECT SI D, RECI D, STAMP, PARENT_RECI D, PARENT_STAMP, SESSI ON_RECI D,
SESSI ON_STAMP, ROW_LEVEL, ROW_TYPE, COMMAND_I D, OPERATI ON, STATUS,
MBYTES_PROCESSED, START_TI ME, END_TI ME
f r omV$RMAN_STATUS
ORDER BY RECI D DESC;

# t o vi ew message gener at ed by t he RMAN oper at i on
sel ect SI D, RECI D, STAMP, SESSI ON_RECI D, SESSI ON_STAMP, OUTPUT
f r omV$RMAN_OUTPUT;
Using RMAN BACKUP Command
BACKUP command options
FULL
INCREMENTAL LEVEL n
INCLUDE CURRENT CONTROLFILE
FILESPERSET n # maximum number of input files in each backup set
SKIP OFFLINE | READONLY | INACCESSIBLE
MAXSETSIZE n K|M|G
DELETE INPUT # applicable on archived logs, datafile copies or backup sets.
FORMAT :
%c copy number
%p backup piece number
%s backup set number
%d database name
%n database name padded with 8 characters
%t backup set time stamp
%u compressed version of %s and %t
%U (default) equivalent t%u_%p_%c
/ * Backup Pi ece Si ze */
ALLOCATE CHANNEL MAXPI ECESI ZE = i nt eger
CONFI GURE CHANNEL MAXPI ECESI ZE = i nt eger

Page 269 Oracle DBA Code Examples

/ * Backup exampl es */
- - make a whol e dat abase backup
BACKUP DATABASE FORMAT ' / t mp/ %U' TAG=' weekl y_bak'
SQL ' ALTER SYSTEM ARCHI VE LOG CURRENT' ;

- - Backi ng Up Tabl espaces
BACKUP TABLESPACE syst em, user s, t ool s;

- - Backi ng up Dat af i l es and Dat af i l e Copi es
BACKUP DATAFI LE 1, 2, 3, 4, DATAFI LECOPY ' / t mp/ syst em01. dbf '

- - Backi ng Up Backup Set s ( f r omdi sk t o t ape or f r omdi sk t di sk)
BACKUP DEVI CE TYPE sbt BACKUPSET ALL;
Backing Up Control File and SPFile
/ * Cont r ol Fi l e Aut obackup */
CONFI GURE CONTROLFI LE AUTOBACKUP enabl e ;

/ * Cont r ol Fi l e Backup For mat */
SET CONTROLFI LE AUTOBACKUP FORMAT FOR DEVI CE TYPE di sk TO ' cont r ol f i l e_%F' ;
CONFI GURE CONTROLFI LE AUTOBACKUP FORMAT ' . . ' ;

/ * Backi ng Up t he Cont r ol Fi l e Manual l y */
BACKUP CURRENT CONTROLFI LE TAG=' mondaypmbackup' ;

/ * I ncl udi ng t he Cont r ol Fi l e i n a Backup Set */
BACKUP TABLESPACE user s I NCLUDE CURRENT CONTROLFI LE;

/ * Backi ng Up t he Ser ver Par amet er Fi l e */
- - Aut omat i cal l y backed up when CONFI GURE CONTROLFI LE
AUTOBACKUP = ON
- - Expl i ci t l y
BACKUP SPFI LE
Backing Up Archived RedLogs
/ * Usi ng BACKUP ARCHI VELOG command */
BACKUP ARCHI VELOG ALL ;
BACKUP ARCHI VELOG NOT BACKED UP 2 TI MES;

- - To del et e backed up copy of t he ar chi ved l og f i l e
BACKUP ARCHI VELOG ALL DELETE I NPUT ;

- - To del et e l ogs f r omal l enabl ed ar chi vi ng dest i nat i ons.
BACKUP ARCHI VELOG ALL DELETE ALL I NPUT ;

- - To speci f y a r ange of ar chi ved r edl ogs by t i me
BACKUP ARCHI VELOG UNTI L TI ME ' SYSDATE- 7' ;
BACKUP ARCHI VELOG FROM TI ME ' SYSDATE- 30' UNTI L TI ME ' SYSDATE- 7' ;

- - To speci f y a r ange of ar chi ved r edl ogs by SCN
BACKUP ARCHI VELOG UNTI L SCN = 320 ;
BACKUP ARCHI VELOG SCN BETWEEN 205 AND 320 ;
Page 270 Oracle DBA Code Examples


- - To speci f y a r ange of ar chi ved r edl ogs by l og sequence number
BACKUP ARCHI VELOG UNTI L SEQUENCE = 501
BACKUP ARCHI VELOG FROM SEQUENCE i nt eger

/ * Usi ng BACKUP . . . PLUS ARCHI VELOG: */
BACKUP DATABASE PLUS ARCHI VELOG;
Backup in NOARCHIVELOG Mode
1. Shut down cl eanl y
2. Mount t he dat abase.
3. Al l ocat e mul t i pl e channel s, i f not usi ng aut omat i c.
4. Run t he BACKUP command.
Encrypting RMAN Backups
Three possible encryption modes for your backups:
o Transparent mode: It requires Oracle Wallet. It is the default encryption mode.
CONFI GURE ENCRYPTI ON FOR DATABASE ON
o Password mode: It requires you to provide a password. It is best suited for backups
restored at remote locations.
SET ENCRYPTI ON ON I DENTI FI ED BY passwor d ONLY
o Dual mode: It can use either Oracle Wallets or passwords.
After making sure the wallet is open:
SET ENCRYPTI ON ON I DENTI FI ED BY passwor d
If there is no wallet or the wallet is closed:
SET DECRYPTI ON I DENTI FI ED BY passwor d1 {, passwor d2, , passwor dn}
Using Compression in RMAN Backups
Only Backupsets can be compressed:
RMAN> CONFI GURE DEVI CE TYPE DI SK BACKUP TYPE TO COMPRESSED BACKUPSET
RMAN> BACKUP AS COMPRESSED BACKUPSET DATABASE
Using Multiplexed Backup Sets
RMAN can read from two datafiles simultaneously, and then combine the blocks from these
datafiles into a single backup piece.
Multiplexing can be controlled by the following:
o The FILESPERSET parameter on the BACKUP command
o The MAXOPENFILES parameter of the ALLOCATE CHANNEL and CONFIGURE CHANNEL
commands (default is 8)
Using Parallelization of Backup Sets
Parallelization of backup sets is achieved by:
o Configuring PARALLELISM to greater than 1
Page 271 Oracle DBA Code Examples

o allocating multiple channels
o Specifying many files in the BACKUP command
BACKUP
( DATAFI LE 1, 2, 3
FI LESPERSET = 1
CHANNEL ORA_DI SK_1)
( DATAFI LECOPY ' / t mp/ syst em01. dbf ' ,
' / t mp/ t ool s01. dbf '
FI LESPERSET = 2
CHANNEL ORA_DI SK_2) ;

RUN
{
ALLOCATE CHANNEL c1 DEVI CE TYPE sbt PARMS=" ENV=
( BACKUP_SERVER=t ape_ser ver 1) " ;
ALLOCATE CHANNEL c2 DEVI CE TYPE sbt PARMS=" ENV=
( BACKUP_SERVER=t ape_ser ver 2) " ;
BACKUP
( DATAFI LE 1, 2, 3 CHANNEL c1)
( DATAFI LECOPY ' / t mp/ syst em01. dbf ' ,
' / t mp/ t ool s01. dbf ' FI LESPERSET = 2 CHANNEL c2)
}
Using Duplexed Backup Sets (Backupset Copies)
CONFIGURE . . . BACKUP COPIES option (maximum 4)
SET BACKUP COPIES in a RUN block.
The COPIES option in the BACKUP command.
- - BACKUP COPI ES
BACKUP DEVI CE TYPE DI SK COPIES 2 DATAFI LE 1 FORMAT ' / di sk1/ df 1_%U' ,
' / di sk2/ df 1_%U' ;
BACKUP COPI ES 2 DATAFI LE 1, DATAFI LE 2 FORMAT ' / BACKUP1/ %U' , ' / BACKUP2/ %U' ;
BACKUP COPI ES 3 I NCREMENTAL LEVEL = 0 DATABASE;

- - CONFI GURE BACKUP COPI ES
CONFI GURE CHANNEL DEVI CE TYPE DI SK FORMAT ' / save1/ %U' , ' / save2/ %U' ;
CONFI GURE DATAFI LE BACKUP COPI ES FOR DEVI CE TYPE sbt T2;
CONFI GURE ARCHI VELOG BACKUP COPI ES FOR DEVI CE TYPE sbt T2;
Making Image Copies
BACKUP AS COPY..
BACKUP AS COPY DATABASE;
BACKUP AS COPY TABLESPACE SYSAUX;
BACKUP AS COPY DATAFI LE 2;

BACKUP AS COPY COPY OF DATABASE;

BACKUP AS BACKUPSET COPY OF TABLESPACE SYSAUX;

BACKUP AS COPY COPY OF DATAFI LE 2;

- - t o check
Page 272 Oracle DBA Code Examples

l i st backupset of t abl espace t bs1;
In 9i , ( DEPRICATED IN 10G )
COPY DATAFI LE { ' f i l ename' | i nt eger }
| DATAFI LECOPY {' f i l ename' | TAG=' t ag_name' }
| ARCHI VELOG ' f i l ename'
| CURRENT CONTROLFI LE
| CONTROLFI LECOPY {' f i l ename' | TAG=' t ag_name' }
TO AUXNAME | ' f i l ename'
COPY DATAFI LE ' / ORADATA/ user s_01_db01. dbf ' t o ' / BACKUP/ user s01. dbf ' t ag=DF3 ;
Validating Backup
When you run BACKUP VALIDATE, RMAN checks datafiles for physical and logical block
corruption but it does not actually produce any backup sets or image copies.
# onl y dat abase l evel
BACKUP VALI DATE DATABASE ARCHI VELOG ALL;

# db, t abl espace, dat af i l e, bl ock l evel s
VALI DATE BACKUPSET 1;
Incremental Backup
Level 0 or Level 1.
Differential: since last 1 or 0, Cumulative: since last 0 (faster recovery).
BACKUP I NCREMENTAL LEVEL N [ CUMULATI VE]
backup of: DATAFI LE, DATAFI LECOPY, TABLESPACE, or DATABASE.
BACKUP I NCREMENTAL LEVEL 0 . . .
Tags for Backups and Image Copies
BACKUP . . TAG=' t ag_name'
Creating Archival Backups
The BACKUP ... KEEP command can be used to create a backup that is both all-inclusive
(every file needed including archived redo logs) and exempt from the backup retention
policy.
In Oracle 11g, some modifications made on the RMAN BACKUP ... KEEP command. In the
new version of the command, the KEEP, NOKEEP, FOREVER, and UNTIL TIME options are
retained. However, the LOGS and NOLOGS options are not there any longer. Instead, you
have a new option, RESTORE POINT. The RESTORE POINT option lets RMAN automatically
create a normal restore point.
Note: You cant use the KEEP clause for backup files in the flash recovery area. Also, you
cannot use the CHANGE ... KEEP command for backup files stored in the flash recovery area.
RUN
Page 273 Oracle DBA Code Examples

{
ALLOCATE CHANNEL c1 DEVI CE TYPE sbt PARMS
' ENV=( OB_MEDI A_FAMI LY=ar chi val _backup) ' ;
- - wi t h f or ever opt i on ( r ecover y cat al og i s r equi r ed)
BACKUP DATABASE TAG BAKQ108 KEEP FOREVER RESTORE POI NT FY08Q1;
- - backup wi l l be kept f or 365 days ( l ong- t er m)
BACKUP DATABASE TAG BAKQ108 KEEP UNTI L TI ME ' SYSDATE+365' RESTORE POI NT
FY08Q1;
- - Af t er one day, t he backup becomes obsol et e,
- - r egar dl ess t he conf i gur ed r et ent i on pol i cy
BACKUP DATABASE FORMAT ' / u01/ or acl ebck/ %U. bck'
TAG TESTDB KEEP UNTI L ' SYSDATE+1' RESTORE POI NT TESTDB08;
}
If you want to change the status of a regular backup to an archival backup, use the CHANGE command
as follows:
CHANGE BACKUP TAG ' weekl y_bkp' KEEP FOREVER;
- - make i t f ol l ow back t he r et ent i on pol i cy
CHANGE BACKUP TAG ' weekl y_bkp' NOKEEP;
Monitoring RMAN Backups
To correlate a process with a channel during a backup:
1. In each session, set the COMMAND I D to a different value
RUN
{
ALLOCATE CHANNEL c1 TYPE sbt ;
SET COMMAND ID TO 'sess1';
BACKUP DATABASE;
}
2. Query the joined V$SESSI ON and V$PROCESS views
SELECT SI D, SPI D, CLI ENT_I NFO
FROM V$PROCESS p, V$SESSI ON s
WHERE p. ADDR = s. PADDR
AND s. CLI ENT_I NFO LI KE ' %i d=sess%' ;
The CLI ENT_I NFO column displays in the following format:
i d=command_i d, r man channel =channel _i d
3. Query the V$SESSI ON_LONGOPS view to get the status of the backup or copy

SELECT s. SI D, S. SERI AL#, CLI ENT_I NFO, r ound( L. ELAPSED_SECONDS/ 60, 2)
ELAPSED_TI ME_MI N , L. SOFAR, L. TI ME_REMAI NI NG/ 60 TI ME_REMAI NI NG_MI N
FROM V$PROCESS p, V$SESSI ON s, V$SESSI ON_LONGOPS l
WHERE p. ADDR = s. PADDR and L. SI D = s. SI D and L. SERI AL# = s. SERI AL#
AND s. CLI ENT_I NFO LI KE ' %r man%'
AND NVL( L. TI ME_REMAI NI NG, 0) <>0;
RMAN Complete Recovery
Validating Backup Files
You can use VALI DATE Validate backup sets before you use them from a recovery.
You can run RESTORE ... VALIDATE to test whether RMAN can restore a specific file or set
of files from a backup. RMAN chooses which backups to use.
Page 274 Oracle DBA Code Examples

LI ST COPY;
LI ST BACKUP;
LI ST BACKUP RECOVERABLE;

VALI DATE BACKUPSET 1;

- - no r est or e i s act ual l y done
- - l ack of er r or s: val i dat i on f ound no pr obl em
RESTORE DATABASE VALI DATE;
RESTORE ARCHI VELOG ALL VALI DATE;
Previewing Backup Files Required by a Restore
The RESTORE . . . PREVIEW command provides a detailed report of all backups that are
necessary for that RESTORE command to succeed.
RESTORE DATABASE PREVI EW;
RESTORE DATABASE PREVI EWSUMMARY;
RESTORE TABLESPACE user s PREVI EW;
RESTORE DATAFI LE 3 PREVI EW;
Identifying Datafiles Requiring Recovery
SELECT r . FI LE# AS df #, d. NAME AS df _name, t . NAME AS t bsp_name,
d. STATUS, r . ERROR, r . CHANGE#, r . TI ME
FROM V$RECOVER_FI LE r , V$DATAFI LE d, V$TABLESPACE t
WHERE t . TS# = d. TS# AND d. FI LE# = r . FI LE#;
Performing Complete Recovery
- - Recover a Dat abase i n ARCHI VELOG Mode
STARTUP MOUNT;
RESTORE DATABASE;
RECOVER DATABASE;


- - Rest or e Dat af i l es t o a New Locat i on
r un{
set newname f or dat af i l e 1 t o ' / newdi r / syst em01. dbf ' ;
r est or e dat abase;
swi t ch dat af i l e al l ; # r ecor d i n cont r ol f i l e
r ecover dat abase; }
- - al t er nat i vel y:
r un {
sql " al t er t abl espace t bs1 of f l i ne i mmedi at e" ;
set newname f or dat af i l e 6 t o ' C: \ APP\ ADMI NI STRATOR\ ORADATA\ ORA11G\ t bs1. dbf ' ;
r est or e t abl espace t bs1;
swi t ch dat af i l e 6;
r ecover t abl espace t bs1; }
sql " al t er t abl espace t bs1 onl i ne" ;


- - Recover a Tabl espace
r un{
sql " al t er t abl espace user s of f l i ne i mmedi at e" ;
r est or e t abl espace user s;
r ecover t abl espace user s;
sql " al t er t abl espace user s onl i ne" ; }
Page 275 Oracle DBA Code Examples



- - Rel ocat e a Tabl espace
RUN{
SQL " al t er t abl espace user s of f l i ne i mmedi at e" ;
SET NEWNAME FOR DATAFI LE ' / ORADATA/ u03/ user s01. dbf '
TO ' / ORADATA/ u04/ user s01. dbf ' ;
RESTORE TABLESPACE user s;
SWI TCH dat af i l e 3; # Updat e t he cont r ol f i l e and r ecover y cat al og
RECOVER TABLESPACE user s; #Recover t he t abl espace
SQL " al t er t abl espace t bs1 onl i ne" ; }
Restoring whole Database from RMAN Backups On a Different Node
The directory structures can be the same or different
The procedure applies for database in ARCHIVELOG mode or NOARCHIVELOG mode.
Reference: Document ID 419137.1
The f ol l owi ng exampl e assume r est or i ng a dat abase f r omnode1 t o node2.

/ * Move t he f ol l owi ng f i l es t o t he NODE 2 */
+ The dat abase backup pi eces t o l ocat i on ' / node2/ dat abase/ backup'
+ Cont r ol f i l e backup pi ece t o t he l ocat i on ' / node2/ dat abase/ backup'
+ The par amet er f i l e i . e i ni t . or a f i l e t o t he def aul t l ocat i on:
Uni x: $ORACLE_HOME/ dbs
Wi ndows: $ORACLE_HOME/ dat abase


/ * Edi t t he PFI LE on NODE 2 t o change t he envi r onment
speci f i c par amet er s and cr eat e t hi er di r ect or i es */
user _dump_dest =
backgr ound_dump_dest =
cont r ol _f i l es= <- - speci f y t he new l ocat i on of cont r ol f i l es
db_r ecover y_f i l e_dest =


/ * set t he Or acl e envi r onment var i abl es and
st ar t t he dat abase i n nomount mode */
Uni x:
expor t ORACLE_HOME=/ u01/ or acl e/ pr oduct / or a10g
expor t ORACLE_SI D=or a10g
expor t PATH=$ORACLE_HOME/ bi n: $PATH

Wi ndows:
set ORACLE_HOME=D: \ or acl e\ pr oduct \ 10. 1. 0\ db_1
set ORACLE_SI D=or adb
set PATH=D: \ or acl e\ pr oduct \ 10. 1. 0\ db_1\ bi n; %PATH%


/ * Cr eat e a passwor d f i l e: */
Uni x:
$or apwd f i l e=$ORACLE_HOME/ dbs/ or apw$ORACLE_SI D. or a passwor d=*** ent r i es=5
Wi ndows:
or apwd f i l e=%ORACLE_HOME%\ dat abase\ PWD%ORACLE_SI D%. or a passwor d=*** ent r i es=5


/ * I n Wi ndows: cr eat e t he SI D ser vi ce: */
Page 276 Oracle DBA Code Examples

or adi m- NEW- SI D or adb - STARTMODE aut o


/ * i nvoke Rman on t he NODE 2 */
- - i n Wi ndows, i t ' s al r eady st ar t ed so shut down f i r st
r man t ar get /
Recover y Manager : Rel ease 10. 2. 0. 1. 0 - Pr oduct i on on Tue Feb 13 00: 36: 55 2007
Copyr i ght ( c) 1982, 2005, Or acl e. Al l r i ght s r eser ved.
connect ed t o t ar get dat abase ( not st ar t ed)
RMAN> st ar t up nomount pf i l e=X: \ . . \ PFI LE. ORA
Or acl e i nst ance st ar t ed
Tot al Syst emGl obal Ar ea 205520896 byt es
Fi xed Si ze 1218508 byt es
Var i abl e Si ze 75499572 byt es
Dat abase Buf f er s 121634816 byt es
Redo Buf f er s 7168000 byt es


/ * Rest or e t he cont r ol f i l e f r omt he backup pi ece. */
- - cont r ol f i l es wi l l be r esot r ed t o l ocat i ons i ndi cat ed i n pf i l e
RMAN> r est or e cont r ol f i l e f r om
' D: \ t emp\ backup\ ORADB\ AUTOBACKUP\ 2011_07_06\ O1_MF_S_755814486_718GDZ6L_. BKP' ;
St ar t i ng r est or e at 06/ 07/ 11
al l ocat ed channel : ORA_DI SK_1
channel ORA_DI SK_1: si d=380 devt ype=DI SK

channel ORA_DI SK_1: r est or i ng cont r ol f i l e
channel ORA_DI SK_1: r est or e compl et e
out put f i l ename=D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ CONTROL01. CTL
out put f i l ename=D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ CONTROL02. CTL
out put f i l ename=D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ CONTROL03. CTL
Fi ni shed r est or e at 06/ 07/ 11


/ * Mount t he dat abase */
RMAN> al t er dat abase mount ;


/ * Now cat al og t he backup pi eces t hat wer e shi pped f r omNODE 1 */
RMAN> cat al og backuppi ece
' / node2/ dat abase/ backup/ o1_mf _annnn_TAG20070213T002925_2x21m6t y_. bkp' ;
RMAN> cat al og backuppi ece
' / node2/ dat abase/ backup/ o1_mf _annnn_TAG20070213T002825_2x21kbds_. bkp' ;
RMAN> cat al og backuppi ece
' / node2/ dat abase/ backup/ o1_mf _nnndf _TAG20070213T002827_2x21kd12_. bkp' ;

RMAN>cat al og backuppi ece
' D: \ t emp\ backup\ ORADB\ BACKUPSET\ 2011_07_06\ O1_MF_NNNDF_TAG20110706T203113_718G
CL0P_. BKP' ;


/ * I n case of ARCHI VELOGMODE: Get t o know t he l ast sequence avai l abl e i n t he
ar chi vel og backup usi ng t he f ol l owi ng command. */
- - Thi s wi l l hel p us i n r ecover i ng t he dat abase t i l l t hat ar chi vel og.
RMAN > l i st backup of ar chi vel og al l ;
Let us assume t he l ast sequence of l ast ar chi vel og i n t he backup i s 50.


Page 277 Oracle DBA Code Examples

/ * Rename t he Redol ogf i l es, so t hat t hey can be cr eat ed i n new l ocat i ons
t he dat abase i s opened i n r eset l ogs */
SQL>conn sys as sysdba
- - get r egi st er ed f i l es f r omSELECT * FROM V$LOGFI LE
SQL> al t er dat abase r ename f i l e ' / node1/ dat abase/ pr od/ r edo01. l og' t o
' / node2/ dat abase/ pr od/ r edo01. l og' ;
. . . .
. . . .

SQL>al t er dat abase r ename f i l e
al t er dat abase r ename f i l e ' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ REDO01. LOG' t o
' D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ REDO01. LOG' ;
. . . .
. . . .


/ * Now r est or e t he dat af i l es t o new l ocat i ons and r ecover . */
Si nce we ar e r ecover i ng t he dat abase her e t i l l t he ar chi vel og sequence 50 t he
sequence number i n t he SET UNTI L SEQUENCE cl ause shoul d be 50
Not e: I f we ar e r est or i ng t he Rman backups f r omt apes, t hen we shoul d ensur e
t he same medi a manager var i abl es t hat wer e used dur i ng backups ar e mai nt ai ned
dur i ng r est or e t oo. The f ol l owi ng document ar t i cl es gi ves t he i nf or mat i on of
var i ous medi a manager Envi r onment Var i abl es:
NOTE. 312737. 1 RMAN and Speci f i c Medi a Manager s Envi r onment Var i abl es.

Not e: i n NOARCHI VEMOE, omi t r ecover dat abase bel ow
RMAN> r un {
set unt i l sequence 51;
set newname f or dat af i l e 1 t o ' / node2/ dat abase/ pr od/ sys01. dbf ' ;
set newname f or dat af i l e 2 t o ' / node2/ dat abase/ pr od/ undot bs01. dbf ' ;
set newname f or dat af i l e 3 t o ' / node2/ dat abase/ pr od/ sysaux01. dbf ' ;
set newname f or dat af i l e 4 t o ' / node2/ dat abase/ pr od/ user s01. dbf ' ;
set newname f or dat af i l e 5 t o ' / node2/ dat abase/ pr od/ 1. dbf ' ;
set newname f or dat af i l e 6 t o ' / node2/ dat abase/ pr od/ sysaux02. dbf ' ;
set newname f or dat af i l e 7 t o ' / node2/ dat abase/ pr od/ undot bs02. dbf ' ;
r est or e dat abase;
swi t ch dat af i l e al l ;
r ecover dat abase;
al t er dat abase open r eset l ogs;
}


Not e: i n NOARCHI VEMOE, omi t r ecover dat abase bel ow
RMAN> r un {
set newname f or dat af i l e ' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SYSTEM01. DBF'
t o ' D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SYSTEM01. DBF' ;
set newname f or dat af i l e
' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ UNDOTBS01. DBF'
t o ' D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ UNDOTBS01. DBF' ;
set newname f or dat af i l e ' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SYSAUX01. DBF'
t o ' D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SYSAUX01. DBF' ;
set newname f or dat af i l e ' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ USERS01. DBF'
t o D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ USERS01. DBF' ;
set newname f or dat af i l e ' E: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SATBS01. DBF'
t o ' D: \ ORACLE\ PRODUCT\ 10. 1. 0\ DB_1\ ORADB\ SATBS01. DBF' ;
r est or e dat abase;
swi t ch dat af i l e al l ;
al t er dat abase open r eset l ogs;
Page 278 Oracle DBA Code Examples

}


/ * Addd t empf i l e t o t empor ar y t abl espaces */
- - l i st of t empor ar y t abl espaces t hat r equi r e dat af i l es ar e i n al er t f i l e
ALTER TABLESPACE t emp ADD TEMPFI LE ' ..' SI ZE 500M AUTOEXTEND ON NEXT 100M
MAXSI ZE 8G;


/ * Some r ecommended post - r est or e */
- - user cr eat ed j obs wi l l aut omat i cal l y r un i f t hei r schedul ed dat e i s due
- - you may consi der st oppi ng t hem
as j ob owner :
- - t o l i st of t he j obs:
sel ect J OB, BROKEN, SCHEMA_USER, NEXT_DATE, WHAT
f r omdba_j obs;

begi n
dbms_j ob. br oken( 387 , t r ue) ;
commi t ;
end;
/
Restoring whole Database from RMAN Backups from A 32 bit to 64 bit
Reference: Document ID 467676.1
- - f ol l ow al l t he st eps i n t he per vi ous sect i on t i t l ed " Rest or i ng whol e
Dat abase f r omRMAN Backups On a Di f f er ent Node" t i l l you r each t o t he st ep
" Now r est or e t he dat af i l es t o new l ocat i ons and r ecover . "

- - i mpl ement t he st eps i n t hat st ep but change openi ng st at ement as f ol l ows:
ALTER DATABASE OPEN RESETLOGS MIGRATE;

- - al l PL/ SQL obj ect s shoul d be r e- compi l ed
- - af t er openi ng t he dat abase wi t h r eset l ogs:
- - i nval i dat e and al l pl / sql modul es
SQL> @?/ r dbms/ admi n/ ut l i r p. sql

SQL> shut down i mmedi at e;
SQL> st ar t up;
- - r ecompi l es i nval i d obj ect s i n t he dat abase
SQL> @?/ r dbms/ admi n/ ut l r p. sql

SQL> shut down i mmedi at e;
SQL> st ar t up
RMAN Incomplete Recovery
1. Mount the database.
2. The following steps should be followed:
RUN { # mul t i pl e channel s f or par al l el i zat i on
ALLOCATE CHANNEL c1 TYPE DI SK;
ALLOCATE CHANNEL c2 TYPE DI SK; # r ecover unt i l t i me, SCN or sequence
SET UNTI L TI ME = ' 2001- 12- 09: 11: 44: 00' ; SET UNTI L TI ME " t o_dat e( ' 09- 05- 2004
00: 00: 20' , ' dd- mm- yyyy hh24: mi : ss' ) " ; SET UNTI L SEQUENCE 120 THREAD 1; #120 not
i ncl uded
Page 279 Oracle DBA Code Examples

# ALL dat af i l es must be r est or ed
RESTORE DATABASE;
RECOVER DATABASE;
ALTER DATABASE OPEN RESETLOGS; }
3. If using a recovery catalog, register the new incarnation of the database using the command: RESET
DATABASE
4. Perform a whole database backup.

Note: Insure that NLS_LANG and NLS_DATE_FORMAT environment variables are set appropriately.
Note: check the al er t . l og for any errors during recovery.
Note: If you need to restore archived redo log files to a new location use the SE SET ARCHI VELOG
DESTI NATI ON TO <l ocat i on>command.
Simplified Recovery Through Resetlogs
Target: to recovery through current and ancestor database incarnations.
You must reset the current incarnation of the database back to the incarnation to which
your target SCN belongs.
You must use the control file from the older incarnation that contains the target SCN.
Fi nd out t he i ncar nat i on key f or t he i ncar nat i on t hat was cur r ent at t he t i me
you want t o r ecover your dat abase t o.
RMAN>LI ST I NCARNATI ON

St ar t t he dat abase i n t he f ol l owi ng way:
RMAN> STARTUP FORCE NOMOUNT;

Reset t he cur r ent i ncar nat i on:
RMAN> RESET DATABASE TO I NCARNATI ON 2;

Rest or e t he ol d cont r ol f i l e f r oma backup:
RMAN> RESTORE CONTROLFI LE FROM AUTOBACKUP;
RMAN> ALTER DATABASE MOUNT;

Rest or e and r ecover t he dat abase:
RMAN> RESTORE DATABASE;
RMAN> RECOVER DATABASE UNTI L SCN 1000;

Open t he dat abase:
RMAN> ALTER DATABASE OPEN RESETLOGS;
Recovering from Lost Control File using RMAN
I f dat abase i sn' t al r eady shut down:
RMAN>shut down abor t

RMAN>st ar t up nomount

RMAN>RESTORE CONTROLFI LE FROM AUTOBACKUP;

ALTER DATABASE MOUNT;

RECOVER DATABASE;
Page 280 Oracle DBA Code Examples


ALTER DATABASE OPEN RESETLOGS;
Block Media Recovery (BMR)
RMANs BLOCKRECOVER command recovers blocks marked as corrupt in the
V$BACKUP_CORRUPTION and V$COPY_CORRUPTION views.
BMR helps on the following goals:
o Faster recovery time.
o Increased database availability.
BMR can repair only physically corrupted blocks but not the logically corrupted blocks.
- - t ypi cal scenar i o:
ORA_11578: ORACLE dat a bl ock cor r upt ed ( f i l e# 9, bl ock# 21)
ORA=01110: dat a f i l e 9: / u01/ app/ or acl e/ or adat a/ r emor se/ user s_01. dbf '

- - t he command wi l l sear ch f l ashback l ogs t hen backup f i l es
- - speci f i c bl ock
RECOVER DATAFI LE 9 BLOCK 21;

- - al l bl ocks i n V$DATABASE_BLOCK_CORRUPTI ON
RECOVER CORRUPTI ON LI ST;
- - t o quer y whi ch bl ocks r ecover ed:
SELECT * FROM V$DATABASE_BLOCK_CORRUPTI ON;
Trial Recovery
Target: to estimate size of corruption in a recovery process.
It lets you know whether there is corruption and, if there is, the extent of the corruption.
- - You can use t he TEST opt i on f or any RECOVER command
RECOVER DATABASE TEST
RECOVER DATABASE USI NG BACKUP CONTROLFI LE UNTI L CANCEL TEST
RECOVER TABLESPACE user s TEST
RECOVER DATABASE UNTI L CANCEL TEST

- - You can l i mi t t he number of dat a bl ocks t r i al r ecover y can cor r upt i n
memor y:
RECOVER DATABASE TEST ALLOW10 CORRUPTI ON;

SQL> RECOVER DATABASE UNTI L CANCEL TEST;
ORA- 10574: Test r ecover y di d not cor r upt any dat a bl ock
ORA- 10573: Test r ecover y t est ed r edo f r omchange 9948095 t o 9948095
ORA- 10570: Test r ecover y compl et e
Handling Specific Errors During Recovery
ORA-01194 Er r or :
- - - - - - - - - - - - - - - -
- - t hi s er r or may r ai se dur i ng st ar t up a cl oned dat abase
- - r esol ut i on: pr ovi de t he onl i ne r edo l og f i l e t o r ecover

SQL> st ar t up
Page 281 Oracle DBA Code Examples

ORACLE i nst ance st ar t ed.
. .
Dat abase mount ed.
ORA- 01589: must use RESETLOGS or NORESETLOGS opt i on f or dat abase open
SQL> al t er dat abase open nor eset l ogs;
al t er dat abase open nor eset l ogs
*
ERROR at l i ne 1:
ORA- 01588: must use RESETLOGS opt i on f or dat abase open
SQL> al t er dat abase open r eset l ogs;
al t er dat abase open r eset l ogs
*
ERROR at l i ne 1:
ORA- 01194: f i l e 1 needs mor e r ecover y t o be consi st ent
ORA- 01110: dat a f i l e 1: ' C: \ ORACLE\ ORADATA\ MANAGER\ SYSTEM01. DBF'

SQL> RECOVER DATABASE UNTI L CANCEL USI NG BACKUP CONTROLFI LE;
ORA- 00279: change 405719 gener at ed at 06/ 30/ 2008 15: 51: 04 needed f or t hr ead 1
ORA- 00289: suggest i on : C: \ ORACLE\ RDBMS\ ARC00019. 001
ORA- 00280: change 405719 f or t hr ead 1 i s i n sequence #19
Speci f y l og: {<RET>=suggest ed | f i l ename | AUTO | CANCEL}
C: \ ORACLE\ ORADATA\ MANAGER\ REDO03. LOG
Log appl i ed.
Medi a r ecover y compl et e.
SQL> al t er dat abase open r eset l ogs;
Dat abase al t er ed.



ORA-01152 Er r or :
- - - - - - - - - - - - - - - -
- - r esol ut i on: pr ovi de t he onl i ne r edo l og f i l e t o r ecover

ORA- 00289: suggest i on :
/ u01/ app/ or acl e/ admi n/ f i nance/ ar ch/ f i nance/ _0000012976. ar c
ORA- 00280: change 962725326 f or t hr ead 1 i s i n sequence #12976
ORA- 00278:
l ogf i l e' / u01/ app/ or acl e/ admi n/ f i nance/ ar ch/ f i nance/ _0000012975. ar c'
no l onger needed f or t hi s r ecover y
Speci f y l og: {<RET>=suggest ed | f i l ename | AUTO | CANCEL}
ORA- 01547: war ni ng: RECOVER succeeded but OPEN RESETLOGS woul d get er r or bel ow
ORA- 01152: f i l e 1 was not r est or ed f r oma suf f i ci ent l y ol d backup
ORA- 01110: dat a f i l e 1: ' / pase16/ or adat a/ f i nance/ syst em_01. dbf ' ORA- 01112:
medi a r ecover y not st ar t ed
Speci f y l og: {<RET>=suggest ed | f i l ename | AUTO | CANCEL}
/ pase04/ or adat a/ f i nance/ r edo01a. r do
ORA- 00279: change 962746677 gener at ed at 07/ 30/ 2008 04: 33: 52 needed f or t hr ead
1
ORA- 00289: suggest i on :
/ u01/ app/ or acl e/ admi n/ f i nance/ ar ch/ f i nance/ _0000012978. ar c
ORA- 00280: change 962746677 f or t hr ead 1 i s i n sequence #12978
ORA- 00278: l og f i l e ' / pase04/ or adat a/ f i nance/ r edo01a. r do'
no l onger needed f or t hi s r ecover y
Speci f y l og: {<RET>=suggest ed | f i l ename | AUTO | CANCEL}
/ pase04/ or adat a/ f i nance/ r edo02a. r do
Log appl i ed.
Medi a r ecover y compl et e.
Page 282 Oracle DBA Code Examples




ORA-00376 Er r or :
- - - - - - - - - - - - - - - -
r eason: mi ght be dat af i l e or t abl espace bei ng of f l i ne
r esol ut i on: br i ngi ng t he t abl espace or dat af i l e onl i ne

ORA- 00376: f i l e 10 cannot be r ead at t hi s t i me
ORA- 01110: dat a f i l e 10: ' / u01/ app/ or acl e/ r emor se/ dat a_01. dbf '
Configuring Instance Crash Recovery Time (MTTR)
SELECT VALUE FROM V$PARAMETER WHERE UPPER( NAME) =' FAST_START_MTTR_TARGET' ;

- - i n seconds
ALTER DATABASE SET FAST_START_MTTR_TARGET=60;

SELECT r ecover y_est i mat ed_i os, est i mat ed_mt t r , t ar get _mt t r
FROM v$i nst ance_r ecover y;
Working with the Data Recovery Advisor in RMAN
l i st f ai l ur e;
l i st f ai l ur e cr i t i cal ;
LI ST FAI LURE HI GH;
LI ST FAI LURE LOW;
l i st f ai l ur e open;
l i st f ai l ur e cl osed;
l i st f ai l ur e excl ude f ai l ur e 12345;

advi se f ai l ur e;
r epai r f ai l ur e pr evi ew;


r epai r f ai l ur e;
The V$I R_REPAI R vi ew shows t he r esul t s of t he REPAI R FAI LURE command:
sel ect REPAI R_I D, ADVI SE_I D, SUMMARY, RANK f r omV$I R_REPAI R;
RMAN Maintenance
Cross Checking Backups and Copies
Use CROSSCHECK command to ensure that data about backup sets and image copies in
the recovery catalog or control file is synchronized with corresponding files on disk or in the
media management catalog.
CROSSCHECK BACKUPSET OF DATABASE;
CROSSCHECK BACKUP OF TABLESPACE user s DEVI CE TYPE sbt COMPLETED BEFORE
' SYSDATE- 31' ;
Page 11 Or acl e Dat abase Admi ni st r at i on Fundament al s I I ( Not e Sheet s)
CROSSCHECK BACKUP OF ARCHI VELOG ALL SPFI LE;
Page 283 Oracle DBA Code Examples

CROSSCHECK BACKUPSET 1338, 1339, 1340;
CROSSCHECK BACKUPPI ECE TAG = ' ni ght l y_backup' ;
CROSSCHECK CONTROLFI LECOPY ' / t mp/ cont r ol 01. ct l ' ;
CROSSCHECK DATAFI LECOPY 113, 114, 115;
Not e: I f t he backup or copy i s no l onger avai l abl e, t hen RMAN mar ks i t as
EXPI RED. You can det er mi ne whi ch f i l es ar e mar ked EXPI RED by i ssui ng a LI ST
EXPI RED command.
Deleting Backups and Copies
/ * Del et i ng Speci f i ed Backups and Copi es */
DELETE BACKUPPI ECE 101;
DELETE CONTROLFI LECOPY ' / t mp/ cont r ol 01. ct l ' ;
DELETE NOPROMPT ARCHI VELOG UNTI L SEQUENCE = 300;
DELETE BACKUP OF TABLESPACE user s DEVI CE TYPE sbt ;
DELETE COPY OF CONTROLFI LE LI KE ' / t mp/ %' ;
DELETE NOPROMPT BACKUP OF SPFI LE COMPLETED BEFORE ' SYSDATE- 7' ;
DELETE NOPROMPT ARCHI VELOG ALL BACKED UP 3 TI MES TO sbt ;

/ * Del et i ng Expi r ed Backups and Copi es */
- - f i l es ar e mar ked as EXPI RED when not f ound by CROSSCHECK
DELETE EXPI RED BACKUP; - - REPORT OBSOLETE
DELETE EXPI RED COPY;
DELETE NOPROMPT EXPI RED BACKUP OF TABLESPACE user s
DEVI CE TYPE sbt COMPLETED BEFORE ' SYSDATE- 31' ;

/ * Del et i ng Backups and Copi es Render ed Obsol et e by t he Ret ent i on Pol i cy */
DELETE OBSOLETE;

/ * Del et i ng Backups and Copi es Def i ned as Obsol et e */
DELETE OBSOLETE REDUNDANCY = 3;
DELETE OBSOLETE RECOVERY WI NDOWOF 7 DAYS;

/ * For ci ng t he Del et i on of Backups and Copi es */
DELETE FORCE NOPROMPT BACKUPSET TAG ' weekl y_bkup' ;
Changing the Availability of RMAN Backups and Copies
If a file is marked UNAVAILABLE, RMAN will not use the file when a RESTORE or RECOVER
command is issued.
Use the command CHANGE ... UNAVAILABLE
CHANGE DATAFI LECOPY ' / DB01/ BACKUP/ user s01. dbf ' UNAVAI LABLE;
CHANGE BACKUP OF CONTROLFI LE UNAVAI LABLE;
CHANGE BACKUP OF CONTROLFI LE AVAI LABLE;
CHANGE COPY OF ARCHI VELOG SEQUENCE BETWEEN 230 AND 240 UNAVAI LABLE;
Exempting a Backup or Copy from the Retention Policy
Note: Specify KEEP ... LOGS to save archived logs for a possible incomplete recovery and
KEEP ... NOLOGS not to save archived logs for a possible incomplete recovery.
Note: The KEEP FOREVER clause requires the use of a recovery catalog.
Note: Use CHANGE ... NOKEEP to make the file conform to the retention policy.
Use the command CHANGE ... KEEP FOREVER|UNTIL
CHANGE BACKUPSET 123 KEEP FOREVER NOLOGS;
CHANGE DATAFI LECOPY ' / DB01/ BACKUP/ user s01. dbf ' KEEP UNTI L ' SYSDATE+60' ;
Page 284 Oracle DBA Code Examples

The CATALOG Command
Use CATALOG command to make RMAN aware of the existence of objects that are not
recorded in the repository.
You need to make RMAN aware of the existence of archived redo log files that are not
recorded in the repository, if you manually have restored your control file from a backup.
CATALOG DATAFI LECOPY ' / DB01/ BACKUP/ user s01. dbf ' ;
CATALOG CONTROLFI LECOPY / DB01/ BACKUP/ db. ct l ;
CATALOG ARCHI VELOG ' / ORADATA/ ARCHI VE1/ ar ch_12. ar c' ,
' / ORADATA/ ARCHI VE1/ ar ch_13. ar c' ;

# st ar t sear chi ng f or al l uncat al oged f i l es i n t he di r ect or y
CATALOG START WI TH ' / di sk1/ backups/ ' ;

# Cat al og al l f i l es and t he cont ent s of di r ect or i es whi ch
# begi n wi t h t he pat t er n " / backup/ MYSI D/ ar ch" .
CATALOG START WI TH ' / backup/ MYSI D/ ar ch' ;

# Cat al og al l f i l es i n t he cur r ent r ecover y ar ea.
CATALOG RECOVERY AREA NOPROMPT;

# Cat al og al l f i l es i n t he cur r ent r ecover y ar ea.
# Thi s i s an exact synonymof t he pr evi ous command.
CATALOG DB_RECOVERY_FI LE_DEST NOPROMPT;
The CHANGE UNCATALOG Command
Run the CHANGE ... UNCATALOG command to perform the following actions on RMAN
repository records:
o Delete a specific backup or copy record from the recovery catalog
o Update a backup or copy record in the target control file repository to status DELETED
RMAN does not touch the specified physical files: it only alters the repository records for
these files. You can use this command when you have deleted a backup or copy through a
means other than RMAN.
The CHANGE ... UNCATALOG is not supported for backupsets. Use Run the CHANGE ...
UNAVAILABLE or CHANGE ... DELETE instead.
CHANGE ARCHI VELOG UNCATALOG;
CHANGE DATAFI LECOPY ' / DB01/ BACKUP/ user s01. dbf ' UNCATALOG;
RMAN Catalog
Creating a Recovery Catalog
1. Create tablespace
2. Create catalog owner
CREATE USER RMAN I DENTI FI ED BY r man
TEMPORARY TABLESPACE t emp
DEFAULT TABLESPACE r man_t bs
QUOTA UNLI MI TED ON r man_t bs;
3. Grant privileges
GRANT connect , r esour ce, r ecover y_cat al og_owner t o r man;
4. Create catalog
r man cat al og r man_db1/ r man_db1@cat db
RMAN> cr eat e cat al og t abl espace r man_t s;
Page 285 Oracle DBA Code Examples

5. Connect to target database as SYSDBA
RMAN TARGET SYS/ SYS@TEST2 CATALOG RMAN/ RMAN@TEST1
6. Register target database ( make sure ORACLE_SID is properly set ):
REGI STER DATABASE;
RMAN Catalog Reporting
Use REPORT and LI ST commands.
Alternatively you can use SQL commands to query the RMAN data dictionary views. Examples of those
view are the following:
RC_DATABASE
RC_DATAFI LE
RC_STORED_SCRI PT
RC_STORED_SCRI PT_LI NE
RC_TABLESPACE
/ * r epor t command */
REPORT SCHEMA
REPORT OBSOLETE;
REPORT NEED BACKUP;
# dat af i l e cont ai ni ng under gone a nol oggi ng dat a ( must be backed up)
REPORT UNRECOVERABLE

/ * l i st command */
LI ST BACKUP;
LI ST BACKUP RECOVERABLE;
LI ST COPY;
LI ST ARCHI VELOG ALL;
LI ST SCRI PT NAMES;
LI ST GLOBAL SCRI PT NAMES;
LI ST I NCARNATI ON;
Upgrading a Recovery Catalog
If your RMAN client is from the Oracle 11.1 release, but the recovery catalog schema is from an older
version, you must upgrade the recovery catalog.
- - t o know cur r ent ver si on of ur cat al og
SELECT * FROM r cver ;

- - upgr ade st eps
1) I f t he r ecover y cat al og owner t hat you cr eat ed i s f r oma r el ease bef or e
10. 1, execut e t he f ol l owi ng
GRANT command ( assumi ng t hat r man i s t he cat al og owner ) :
SQL> GRANT CREATE TYPE TO r man;
2) St ar t RMAN and connect t o t he r ecover y cat al og dat abase.
RMAN> connect cat al og r man/ r man;
3) Execut e t he UPGRADE CATALOG command.
RMAN> UPGRADE CATALOG;
4) Conf i r mt he command by r er unni ng i t .
RMAN> UPGRADE CATALOG;
You can now use t he r ecover y cat al og wi t h t he RMAN cl i ent f r omt he Or acl e
Dat abase 11g r el ease.
Importing Recovery Catalogs
To merge two recovery catalogs, one from the 10.2 release and the other from 11g, into a single 11g
release catalog schema.
Page 286 Oracle DBA Code Examples

1. Connect t o t he dest i nat i on r ecover y cat al og.
$ r man
RMAN> connect cat al og r man/ r man@r man11
2. I ssue t he I MPORT CATALOG command
RMAN> i mpor t cat al og r man1/ r man1@r man10;
To speci f y whi ch dat abase t o r egi st er :
RMAN> i mpor t cat al og r man10/ r man10@t enner dbi d = 123456, 1234557;
RMAN> i mpor t cat al og r man10/ r man10@t enner db_name = t est db, mydb;
- - by def aul t , t he dat abases ar e unr egi st er ed f r omt he sour ce cat al og:
RMAN> i mpor t cat al og r man10/ r man10@t enner NO UNREGI STER
Moving a Recovery Catalog
- - 1) cr eat e empt y r ecover y cat al og
- - 2) connect and i mpor t :
RMAN> connect cat al og r man/ r man@t ar get _db
RMAN> i mpor t cat al og r man10/ r man10@sour ce_db;
Dropping a Recovery Catalog
connect cat al og r man/ r man@t ar get _db
DROP CATALOG;
Virtual Private Catalogs
In Oracle Database 11g, you can restrict access to the recovery catalog by granting access to only a
subset of the metadata in the recovery catalog. The subset that a user has read/write access to is termed
as virtual private catalog, or just virtual catalog. The central or source recovery catalog is now called the
base recovery catalog.
Following are the steps to create a new private catalog for the database user SCOTT:
# gr ant t he r ol e RECOVERY_CATALOG_OWNER t o t he user
SQL>GRANT RECOVERY_CATALOG_OWNER TO scot t ;
# i n RMAN sessi on, connect as t he base cat al og owner
RMAN>CONNECT CATALOG r man/ r man@mydb
RMAN>GRANT CATALOG FOR DATABASE db1, db2 TO SCOTT;
# connect as t he gr ant ed user ( vi r t ual cat al og onwer ) and cr eat e t he vi r t ual cat al og
RMAN>CONNECT CATALOG scot t / l i on@mydb
RMAN>CREATE VI RTUAL CATALOG;
# make sur e onl y gr ant ed dbs ar e seen
RMAN>LI ST I NCARNATI ON;
If the catalog is to be used for releases pre-Oracle 11g clients, in the SQL*Plus log on as the virtual
private catalog owner and run the following procedure, where "r man" is the name of the base catalog
owner:
SQL> CONN scot t / l i on@mydb
SQL> EXEC r man. DBMS_RCVCAT. CREATE_VI RTUAL_CATALOG;

Note
A virtual private catalog owner can create a local stored script, but has only read-only access to
global scripts.
The CATALOG FOR DATABASE privileges include the privilege to register and unregister those
databases for which the catalog for database privilege was granted.
The set of views and synonyms that makes up the virtual private catalog is stored in the schema
of the virtual catalog owner.
Page 287 Oracle DBA Code Examples

Managing Virtual Private Catalogs
The base recovery catalog owner can optionally grant a virtual catalog owner the right to register new
target databases in the recovery catalog by specifying the REGI STER database clause with the GRANT
command. Following is an example:
RMAN> gr ant r egi st er dat abase t o scot t ;
The virtual catalog owner must have the SYSDBA and SYSOPER privileges on the traget database, to
perform most of the RMAN operations on it.
Following are examples of removing the privileges from a virtual catalog owner:
# To r emove r ecover y cat al og access t o a dat abase f r oma user :
RMAN>CONNECT CATALOG RMAN/ RMAN@MYDB;
RMAN>REVOKE CATALOG FOR DATABASE db1 FROM scot t ;
# To r evoke t he abi l i t y t o r egi st er new dat abases f r oma vi r t ual pr i vat e cat al og owner :
RMAN>REVOKE REGI STER DATABASE FROM scot t ;
# To r evoke bot h t he cat al og and r egi st er pr i vi l eges f r oma user :
RMAN>REVOKE ALL PRI VI LEGES FROM scot t ;
Dropping a Virtual Private Catalog
Virtual private catalog owners can drop the private recovery catalog they own by issuing the DROP
CATALOG command. Following is an example:
# Log i n as t he vi r t ual cat al og owner :
RMAN>CONNECT CATALOG scot t / <passwor d>@mydb;
# I ssue t he dr op cat al og command
RMAN>DROP CATALOG;

Caution
When the DROP CATALOG command is issued by the virtual catalog owner, all the metadata
pertaining to it is deleted from the base recovery catalog.
Using RMAN Scripts
# cr eat e scr i pt
CREATE SCRI PT ni ght l y_backup {
ALLOCATE CHANNEL c1 TYPE DI SK;
BACKUP DATABASE FORMAT ' / u01/ app/ or acl e/ %u' ;
SQL ' ALTER DATABASE BACKUP CONTROLFI LE TO TRACE' ;
}

# r un i t
RUN {EXECUTE SCRI PT ni ght l y_backup; }

# cr eat e gl obal scr i pt : accessi bl e by any r egi st er ed db
CREATE GLOBAL SCRI PT gl obal _f ul l _backup
{. .

# cr eat i ng and usi ng dynami c scr i pt s:
CREATE SCRI PT myscr i pt { . . . BACKUP TAG &1 . .
RUN
{ EXECUTE SCRI PT myscr i pt
USI NG ar ch_bkp
FY09Q4; }

# pr i nt a scr i pt on t he scr een ( or quer y RC_STORED_SCRI PT_LI NE )
Page 288 Oracle DBA Code Examples

PRI NT GLOBAL SCRI PT gl obal _f ul l _backup;

# l i st i ng scr i pt names
LI ST SCRI PT NAMES;

# updat e a scr i pt
REPLACE SCRI PT f ul l _backup { . .

# conver t i ng st or ed scr i pt t o t ext f i l e
PRI NT scr i pt ni ght l y_backup t o f i l e ' t est . t xt ' ;

# del et e a scr i pt
DELETE SCRI PT ' my- scr i pt ' ;
Page 289 Oracle DBA Code Examples

Duplicating (Cloning) a Database
A duplicate database is a copy of your target database with a new, unique database
identifier (DBID).
Database Duplication (Cloning) Methods
Using RMAN DUPLICATE command
Using the OEM Database Control
Manually with SQL*Plus
Database Duplication Techniques
Following are the techniques for database duplication:
o Duplicating an Active Database: From an active database, connected to the target and
auxiliary instances (no backup is required).
o Duplicating a Database with a Target Connection: From backup, connected to the
target and auxiliary instances.
o Duplicating a Database with Recovery Catalog Without Target Connection: From
backup, connected to the auxiliary instance, not connected to the target, but with
recovery catalog connection.
o Duplicating a Database without Recovery Catalog or Target Connection: From backup,
connected to the auxiliary instance, not connected to the target and the recovery
catalog.
Database Duplication Prerequisites
Both the target and destination databases must be on an identical operating system
platform.
The password file must exist for the source database and both the target and destination
databases must have the same SYS password.
The target database must be open or in mount state.
If the target database is open, it must be in ARCHIVELOG mode.
Duplicating an Active Database using RMAN
- Cr eat e a passwor d f i l e i n t he dest i nat i on ser ver :
or apwd FI LE=D: \ or acl e\ pr oduct \ 11. 1. 0\ db_1\ dat abase\ PWDor a11g2. or a
PASSWORD=or a11g ENTRI ES=10 i gnor ecase=n

- Est abl i sh Or acl e Net connect i vi t y t o t he auxi l i ar y i nst ance i n bot h t he
sour ce and dest i nat i on ser ver s:
ORA11G2 =
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = moep10) ( PORT = 1521) )
( CONNECT_DATA =
( SERVER = DEDI CATED)
Page 290 Oracle DBA Code Examples

( SERVI CE_NAME = or a11g2)
)
)


- Add t he auxi l i ar y dat abase ser vi ce t o t he l i st ener conf i gur at i on f i l e i n t he
sour ce ser ver :
SI D_LI ST_LI STENER =
( SI D_LI ST =
( SI D_DESC =
( GLOBAL_DBNAME = or a11g)
( ORACLE_HOME = C: \ app\ Admi ni st r at or \ pr oduct \ 11. 1. 0\ db_1)
( SI D_NAME = or a11g)
)
( SI D_DESC =
( GLOBAL_DBNAME = or a11g2)
( ORACLE_HOME = C: \ app\ Admi ni st r at or \ pr oduct \ 11. 1. 0\ db_1)
( SI D_NAME = or a11g2)
)
)



- cr eat e a t ext - based i ni t i al i zat i on par amet er f i l e f or t he auxi l i ar y i nst ance
t hat cont ai ns onl y one par amet er : DB_NAME
i n ORACLEHOME\ dat abase\ i ni t or a11g2. or a
DB_NAME=or a11g2


- cr eat e Or acl e SI D ser vi ce ( i n Wi ndows)
or adi m- new - si d or a11g2


- connect t o t he auxi l ar y i nst ance:
sql pl us / nol og
conn sys/ or a11g@or a11g2 as sysoper
STARTUP NOMOUNT pf i l e=D: \ or acl e\ pr oduct \ 11. 1. 0\ db_1\ dat abase\ I ni t Or a11g2. or a



- - St ar t and Conf i gur e RMAN Bef or e Dupl i cat i on
# sour ce dat abase
RMAN>CONNECT TARGET SYS@or a11g
# dupl i cat e dat abase i nst ance
RMAN>CONNECT AUXI LI ARY SYS@or a11g2



- - You may want t o i ncr ease t he par al l el i smset t i ng of your sour ce dat abase
di sk channel s
CONFI GURE DEVI CE TYPE DI SK PARALLELI SM 1 ;


- - check par amet er s cont ai ni ng f ol der i nf o:
col val ue f or mat a35
col name f or mat a30
sel ect NAME, VALUE FROM v$par amet er wher e upper ( val ue) l i ke ' %D: \ %' ;

Page 291 Oracle DBA Code Examples


- - Run t he DUPLI CATE command
- - dupl i cat i ng a dat abase wi t h a di f f er ent di r ect or y st r uct ur e
- - ( CREATE REQUI RED DI RS)
DUPLI CATE TARGET DATABASE TO or a11g2
FROM ACTI VE DATABASE
DB_FI LE_NAME_CONVERT ' D: \ or acl e\ or adat a\ or a11g' , ' D: \ or acl e\ or adat a\ or a11g2'
SPFI LE
PARAMETER_VALUE_CONVERT ' D: \ or acl e\ or adat a\ or a11g' ,
' D: \ or acl e\ or adat a\ or a11g2'
SET MEMORY_TARGET ' 350M'
SET LOG_FI LE_NAME_CONVERT ' D: \ or acl e\ or adat a\ or a11g' ,
' D: \ or acl e\ or adat a\ or a11g2'
SET audi t _f i l e_dest ' D: \ or acl e\ admi n\ or a11g2\ adump'
SET
CONTROL_FI LES=" D: \ ORACLE\ ORADATA\ ORA11G2\ CONTROL01. CTL" , " D: \ ORACLE\ ORADATA\ ORA
11G2\ CONTROL02. CTL" ;
Duplicating a Database without Recovery Catalog or Target Connection
Oracle 11g R2
Thi s i s backup- based dupl i cat i on

- Make Backups and Ar chi ved Logs Accessi bl e t o t he Dupl i cat e I nst ance:
- i f backup f i l es l ocat i on cannot be shar ed:
Cr eat e a new di r ect or y i n t he sour ce host t hat has t he same name as t he
di r ect or y on t he dest i nat i on host t hat wi l l cont ai n t he backups:
i n sour ce
mkdi r C: \ or acl e\ st agi ngbackups

i n sour ce
RUN {
ALLOCATE CHANNEL c1 DEVI CE TYPE DI SK FORMAT ' C: \ or acl e\ st agi ngbackups\ %U' ;
BACKUP AS COPY DATABASE;
BACKUP AS COPY CURRENT CONTROLFI LE FORMAT
' C: \ or acl e\ st agi ngbackups\ cont r ol 01. ct l ' ;
}
OR
RUN {
ALLOCATE CHANNEL c1 DEVI CE TYPE DI SK FORMAT ' C: \ or acl e\ st agi ngbackups\ %U' ;
BACKUP COPY OF DATABASE ;
BACKUP AS COPY CURRENT CONTROLFI LE FORMAT
' C: \ or acl e\ st agi ngbackups\ cont r ol 01. ct l ' ;
}

- Manual l y t r ansf er t he backups i n t he new di r ect or y on t he sour ce host t o t he
i dent i cal l y named di r ect or y on t he dest i nat i on host .

- i n sour ce:
- - check par amet er s cont ai ni ng f ol der i nf o:
col val ue f or mat a35
col name f or mat a30
sel ect NAME, VALUE FROM v$par amet er wher e upper ( val ue) l i ke ' %C: \ %' ;
OR
sel ect NAME, VALUE FROM v$par amet er
wher e name i n
Page 292 Oracle DBA Code Examples

( ' cont r ol _f i l es' , ' db_r ecover y_f i l e_dest ' , ' audi t _f i l e_dest ' , ' di agnost i c_dest ' ) ;


- i n dest i nat i on:
- Cr eat e a passwor d f i l e i n t he dest i nat i on ser ver :
or apwd FI LE=C: \ or acl e\ or acl edb11g\ dat abase\ PWDor a11g2. or a PASSWORD=or a11g
ENTRI ES=10 i gnor ecase=n

- cr eat e a t ext - based i ni t i al i zat i on par amet er f i l e f or t he auxi l i ar y i nst ance
t hat cont ai ns onl y one par amet er : DB_NAME
i n ORACLEHOME\ dat abase\ i ni t or a11g2. or a
DB_NAME=or a11g2


- cr eat e Or acl e SI D ser vi ce ( i n Wi ndows)
or adi m- new - si d or a11g2


- conf i gur e Net connect i vi t y t o t he auxi l i ar y i nst ance i n t he dest i nat i on
ser ver :
ORA11G2 =
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = pc02) ( PORT = 1521) )
( CONNECT_DATA =
( SERVER = DEDI CATED)
( SERVI CE_NAME = or a11g2. pc02)
)
)


- conf i gur e t he l i st ner , i f no l i st ener al r eady exi st s

- manual l y r egi st er t he dat abase i n t he l i st ner . or a:

SI D_LI ST_LI STENER =
( SI D_LI ST =
( SI D_DESC =
( GLOBAL_DBNAME = or a11g2. pc02)
( ORACLE_HOME = C: \ or acl e\ or acl edb11g)
( SI D_NAME = or a11g2)
)
)

LI STENER =
( DESCRI PTI ON_LI ST =
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = PC02) ( PORT = 1521) )
)
( DESCRI PTI ON =
( ADDRESS = ( PROTOCOL = I PC) ( KEY = EXTPROC1521) )
)
)



- connect t o t he auxi l ar y i nst ance:
set ORACLE_SI D=ORA11G2
sql pl us / nol og
Page 293 Oracle DBA Code Examples

conn sys/ or a11g@or a11g2 as sysoper
STARTUP NOMOUNT pf i l e=C: \ or acl e\ or acl edb11g\ dat abase\ i ni t or a11g2. or a


- - St ar t and Conf i gur e RMAN Bef or e Dupl i cat i on
# dupl i cat e dat abase i nst ance
set ORACLE_SI D=ORA11G2
r man
CONNECT AUXI LI ARY SYS@or a11g2

- - You may want t o i ncr ease t he par al l el i smset t i ng of your sour ce dat abase
di sk channel s
CONFI GURE DEVI CE TYPE DI SK PARALLELI SM 1 ;

- - Run t he DUPLI CATE command
- - dupl i cat i ng a dat abase wi t h a di f f er ent di r ect or y st r uct ur e
- - ( CREATE REQUI RED DI RS)
DUPLI CATE TARGET DATABASE TO or a11g2
BACKUP LOCATI ON ' C: \ or acl e\ st agi ngbackups'
DB_FI LE_NAME_CONVERT ' C: \ or acl e\ or adat a\ or a11g' , ' C: \ or acl e\ or adat a\ or a11g2'
SPFI LE
PARAMETER_VALUE_CONVERT ' C: \ or acl e\ or adat a\ or a11g' , ' C: \ or acl e\ or adat a\ or a11g'
SET MEMORY_TARGET ' 620M'
SET LOG_FI LE_NAME_CONVERT ' C: \ or acl e\ or adat a\ or a11g' ,
' C: \ or acl e\ or adat a\ or a11g2'
SET audi t _f i l e_dest ' C: \ ORACLE\ ADMI N\ ORA11G2\ ADUMP'
SET
CONTROL_FI LES=" C: \ ORACLE\ ORADATA\ ORA11G2\ CONTROL01. CTL" , " C: \ ORACLE\ ORADATA\ ORA
11G2\ CONTROL02. CTL" ;
Manually Duplicating a Database
- - i t i s assumed t hat t he dupl i cat e dat abase wi l l have di f f er ent name
( or a11g2) f r ompr od ( or a11g)

1. Copy t he pr od dat abase f i l es t o t he t ar get l ocat i on.
- i n pr od
SHUTDOWN I MMEDI ATE
COPY THE DATABASE DATA FI LES ( EXCLUDE THE TEMFI LES) + r edo l og f i l e + spf i l es
CREATE PFI LE=' C: \ TEMP\ MYPFI LE. TXT' FROM MEMORY;

Edi t t he gener at ed PFI LE t o modi f y di r ect or y- based par amet er s l i ke:
cont r ol _f i l es
audi t _f i l e_dest
db_r ecover y_f i l e_dest
di agnost i c_dest

Change DB name:
db_domai n
db_name


2. Pr epar e a t ext f i l e f or t he cr eat i on of a cont r ol f i l e f or t he new dat abase
as f ol l ows:
- i n pr od
SQL> ALTER DATABASE BACKUP CONTROLFI LE TO TRACE;
Page 294 Oracle DBA Code Examples

i n ORACLE_BASE\ di ag\ r dbms\ or a11g\ or a11g\ t r ace\ f ol der

Modi f y as r equi r ed t he par amet er s bel ow, i ncl ude t hemi n t he par amet er f i l e
and cr eat e t hei r f ol der s:
Not e: i f you def i ne di agnost i c_dest , you don' t have t o cr eat e i t s sub-
di r ect or i es

- - The f ol l owi ng ar e cur r ent Syst em- scope REDO Log Ar chi val r el at ed
- - par amet er s and can be i ncl uded i n t he dat abase i ni t i al i zat i on f i l e.
- -
- - LOG_ARCHI VE_DEST=' '
- - LOG_ARCHI VE_DUPLEX_DEST=' '
- -
- - LOG_ARCHI VE_FORMAT=ARC%S_%R. %T
- -
- - DB_UNI QUE_NAME=" or a11g2"
- -
- - LOG_ARCHI VE_CONFI G=' SEND, RECEI VE, NODG_CONFI G'
- - LOG_ARCHI VE_MAX_PROCESSES=4
- - STANDBY_FI LE_MANAGEMENT=MANUAL
- - STANDBY_ARCHI VE_DEST=C: \ or acl e\ or acl edb11g\ RDBMS
- - FAL_CLI ENT=' '
- - FAL_SERVER=' '
- -
- - LOG_ARCHI VE_DEST_10=' LOCATI ON=USE_DB_RECOVERY_FI LE_DEST'
- - LOG_ARCHI VE_DEST_10=' OPTI ONAL REOPEN=300 NODELAY'
- - LOG_ARCHI VE_DEST_10=' ARCH NOAFFI RM NOEXPEDI TE NOVERI FY SYNC'
- - LOG_ARCHI VE_DEST_10=' REGI STER NOALTERNATE NODEPENDENCY'
- - LOG_ARCHI VE_DEST_10=' NOMAX_FAI LURE NOQUOTA_SI ZE NOQUOTA_USED
NODB_UNI QUE_NAME'
- - LOG_ARCHI VE_DEST_10=' VALI D_FOR=( PRI MARY_ROLE, ONLI NE_LOGFI LES) '
- - LOG_ARCHI VE_DEST_STATE_10=ENABLE
- -
- -

- - t he cur r ent ver si ons of al l onl i ne l ogs ar e avai l abl e
- - Not e: t he gener at ed code wi l l use " REUSE DATABASE . . NORESETLOGS" ; change
i t t o " SET DATABASE. . RESETLOGS " i f
- - you want t o use a di f f er nt db name
CREATE CONTROLFI LE SET DATABASE " ORA11G2" RESETLOGS ARCHI VELOG
MAXLOGFI LES 16
MAXLOGMEMBERS 3
MAXDATAFI LES 100
MAXI NSTANCES 8
MAXLOGHI STORY 292
LOGFI LE
GROUP 1 ' C: \ ORACLE\ ORADATA\ ORA11G2\ REDO01. LOG' SI ZE 50M,
GROUP 2 ' C: \ ORACLE\ ORADATA\ ORA11G2\ REDO02. LOG' SI ZE 50M,
GROUP 3 ' C: \ ORACLE\ ORADATA\ ORA11G2\ REDO03. LOG' SI ZE 50M
- - STANDBY LOGFI LE
DATAFI LE
' C: \ ORACLE\ ORADATA\ ORA11G2\ SYSTEM01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G2\ SYSAUX01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G2\ UNDOTBS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G2\ USERS01. DBF' ,
' C: \ ORACLE\ ORADATA\ ORA11G2\ FDA_TBS. DBF'
CHARACTER SET AR8MSWI N1256
;
Page 295 Oracle DBA Code Examples



3. i n dest i nat i on: Cr eat e a passwor d f i l e i n t he dest i nat i on ser ver :
or apwd FI LE=C: \ or acl e\ or acl edb11g\ dat abase\ PWDor a11g2. or a PASSWORD=or a11g
ENTRI ES=10 i gnor ecase=n


4. Cr eat e Or acl e SI D ser vi ce ( i n Wi ndows)
or adi m- new - si d or a11g2


5. Conf i gur e t he l i st ner , i f no l i st ener al r eady exi st s


6. Connect t o t he i nst ance:
set ORACLE_SI D=ORA11G2
sql pl us / nol og
conn / as sysdba
# use pf i l e f r omst ep 1
STARTUP NOMOUNT pf i l e=C: \ or acl e\ or acl edb11g\ dat abase\ i ni t or a11g2. or a
sampl e of i t s cont et ns f ol l ows:

audi t _f i l e_dest =' C: \ ORACLE\ ADMI N\ ORA11G2\ ADUMP'
audi t _t r ai l =' DB'
compat i bl e=' 11. 1. 0. 0. 0'
cont r ol _f i l es=' C: \ ORACLE\ ORADATA\ ORA11G2\ CONTROL01. CTL'
cont r ol _f i l es=' C: \ ORACLE\ ORADATA\ ORA11G2\ CONTROL02. CTL'
cont r ol _f i l es=' C: \ ORACLE\ ORADATA\ ORA11G2\ CONTROL03. CTL'
db_bl ock_si ze=8192
db_domai n=' pc02'
db_name=' or a11g2'
db_r ecover y_f i l e_dest =' C: \ or acl e\ f l ash_r ecover y_ar ea'
db_r ecover y_f i l e_dest _si ze=4048M
di agnost i c_dest =' C: \ ORACLE'
di spat cher s=' ( PROTOCOL=TCP) ( SERVI CE=or a11gXDB) '
l og_buf f er =5654016 # l og buf f er updat e
memor y_t ar get =620M
open_cur sor s=400
opt i mi zer _dynami c_sampl i ng=2
opt i mi zer _mode=' ALL_ROWS'
pl sql _war ni ngs=' DI SABLE: ALL' # PL/ SQL war ni ngs at i ni t . or a
pr ocesses=400
quer y_r ewr i t e_enabl ed=' TRUE'
r emot e_l ogi n_passwor df i l e=' EXCLUSI VE'
r esul t _cache_max_si ze=2112K
sessi ons=390
ski p_unusabl e_i ndexes=TRUE
undo_t abl espace=' UNDOTBS1'
LOG_ARCHI VE_FORMAT=ARC%S_%R. %T
DB_UNI QUE_NAME=" or a11g2"
LOG_ARCHI VE_DEST_10=' LOCATI ON=USE_DB_RECOVERY_FI LE_DEST'

7. Cr eat e t he cont r ol f i l e be execut i ng t he command i n st ep 2

8. Execut e:
ALTER DATABASE OPEN RESETLOGS;

Page 296 Oracle DBA Code Examples

8. Execut e:
ALTER TABLESPACE TEMP ADD TEMPFI LE ' C: \ ORACLE\ ORADATA\ ORA11G2\ TEMP01. DBF' si ze
250maut oext end on next 10mmaxsi ze 4g;

9. Execut e:
ALTER DATABASE RENAME GLOBAL_NAME TO or a11g2. pc02;
ALTER SYSTEM REGI STER;
Page 297 Oracle DBA Code Examples

Using Oracle Flashback Technology
Page 298 Oracle DBA Code Examples

Flashback Options
Row Level:
o Flashback Query
o Flashback Versions Query
o Flashback Transaction Query
o Flashback Transaction Backout
Table level:
o Flashback Table
o Flashback Drop
o Flashback Data Archive (FDA)
Database level:
o Flashback Database
Page 299 Oracle DBA Code Examples

Preparing Your Database for Flashback
- - must be AUTO
show par amet er UNDO_MANAGEMENT

- - set undo r et ensi on t ar get
sel ect val ue f r omv$par amet er wher e upper ( name) =' UNDO_RETENTI ON' ;
al t er syst emset UNDO_RETENTI ON = 2400;

- - get undo t bs name
show par amet er UNDO_TABLESPACE

- - consi der guar ant eei ng undo r et ent i on:
ALTER TABLESPACE UNDOTBS1 RETENTI ON GUARANTEE ;
Page 300 Oracle DBA Code Examples

Using Row Level Flashback Options
Flashback Query
- - i f t he user i sn' t t he owner
GRANT FLASHBACK ON empl oyees TO scot t ;
GRANT FLASHBACK ANY TABLE TO scot t ;

- - what was t he sal ar y at t hat t i me
SELECT empl oyee_i d, depar t ment _i d, sal ar y FROM empl oyees
AS OF TIMESTAMP
TO_TI MESTAMP ( ' 2008- 11- 07 11: 30: 00' , ' YYYY- MM- DD HH: MI : SS' )
WHERE empl oyee_i d=101;

sel ect empl oyee_i d , sal ar y f r omempl oyees
AS OF SCN 794532059
wher e empl oyee_i d=101



/ * usi ng DBMS_FLASHBACK */
- - set t he speci f i ed poi nt i n t i me i n t he past
sel ect . . . - - t he out put wi l l be as of cur r ent t i me
EXECUTE DBMS_FLASHBACK. ENABLE_AT_TI ME ( TO_TI MESTAMP ' 11- DEC- 2008 10: 00: 00' ,
' DD- MON- YYYY hh24: MI : SS' ) ;
sel ect . . . - - t he out put wi l l be as of t he set t i me
EXECUTE DBMS_FLASHBACK. DI SABLE ( ) ;



- - t o get cur r ent SCN
SELECT cur r ent _scn f r omV$DATABASE;
sel ect DBMS_FLASHBACK. GET_SYSTEM_CHANGE_NUMBER f r omdual ;
Flashback Versions Query
The VERSIONS clause cannot span DDL commands.
Syntax:
SELECT [ pseudocol umns] . . . / * pr ovi de det ai l s about t he r ow hi st or y */
FROM . . . / * t abl e name goes her e */
VERSI ONS BETWEEN
{SCN| TI MESTAMP {expr | MI NVALUE} AND {expr | MAXVALUE}}
[ AS OF{SCN| TI MESTAMP expr }]
WHERE [ pseudocol umns . . . ] . . .
Pseudo-Columns:
VERSI ONS_STARTSCN and VERSI ONS_STARTTI ME:
VERSI ONS_ENDSCN and VERSI ONS_ENDTI ME: i f nul l , cur r ent or del et ed
VERSI ONS_OPERATI ON: I , D, U
VERSI ONS_XI D: t r ans I D
Note: The actual time might be up to three seconds earlier or later than the time you
specify with a time stamp.
Page 301 Oracle DBA Code Examples

Flashback Versions Query restrictions:
o You cant apply the VERSIONS clause across DDL operations.
o The query will ignore purely physical row changes as happen, for example, during a
segment shrink operation.
SELECT ver si ons_xi d AS XI D,
ver si ons_st ar t scn AS START_SCN,
ver si ons_endscn AS END_SCN,
ver si ons_oper at i on AS OPERATI ON,
l ast _name,
sal ar y
FROM EMPLOYEES
VERSI ONS BETWEEN SCN MI NVALUE AND MAXVALUE
WHERE empl oyee_i d = 101;

SET LI NESI ZE 100
COL START_TI ME FORMAT A21
COL END_TI ME FORMAT A21
SELECT ver si ons_xi d AS XI D,
VERSI ONS_STARTTI ME AS START_TI ME,
VERSI ONS_ENDTI ME AS END_TI ME,
VERSI ONS_OPERATI ON AS OPERATI ON,
l ast _name,
sal ar y
FROM EMPLOYEES
VERSI ONS BETWEEN TI MESTAMP MI NVALUE AND MAXVALUE
WHERE empl oyee_i d = 101;
Flashback Transaction Query
It is actually a SELECT from FLASHBACK_TRANSACTION_QUERY
/ * r equi r ement s */
- - ( 1) hi ghl y r ecommended
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
- - ( 2) r equi r ed pr i vs
gr ant SELECT ANY TRANSACTI ON t o scot t ;

/ * usi ng i t */
SELECT t o_char ( st ar t _t i mest amp, ' dd- Mon hh24: mi ' ) , oper at i on, undo_sql
FROM f l ashback_t r ansact i on_quer y
WHERE st ar t _t i mest amp >= TO_TI MESTAMP ( ' 2009- 11- 09 05: 00: 00' , ' YYYY- MM- DD
HH: MI : SS' )
AND t abl e_owner =' HR' AND t abl e_name=' EMPLOYEES'
or der by st ar t _t i mest amp desc;

/ * usi ng f l ashback t r ansact i on wi t h ver si ons quer y */
SELECT xi d, START_SCN , commi t _scn COMMI T, OPERATI ON, l ogon_user , undo_sql
FROM f l ashback_t r ansact i on_quer y
WHERE xi d = HEXTORAW( ' 0600230050010000' ) ; - - obt ai ned f r omver si on quer y
Flashback Transaction (Backout)
Target: to back-out a committed transaction and all dependent transactions while the
database is still online.
Page 302 Oracle DBA Code Examples

OEM provides an easier to manage interface.
DBMS_FLASHBACK.TRANSACTION_BACKOUT parameters:
NUMBEROFXI DS Number of transactions to be backed out
XI DS array of transaction identifiers
OPTI ONS nocascade (default), cascade, nocascade_force, noconflict_only
TI MEHI NT time at the start of the transaction you are backing out
SCNHI NT SCN at the beginning of the transaction you are backing out
- - Set t i ng Up f or Fl ashback Tr ansact i on Backout
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( PRI MARY KEY) COLUMNS;


- - r equi r ed pr i vs
gr ant EXECUTE on DBMS_FLASHBACK t o hr ;
gr ant SELECT ANY TRANSACTI ON t o hr ;


- - get t he t r ansact i on I D
- - use v$ vi ews or t he f l ashback t r ansact i on quer y or l og mi ner
- - f ol l owi ng exampl e f r omsql i n cache:
sel ect A. SQL_TEXT, B. XI D
f r om V$OPEN_CURSOR A, V$TRANSACTI ON B, V$SESSI ON C
wher e A. SI D=C. SI D AND C. TADDR=B. ADDR
and A. SQL_TEXT LI KE ' %del et e%' ;


- - backout t he t r ans
decl ar e
V_XI D SYS. XI D_ARRAY;
begi n
V_XI D : = SYS. XI D_ARRAY( ' 03001800BC0D0000' ) ;
DBMS_FLASHBACK. TRANSACTI ON_BACKOUT( NUMTXNS => 1,
XI DS=>V_XI D, OPTI ONS=>DBMS_FLASHBACK. CASCADE) ; - - chi l dr en t r ans al so
backed out
end;
/
- - t o make i t per manent : you must now COMMIT or ROLLBACK

- - I nf or mat i on about t r ansact i on Backout s done can be obt ai ned f r om:
DBA_FLASHBACK_TXN_STATE: any t r ansact i on shown i n t hi s vi ew i s backed out .
DBA_FLASHBACK_TXN_REPORT: compensat i ng st at us of al l t r ansact i ons i n t he
dat abase
Page 303 Oracle DBA Code Examples

Using Table Level Flashback Options
Flashback Table
ROW MOVEMENT must be enabled in advance and before flashback recovery time.
Generates undo and redo data
Syntax:
FLASHBACK TABLE [ schema. ] t abl e [ , [ schema. ] t abl e] . . . TO {SCN| TI MESTAMP} expr
By default, Oracle disables all relevant triggers and reenables them upon completing the
table recovery.
Several restrictions apply:
o You cant flash back a table to a time preceding any DDL operation involving a
change in table structure.
o If the flashback operation involves multiple tables, all of the tables must be flashed
back or none.
- - r equi r ed pr i vs
gr ant FLASHBACK ANY TABLE t o hr ;
gr ant FLASHBACK on hr . empl oyees t o hr ;
- - SELECT, I NSERT, DELETE, and ALTER pr i vi l eges on t he t abl e t o be f l ashed
back ar e r equi r ed

- - r equi r ed on t he t abl e
- - al so enabl e i t f or t he t abl es t hat r ef er ence i t
ALTER TABLE emp ENABLE ROW MOVEMENT;

- - TAKE cur r ent SCN bef or e f l ashback t o go back t o i ni t i al st at of t abl e i f
- - t he f l ashback doesn t do good
SELECT cur r ent _scn f r omV$DATABASE;
sel ect DBMS_FLASHBACK. GET_SYSTEM_CHANGE_NUMBER f r omdual

FLASHBACK TABLE emp TO SCN 5759290864;

FLASHBACK TABLE emp TO TI MESTAMP TO_TI MESTAMP ( ' 2008- 01- 30 07: 00: 00' , ' YYYY-
MM- DD HH24: MI : SS' ) ;

FLASHBACK TABLE emp TO TI MESTAMP TO_TI MESTAMP ( ' 2009- 04- 05 10: 00: 00' , ' YYYY-
MM- DD HH24: MI : SS' ) ENABLE TRIGGERS;
Flashback Drop
When table is dropped, its dependents' names will also renamed by system generated
names.
If a table is undropped, the cryptic system-generated names of the dependents remain.
- - Necessar y Pr i vi l eges ****
be t he owner or
have t he dr op pr i vi l eges ( DROP TABLE or DROP ANY TABLE) on a t abl e.
You must have t he SELECT pr i vi l ege and t he FLASHBACK pr i vi l ege on an obj ect i n
or der t o quer y t hat obj ect i n t he Recycl e Bi n.


Page 304 Oracle DBA Code Examples

- - l i st dr opped t abl es ****
- - db l evel
SELECT owner , or i gi nal _name, obj ect _name, t s_name, dr opt i me, CAN_UNDROP
FROM dba_r ecycl ebi n;

- - user l evel
SELECT * FROM RECYCLEBI N;
SHOWRECYCLEBI N


- - Enabl i ng and Di sabl i ng t he Recycl e Bi n ***
- - sessi on l evel
ALTER SESSI ON SET r ecycl ebi n = OFF;
- - db l evel
- - i t af f ect s t he par amet er f i l e
ALTER SYSTEM SET r ecycl ebi n = OFF;



- - r et r ei ve dat a f r oma dr opped t abl e
SELECT * FROM " BI N$xTMPj HZ6SG+1xnDI aR9E+g==$0" ;



- - r est or e t abl e f r omdr op
FLASHBACK TABLE t abl e_name TO BEFORE DROP;
FLASHBACK TABLE " BI N$xTMPj HZ6SG+1xnDI aR9E+g==$0" TO BEFORE DROP;
FLASHBACK TABLE " BI N$xTMPj HZ6SG+1xnDI aR9E+g==$0" TO BEFORE DROP RENAME TO
NEW_PERSONS;
- - you can r ename any dependent
SELECT I NDEX_NAME FROM USER_I NDEXES WHERE TABLE_NAME = ' J OB_HI STORY' ;
ALTER I NDEX " BI N$DBo9UCht ZSbgQFeMi AdCcQ==$0" RENAME TO J HI ST_J OB_I X;

- - pur ge a t abl e( s)
DROP TABLE t abl e_name PURGE;
PURGE TABLE i nt _admi n_emp;
PURGE TABLE BI N$j sl ei l x392mk2=293$0;
PURGE TABLESPACE user s;
PURGE TABLESPACE user s USER scot t ;
PURGE RECYCLEBI N;
- - pur ge al l obj ect s i n t he db
PURGE DBA_RECYCLEBI N;
Flashback Data Archive
FDA is part of the "Oracle Total Recall" option in Oracle database 11g.
Page 305 Oracle DBA Code Examples

Disabling flashback archiving for a table or dropping its flashback archive object will result
in all the historical data for that table being lost. It also requires SYSDBA or FLASHBACK
ARCHIVE ADMINISTER privilege.
For a table with Flashback Archiving enabled, you cannot issue the following DDL
commands: ALTER TABLE (except adding a column), DROP TABLE, RENAME TABLE and
TRUNCATE TABLE.
/ * t o obt ai n i nf o about FDA */
- - i nf or mat i on on al l f l ashback ar chi ves cont ai ned i n t he dat abase
SELECT * FROM DBA_FLASHBACK_ARCHI VE;

- - i nf or mat i on on al l t abl espaces cont ai ni ng f l ashback ar chi ves
SELECT * FROM DBA_FLASHBACK_ARCHI VE_TS;

- - whi ch f l ashback ar chi ve a gi ven t abl e i s assi gned t o.
SELECT TABLE_NAME, OWNER_NAME, FLASHBACK_ARCHI VE_NAME FROM
DBA_FLASHBACK_ARCHI VE_TABLES;

- - hi st or y t abl es names cr eat ed by Or acl e:
sel ect * f r omdba_FLASHBACK_ARCHI VE_TABLES;

/ * Set t i ng up t he Dat a Fl ashback Ar chi ve */
- - 1) f or syst eml evel FDA, FLASHBACK ARCHI VE ADMI NI STER pr i v i s r equi r ed
SELECT * FROM DBA_SYS_PRI VS WHERE PRI VI LEGE LI KE ' %FLASHBACK ARC%'
- - f or speci f i c t abl e:
GRANT FLASHBACK ARCHI VE ON hr _hi st TO scot t ;


- - 2) Cr eat e FDA obj ect
- - The st at ement i n t he exampl e above may r et ur n ORA- 55603: I nval i d Fl ashback
Ar chi ve command er r or , i f you t r y t o cr eat e a f l ashback ar chi ve i n a non- empt y
t abl espace. I f i gur ed out a wor kar ound whi ch i s t o put t he t abl espace name
bet ween doubl e quot at i ons.
CREATE FLASHBACK ARCHI VE hr _hi st - - DEFAULT keywor d may be used
TABLESPACE f da_ar chi ves - - mandat or y ( and i t must be wi t h ASSM)
QUOTA 5G - - opt i onal i n M, G, T, P
RETENTI ON 24 MONTH; - - mandat or y ( i n YEAR, MONTH, DAY)


- - 3) Enabl e Fl ashback Dat a Ar chi vi ng f or exi st i ng or new t abl es
- - Cr eat e t he t abl e, usi ng t he def aul t ar chi ve l ocat i on.
CREATE TABLE my_t abl e( . . ) FLASHBACK ARCHI VE;

- - Modi f y a t abl e t o use t he def aul t ar chi ve l ocat i on
- - Not e: i f t her e i s not def aul t f l ashback ar chi ve, an er r or wi l l be r ai sed
ALTER TABLE my_t abl e FLASHBACK ARCHI VE;

- - Cr eat e a t abl e t o use a non- def aul t ar chi vel ocat i on
CREATE TABLE my_t abl e ( . . ) FLASHBACK ARCHI VE hr _ar c;

Page 306 Oracle DBA Code Examples

- - Modi f y a t abl e t o use a non- def aul t ar chi ve l ocat i on.
ALTER TABLE my_t abl e FLASHBACK ARCHI VE hr _ar c;

- - Modi f y a t abl e t o st op ( di sabl e) ar chi vi ng.
ALTER TABLE my_t abl e NO FLASHBACK ARCHI VE;



/ * Al t er i ng Fl ashback Ar chi ves */
- - make myf l ash t he def aul t f l ashback ar chi ve ( as SYSDBA)
ALTER FLASHBACK ARCHI VE myf l ash SET DEFAULT;

- - add space t o t he f l ashback ar chi ve
ALTER FLASHBACK ARCHI VE myf l ash ADD TABLESPACE myt bs;

- - r emove t he t abl espace f r omuse by t he f l ashback ar chi ve
- - ( assi gn i t t o anot her t abl espace f i r st )
ALTER FLASHBACK ARCHI VE myf l ash REMOVE TABLESPACE myt bs;

- - change t he quot a f or t he ar chi ve
ALTER FLASHBACK ARCHI VE myf l ash MODI FY TABLESPACE myt bs QUOTA 10G;

- - undef i ned quot a ( make t he space unl i mi t ed)
ALTER FLASHBACK ARCHI VE myf l ash MODI FY TABLESPACE myt bs;

- - change t he ar chi ve r et ent i on t i me
ALTER FLASHBACK ARCHI VE myf l ash MODI FY RETENTI ON 2 YEAR;

- - pur ge al l ar chi ved dat a
ALTER FLASHBACK ARCH`I VE myf l ash PURGE ALL;

- - pur ge dat a ol der t han 2 days
ALTER FLASHBACK ARCHI VE MYFLASH
PURGE BEFORE TI MESTAMP( SYSTI MESTAMP I NTERVAL ' 2' DAY) ;

- - dr oppi ng FDA:
DROP FLASHBACK ARCHI VE myf l ash;

/ * Usi ng Or acl e Fl ashback Dat a Ar chi ves */
SELECT LAST_NAME, SALARY FROM HR. EMPLOYEES
AS OF TI MESTAMP TO_TI MESTAMP ( ' 2008- 01- 01 00: 00: 00' , ' YYYY- MM- DD HH24: MI : SS' ) ;
SELECT LAST_NAME, SALARY FROM HR. EMPLOYEES
AS OF TI MESTAMP ( SYSTI MESTAMP - I NTERVAL ' 6' MONTH) ;

SELECT LAST_NAME, SALARY FROM HR. EMPLOYEES
VERSI ONS BETWEEN TI MESTAMP
TO_TI MESTAMP ( ' 2008- 01- 01 00: 00: 00' , ' YYYY- MM- DD HH24: MI : SS' ) - - or MI NVALUE
AND
TO_TI MESTAMP ( ' 2008- 01- 01 15: 00: 00' , ' YYYY- MM- DD HH24: MI : SS' ) - - or MAXVALUE
Page 307 Oracle DBA Code Examples

WHERE EMPLOYEE_I D = 200;

FLASHBACK TABLE empl oyees TO TI MESTAMP ( SYSTI MESTAMP I NTERVAL ' 6' MONTH) ;
Page 308 Oracle DBA Code Examples

Using Flashback Database
When to use Flashback Database
To retrieve a dropped schema
When a user error affects the entire database
When you truncate a table in error
When a batch job performs only partial changes
Flashback Database Considerations
You cannot use Flashback Database when:
The control file has been restored or re-created.
A tablespace has been dropped.
A data file has been reduced in size, for example by a shrink.
Using Flashback Database
It is essential that you monitor the flash recovery areas size to ensure that you have
sufficient space so as not to risk losing any of the Flashback Database logs.
/ * Conf i gur i ng Fl ashback Dat abase */
- - Check t hat your dat abase i s i n t he ar chi vel og mode:
ARCHI VE LOG LI ST

- - i n mi nut es ( 1440= 1 day)
ALTER SYSTEM SET DB_FLASHBACK_RETENTI ON_TARGET=1440;

- - i n mount l evel
ALTER DATABASE FLASHBACK ON;
ALTER DATABASE OPEN;


/ * Exempt i ng a t abl espace f or mdb f l ashback */
ALTER TABLESPACE user s FLASHBACK OFF;

- - t o swi t ch i t on agai n:
ALTER TABLESPACE user s FLASHBACK ON;


/ * Di sabl i ng Fl ashback Dat abase */
- - i n mount l evel
- - al l Fl ashback Dat abase l ogs wi l l be del et ed
ALTER DATABASE FLASHBACK OFF;


Page 309 Oracle DBA Code Examples


/ * Obt ai n i nf o about Fl ashback Dat abase */
- - t o f i nd out how f ar you can f l ash back your dat abase
SELECT ol dest _f l ashback_scn,
t o_char ( ol dest _f l ashback_t i me, ' dd- Mon hh24: mi : ss' ) ol dest _f l ashback_t i me
FROM v$f l ashback_dat abase_l og;

- - t o est i mat e t he space r equi r ed by f l ashback db:
SELECT est i mat ed_f l ashback_si ze/ 1024/ 1024 est i mat ed_f l ashback_si ze,
r et ent i on_t ar get , f l ashback_si ze/ 1024/ 1024 f l ashback_si ze
FROM v$f l ashback_dat abase_l og;

- - l ast 24- hour st at s dat a ( each r ow i s one- hour )
SELECT begi n_t i me, end_t i me, f l ashback_dat a, db_dat a,
r edo_dat a, est i mat ed_f l ashback_si ze AS EST_FB_SZE
FROM V$FLASHBACK_DATABASE_STAT
or der by begi n_t i me desc;



/ * Fl ashback db i n act i on */
- - f l ashback db t o a past t i me
STARTUP MOUNT;
FLASHBACK DATABASE TO SCN 5964663;
FLASHBACK DATABASE TO SEQUENCE 12345;
FLASHBACK DATABASE TO TI MESTAMP( SYSDATE - 1/ 24) ;
- - You can f l ash back t o j ust bef or e t he l ast RESETLOGS oper at i on by :
FLASHBACK DATABASE TO SCN 5964663 TO BEFORE RESETLOGS;
- - you can check t he dat a bef or e open r eset l ogs
ALTER DATABASE OPEN READ ONLY;

- - open r eset l ogs
ALTER DATABASE OPEN RESETLOGS;

- - t o undo t he r esul t s of t he ent i r e Fl ashback oper at i on
RECOVER DATABASE;

/ * Assi sst ed commands */
- - cur r ent scn
SELECT cur r ent _scn FROM V$DATABASE;
Restore Points
Guaranteed restore points use a separate logging mechanism from the Flashback logging
used for a Flashback Database operation.
However, if you use a guaranteed restore point and Flashback Database is enabled, Oracle
wont delete any Flashback logs and thus FRA will eventually become full.
Turning off Flashback Database if youre using guaranteed restore points.
Page 310 Oracle DBA Code Examples

With guaranteed restore points, you can only flashback to exactly the restore point time.
- - obt ai n i nf o about r p:
SELECT name, scn, st or age_si ze, t i me, guar ant ee_f l ashback_dat abase
FROM v$r est or e_poi nt ;


- - cr eat i ng or di nar y r est or e poi nt
CREATE RESTORE POI NT r p_t est ;
DROP RESTORE POI NT r p_t est ;


- - cr eat i ng a guar ant eed r est or e poi nt
CREATE RESTORE POI NT t est _guar ant ee GUARANTEE FLASHBACK DATABASE;


- - t o use l at er t he r p:
FLASHBACK DATABASE TO RESTORE POI NT t est _guar ant ee;


- - t o know i f f l ashback db st at us: i f onl y guar ant eed r p i s enabl ed, i t ' l l
r et ur n RESTORE POI NT ONLY
SELECT f l ashback_on FROM v$dat abase;

Page 311 Oracle DBA Code Examples

Part 4 Oracle Database Security
Page 312 Oracle DBA Code Examples

Oracle Database Security Management
The main aspects of Oracle database security management:
o Authorization: controlling access to data
o Authentication: restricting access to legitimate users
o Auditing: ensuring accountability on the part of the users
o Encryption: safeguarding key data in the database
o Enterprise Security: managing the security of the entire organizational information
structure
Page 313 Oracle DBA Code Examples

Security Guidelines
Apply Security Patches. http://technet.oracle.com/deploy/security/alerts.htm
Enable "Automatic Secure Configuration" when creating a new database.
Lock default users. Exceptions: SYS, SYSTEM, DBSNMP, SYSMAN, and MGMT_VIEW.
Strict password aging and expiration policies.
Do not use hard coded passwords in your script.
If possible, avoid Operating System Authentication.
Enable SYSDBA operations by setting AUDIT_SYS_OPERATIONS to TRUE. The audit
records are written to the operating system's audit trail.
Avoid granting ANY privileges and privileges with the ADMIN option.
Whenver possible, use roles rather than granting privileges directly to users.
Dont grant any unnecessary roles or privileges to PUBLIC.
sel ect count ( *) f r omDBA_TAB_PRI VS
wher e GRANTEE=' PUBLI C' ;
Set the UMASK variable to 022 to the Oracle software OS user owner.
Remove the SETUID on all Oracle files.
Unless needed, remove mentions to EXTPROC in both the listener.ora file on the server
and the tnsnames.ora file on the client. Then remove all EXTPROC executables from your
$ORACLE_HOME/bin directory ( usually extproc and xtproc0). If needed, refere to
Document ID 175429.1 in metalink.
Set a password to the listener. Secure the linstener.ora file.
ADMIN_RESTRICTIONS=ON
You may use Server-side Access Controls in the sqlnet.ora file as follows:
- - onl y t he addr esses i n t he l i st ar e al l owed t o make connect i ons
t cp. val i dnode_checki ng = yes
t cp. i nvi t ed_nodes = ( ser ver 1. us. mycompany. com, 172. 14. 16. 152)
- - addr esses i n t he l i st ar e excl uded
t cp. excl uded_nodes = ( ser ver 1. us. mycompany. com, 172. 14. 16. 152)
Disable remote OS authentication by setting the following parameter in the init.ora :
REMOTE_OS_AUTHENT=FALSE
Consider the proper setting of the security-related parameters:
# passwor d case sensi t i vi t y ( 11g)
sel ect val ue f r omv$par amet er wher e upper ( name) =' SEC_CASE_SENSI TI VE_LOGON'
al t er syst emset SEC_CASE_SENSI TI VE_LOGON = TRUE;
# maxi mumnumber of aut hent i cat i on at t empt s t hat can be made by a
# cl i ent on a connect i on t o t he ser ver pr ocess. Def aul t 10 ( 11g)
sel ect val ue f r omv$par amet er wher e
l ower ( name) =' sec_max_f ai l ed_l ogi n_at t empt s'
al t er syst emset sec_max_f ai l ed_l ogi n_at t empt s=10 scope=spf i l e;
For application users:
Page 314 Oracle DBA Code Examples

o Grant privileges to users through roles rather than direct access.
o Consider using application enabled roles.
o The users can make data changes only through procedures not using direct
DML statements.
o Consider preventing normal users from using SQL*Plus:
- - di sabl e
I NSERT I NTO SYSTEM. PRODUCT_USER_PROFI LE( PRODUCT, user i d, at t r i but e, char _val ue)
VALUES( ' SQL*Pl us' , ' TESTER' , ' ROLES' , ' TEST123' ) ;
- - enabl e
DELETE FROM pr oduct _user _pr of i l e WHERE user i d=' TESTER'
AND char _val ue = ' TEST123' ;


Page 315 Oracle DBA Code Examples

Managing Users
Recommendation: create default tablespace to every user.
For managing resources, it might be better using Resource Manager.
User Profile parameters:
o Resource limit paramters:
CONNECT_TIME: (in minutes)
IDLE_TIME
CPU_PER_CALL: CPU time used per each call
CPU_PER_SESSION
SESSIONS_PER_USER
LOGICAL_READS_PER_SESSION
LOGICAL_READS_PER_CALL
PRIVATE_SGA: applicable only to shared server architecture systems
COMPOSITE_LIMIT:
o Password management parameters (see the following section):
FAILED_LOGIN_ATTEMPTS
PASSWORD_LIFE_TIME
PASSWORD_GRACE_TIME
PASSWORD_LOCK_TIME
PASSWORD_REUSE_TIME
PASSWORD_REUSE_MAX
PASSWORD_VERIFY_FUNCTION
- - cr eat i ng user
CREATE USER user 1 I DENTI FI ED BY ur s1754
TEMPORARY TABLESPACE TEMPTBS01
DEFAULT TABLESPACE user 1t s
QUOTA 500M ON user 1t s
PROFI LE ' SALES_RPOF' ;

GRANT CREATE SESSI ON TO sal apat i ;
ALTER USER user 1 QUOTA 100M ON user 1t s;
GRANT UNLI MI TED TABLESPACE TO user 1;

SELECT t abl espace_name, user name, byt es FROM DBA_TS_QUOTAS
WHERE user name=' USER1' ;

- - dr oppi ng user
DROP USER user 1;
DROP USER user 1 cascade;
REVOKE CREATE SESSI ON FROM user 1;
Page 316 Oracle DBA Code Examples


- - Cr eat i ng and Usi ng User Pr of i l es
CREATE PROFI LE SALES_PROF
LI MI T
connect _t i me 120
f ai l ed_l ogi n_at t empt s 3
i dl e_t i me 60
sessi ons_per _user 2;

ALTER PROFI LE t est
LI MI T
sessi ons_per _user 4
f ai l ed_l ogi n_at t empt s 4;

- - t o make Or acl e enf or ce t he r esour ce l i mi t s i n
- - t he pr of i l e, i f t hey ar e used
ALTER SYSTEM SET r esour ce_l i mi t =t r ue;

ALTER USER sal apat i PROFI LE SALES_PROF;

SELECT pr of i l e FROM dba_user s
WHERE user name = ' USER1' ;

SELECT DI STI NCT r esour ce_name, l i mi t
FROM dba_pr of i l es
WHERE pr of i l e=' DEFAULT' ;


- - Passwor d Management Funct i on
- - ut l pwdmg. sql scr i pt cr eat es ver i f y_f unct i on_11g
ALTER PROFI LE DEFAULT
LI MI T
PASSWORD_LI FE_TI ME 180
PASSWORD_GRACE_TI ME 7
PASSWORD_REUSE_TI ME UNLI MI TED
PASSWORD_REUSE_MAX UNLI MI TED
FAI LED_LOGI N_ATTEMPTS 10
PASSWORD_LOCK_TI ME 1
PASSWORD_VERI FY_FUNCTI ON ver i f y_f unct i on_11G;

- - Dr oppi ng a User Pr of i l e
DROP PROFI LE t est CASCADE;
Page 317 Oracle DBA Code Examples

Database Authentication
Managin Passwords
sel ect val ue f r omv$par amet er wher e name=' sec_case_sensi t i ve_l ogon' ;
- - dynami c
al t er syst emset sec_case_sensi t i ve_l ogon=f al se ;

SELECT user name, passwor d, passwor d_ver si ons
FROM dba_user s
or der by 1;

/ * maki ng a passwor d expi r ed */
ALTER USER hr I DENTI FI ED BY hr PASSWORD EXPI RE;
ALTER PROFI LE t est _pr of i l e
LI MI T PASSWORD_LI FE_TI ME 30; - - i n days ( r ef er e t o pr of i l e sect i on)
ALTER USER hr PROFI LE t est _pr of i l e;

/ * passwor d f i l e */
sel ect val ue f r omv$par amet er wher e upper ( name) =' REMOTE_LOGI N_PASSWORDFI LE' ;
SELECT * FROM v$pwf i l e_user s;

or apwd FI LE=t est pwd PASSWORD=r emor se1 ENTRI ES=20
External (OS) Authentication
Following are the steps to setting up OS Authentication on UNIX/Linux and Windows
platforms.
# t o enabl e ext er nal aut hent i cat i on over t he net
REMOTE_OS_AUTHENT=TRUE


# cr eat e t he OS user
user add ahmedb
passwd ahmedb

# set t he par amet er OS_AUTHENT_PREFI X
SHOWPARAMETER os_aut hent _pr ef i x
al t er syst emset os_aut hent _pr ef i x=' ops$' scope=spf i l e;
al t er syst emset OS_AUTHENT_PREFI X = ' ' scope=spf i l e;

# i n DB: cr eat e t he DB user wi t h t he pr ef i x
# i n Uni x
CREATE USER ops$ahmedb I DENTI FI ED EXTERNALLY;
GRANT CONNECT TO ops$ahmedb;
# i n Wi ndows
Page 318 Oracle DBA Code Examples

CREATE USER " OPS$MYDOMAI N. COM\ AHMEDB" I DENTI FI ED EXTERNALLY;
GRANT CONNECT TO " OPS$MYDOMAI N. COM\ AHMEDB" ;

# i n Wi ndows:
# set t he f ol l owi ng i n t he f i l e " %ORACLE_HOME%\ net wor k\ admi n\ sql net . or a" :
SQLNET. AUTHENTI CATI ON_SERVI CES= ( NTS)

# t est :
su - ahmedb
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
expor t PATH=$PATH: $ORACLE_HOME/ bi n
expor t ORACLE_SI D=or a11gr 2
sql pl us /
Proxy Authentication
- - t o aut hor i ze connect i ons by a dat abase user l oggi ng on f r om
- - a mi ddl e- t i er node, usi ng passwor d aut hent i cat i on.
ALTER USER user 1
GRANT CONNECT THROUGH appser v
AUTHENTI CATED USI NG PASSWORD;

- -
ALTER USER user 1 GRANT CONNECT THROUGH appser v;
Logging In As a Different User
If you want to log on as a different user and you do not know his password.
- - 1) obt ai n hi s encr ypt ed passwor d
SELECT ' al t er user t est er i dent i f i ed by val ues ' | | passwor d| | ' ; '
FROM user $
WHERE user name=' HR' ;
- - 2) set a new passwor d t o hi m
ALTER USER hr I DENTI FI ED BY newpasswor d;
- - 3) l og on usi ng t he new passwor d and execut e your commands
- - 4) r eset t he user passwor d back t o t he or i gi nal one ( not e t he qout )
ALTER USER t est er I DENTI FI ED BY VALUES ' 1825ACAA229030F1' ;
Killing User Sessions from OS
- - on Uni x
- - 1. obt ai n pr ocess#
SELECT pr ocess, si d, ser i al # FROM v$sessi on WHERE user name=' &user ' ;
- - 2. ki l l t he pr ocess
ki l l - 9 345678
Page 319 Oracle DBA Code Examples


- - on Wi ndows
- - 1. obai n t hr ead #
SELECT si d, spi d as t hr ead, osuser , s. pr ogr am
FROM v$pr ocess p, v$sessi on s
WHERE p. addr = s. paddr ;
- - ki l l t he pr ocess usi ng or aki l l ut i l i y ( or aki l l DBsi d t hr ead#)
or aki l l MyDB 6200
Page 320 Oracle DBA Code Examples

Controlling Database Access
System and Object Privileges
/ * syst empr i vs */
GRANT CREATE SESSI ON TO hr ;
GRANT CREATE SESSI ON TO hr WI TH ADMI N OPTI ON;
GRANT ANY OBJ ECT t o hr ;
- - onl y SELECT ANY DI CTI ONARY i s NOT i ncl uded
GRANT ALL PRI VI LEGES TO our dba;
REVOKE DELETE ANY TABLE FROM our dba;

- - di ct i onar y vi ews become accessi bl e
gr ant SELECT_CATALOG_ROLE t o our dev;


/ * obj ect pr i vs */
GRANT DELETE ON bonuses TO hr WI TH GRANT OPTI ON;
GRANT UPDATE ( pr oduct _i d) ON sal es01 TO hr ;
GRANT SELECT, UPDATE ON emp_vi ew TO PUBLI C;
GRANT SELECT ON oe. cust omer s_seq TO hr ;
GRANT ALL ON EMPLOYEES TO hr ;
GRANT EXECUTE ON empl oyee_pkg TO hr ;
GRANT QUERY REWRI TE TO hr ;
GRANT READ ON DI RECTORY bf i l e_di r TO hr ;

- - i ncor r ect
REVOKE UPDATE ( host name) ON ods_pr ocess FROM hr ;
- - cor r ect
REVOKE UPDATE ON ods_pr ocess FROM hr ;
Invoker Rights and Definer Rights
CREATE OR REPLACE PROCEDURE del et e_emp ( p_emp_i d number )
AUTHID CURRENT_USER
I S
BEGI N
DELETE FROM emp WHERE
emp_i d = p_emp_i d;
COMMI T;
END;
/
Roles
Predefined roles:
Page 321 Oracle DBA Code Examples

o CONNECT
o RESOURCE: CREATE CLUSTER, CREATE INDEXTYPE, CREATE OPERATOR, CREATE
PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER, CREATE TYPE
o DBA
o EXP_FULL_DATABASE
o IMP_FULL_DATABASE
o RECOVERY_CATALOG_OWNER
- - cr eat e r ol e
CREATE ROLE new_dba;

/ * Rol e Aut hor i zat i on */
- - ( 1) Dat abase aut hor i zat i on
CREATE ROLE cl er k I DENTI FI ED BY passwor d;
- - ( 2) Dat abase aut hor i zat i on wi t h a PL/ SQL package
- - t he r ol e i s enabl ed by a hr . admi n package:
CREATE ROLE admi n_r ol e I DENTI FI ED USI NG hr . admi n;
- - ( 3) Ext er nal l y
CREATE ROLE acct s_r ec I DENTI FI ED EXTERNALLY;
- - ( 4) Gl obal l y: enabl ed by an ent er pr i se di r ect or y ser vi ce
CREATE ROLE super vi sor I DENTI FI ED GLOBALLY;

/ * Di sabl i ng and Enabl i ng a Rol e */
- - di sabl e
I NSERT I NTO SYSTEM. PRODUCT_USER_PROFI LE( PRODUCT, user i d, at t r i but e, char _val ue)
VALUES( ' SQL*Pl us' , ' TESTER' , ' ROLES' , ' TEST123' ) ;
- - enabl e
DELETE FROM pr oduct _user _pr of i l e WHERE user i d=' TESTER'
AND char _val ue = ' TEST123' ;

- - Dr oppi ng a Rol e
DROP ROLE admi n_user ;
Users, Roles, and Privileges Views
DBA_USERS Provides information about users
DBA_ROLES Shows all the roles in the database
DBA_COL_PRI VS Shows column-level object grants
DBA_ROLE_PRI VS Shows users and their roles
DBA_SYS_PRI VS Shows users who have been granted system privileges
DBA_TAB_PRI VS Shows users and their privileges on tables
ROLE_ROLE_PRI VS Shows roles granted to roles
ROLE_SYS_PRI VS Shows system privileges granted to roles
ROLE_TAB_PRI VS Shows table privileges granted to roles
SESSI ON_PRI VS Shows privileges currently enabled for the current session
SESSI ON_ROLES Shows roles currently enabled for the current session

- - l i st of ever yt hi ng gr ant ed t o a user :
SELECT ' GRANT ' | | PRI VI LEGE| | ' t o " ' | | gr ant ee| | ' " ; ' FROM dba_sys_pr i vs WHERE
Page 322 Oracle DBA Code Examples

gr ant ee=' FI NANCE'
uni on al l
SELECT ' GRANT ' | | GRANTED_ROLE| | ' t o " ' | | gr ant ee| | ' " ; ' FROM dba_r ol e_pr i vs
WHERE gr ant ee=' FI NANCE'
uni on al l
SELECT ' GRANT ' | | PRI VI LEGE| | ' t o " ' | | gr ant ee| | ' " ; ' FROM dba_t ab_pr i vs WHERE
gr ant ee=' FI NANCE' ;

Fine-Grained Data Access (Virtual Private Database VPD)
Fine-grained security within the database is implemented by DBMS_RLS
Fine-grained access control policy: attached to DB object. It can be applied to SELECT,
INSERT, UPDATE, INDEX, and DELETE statements.
SYS user is not affected by FGAC.
Common Predefined Attributes in the USERENV
instance Instance ID
entryID Auditing entry identifier
current_user Name of the user who started the session
session_user Database username by which the current user is authenticated
db_name Name of the database
host Name of the machine on which the database is running
os_user Operating system account name
terminal Client terminal through which the database is being accessed
ip_address IP address of the client machine
external_name External name of the database user
/ * Usi ng Appl i cat i on Cont ext */
- - usi ng pr e- def i ned cont ext
SELECT sys_context ('USERENV', 'OS_USER') FROM DUAL;
SELECT f i r st _name, l ast _name, empl oyee_i d FROM empl oyees
WHERE UPPER( l ast _name) =sys_context('USERENV', 'SESSION_USER');

- - usi ng user - def i ned appl i cat i on cont ext : var =val pai r per sessi on
CONNECT syst em/ syst em_passwd;
GRANT CREATE ANY CONTEXT TO hr ;
CONNECT hr / hr ;
CREATE CONTEXT empl oyee_i nf o USI NG hr . cont ext ;
CREATE OR REPLACE PACKAGE hr _cont ext AS
PROCEDURE sel ect _emp_no ;
END;
/
CREATE OR REPLACE PACKAGE BODY hr _cont ext as
PROCEDURE sel ect _emp_no I S
empnumnumber ;
BEGI N
SELECT empl oyee_i d I NTO empnumFROM empl oyees WHERE
UPPER( l ast _name) = sys_cont ext ( ' USERENV' , ' SESSI ON_USER' ) ;
Page 323 Oracle DBA Code Examples

DBMS_SESSION.SET_CONTEXT('EMPLOYEE_INFO', 'EMP_NUM', EMPNUM);
END sel ect _emp_no;
END;
/
- - set appl i cat i on cont ext : upon l ogi n t r i gger
CREATE OR REPLACE TRI GGER hr . secur i t y_cont ext
AFTER LOGON ON DATABASE
BEGI N
hr _cont ext . sel ect _emp_no;
END;
/

/ * usi ng f i ne- gr ai ned access cont r ol */
- - her e ar e t he st eps
- - ( 1) def i ne t he pol i cy f unct i on: whi ch wi l l gener at e t he pr edi cat es
- - t he f unct i on must adher e t o t he f ol l owi ng synt ax:
- - FUNCTI ON pol i cy_f unct i on ( obj ect _schema I N VARCHAR2, obj ect _name VARCHAR2)
- - RETURN VARCHAR2 r et ur ni ng max of 2000 Byt es
CREATE OR REPLACE PACKAGE hr _secur i t y AS
FUNCTI ON empnum_sec ( A1 VARCHAR2, A2 VARCHAR2)
RETURN var char 2;
END;
/
CREATE OR REPLACE PACKAGE BODY hr _secur i t y AS
FUNCTI ON empnum_sec ( A1 VARCHAR2, A2 VARCHAR2)
RETURN var char 2
I S
d_pr edi cat e var char 2 ( 2000) ;
BEGI N
d_pr edi cat e: = ' empl oyee_i d =
SYS_CONTEXT( " EMPLOYEE_I NFO" , " EMP_NUM" ) ' ;
RETURN d_pr edi cat e;
END empnum_sec;
END hr _secur i t y;
/
- - t o make al l db user bei ng abl e t o use i t
GRANT EXECUTE ON hr _secur i t y TO publ i c;

- - ( 2) cr eat e secur i t y pol i cy RLS=r ow- l evel secur i t y
- - POLI CY_TYPE par amet er i n DBMS_RLS. ADD_POLI CY t akes:
- - DBMS_RLS. DYNAMI C ( def aul t )
- - DBMS_RLS. STATI C
- - DBMS_RLS. SHARED_STATI C
- - DBMS_RLS. CONTEXT_SENSI TI VE
- - DBMS_RLS. SHARED_CONTEXT_SENSI TI VE
BEGI N
DBMS_RLS.ADD_POLICY ( OBJ ECT_SCHEMA=>' HR' ,
OBJ ECT_NAME=>' EMPLOYEES' ,
POLI CY_NAME=>' MANAGER_POLI CY' ,
Page 324 Oracle DBA Code Examples

FUNCTI ON_SCHEMA=>' HR' ,
POLI CY_FUNCTI ON=>' hr _secur i t y. empnum_sec' , - - f unc gener at es t he pr edi cat es
STATEMENT_TYPES=' SELECT' ) ;
END;
/
SELECT obj ect _name, pol i cy_name, sel , i ns, upd, del , enabl e
FROM al l _pol i ci es;

- - Col umn- Level VPD
- - You can appl y col umn- l evel VPD t o a t abl e or a vi ew
BEGI N
DBMS_RLS. ADD_POLI CY ( OBJ ECT_SCHEMA=>' HR' ,
OBJ ECT_NAME=>' EMPLOYEES' ,
POLI CY_NAME=>' MANAGER_POLI CY' ,
FUNCTI ON_SCHEMA=>' HR' ,
POLI CY_FUNCTI ON=>' hr _secur i t y. empnum_sec ,
STATEMENT_TYPE= I NSERT, UPDATE ,
SEC_RELEVANT_COLS=>' sal ar y, commi ssi on' )
END;
/

/ * Exempt i ng f r omAccess Pol i cy */
GRANT EXEMPT ACCESS POLI CY t o hr ;
Page 325 Oracle DBA Code Examples

Auditing Database
Standard Auditing
Set AUDIT_TRAIL to: NONE (default), OS, DB (SYS.AUD$), DB_EXTENDED (SYS.AUD$ +
the columns SQLBIND and SQLTEXT CLOB), XML (in OS), 'XML, EXTENDED'.
If you set AUDIT_TRAIL to DB, change the tablespace of SYS.AUD$ from SYSTEM.
Audited info:
o Operating system login
o Database username
o Terminal and session identifiers
o Operation performed or attempted
o Date and time stamp
o SQL text that triggered the auditing
sel ect val ue f r omv$par amet er wher e name=' audi t _t r ai l ' ;
- - i f not def i ned: $ORACLE_HOME/ r dbms/ audi t /
sel ect val ue f r omv$par amet er wher e name=' audi t _f i l e_dest ' ;

al t er syst emset audi t _t r ai l =db_ext ended scope=spf i l e;
ALTER SYSTEM SET audi t _t r ai l = xml , ext ended SCOPE=SPFI LE ;

- - AUDI T f ocused by
- - DB/ user
- - success/ f ai l ur e and
- - gr ouped by sessi on or access
audi t sessi on ;
AUDI T SESSI ON BY hr ;
AUDI T sel ect t abl e BY hr BY SESSI ON;
AUDI T DELETE ANY TABLE BY hr WHENEVER NOT SUCCESSFUL;
AUDI T UPDATE ANY TABLE;
AUDI T SELECT, I NSERT, UPDATE, DELETE ON empl oyees BY ACCESS WHENEVER SUCCESSFUL;
AUDI T ALL PRI VI LEGES;

/ * t ur n audi t of f */
NOAUDI T sel ect t abl e BY hr ;
NOAUDI T ALL; / * t ur ns of f al l st at ement audi t i ng */
NOAUDI T ALL PRI VI LEGES; / * t ur ns of f al l pr i vi l ege audi t i ng */
NOAUDI T ALL ON DEFAULT; / * t ur ns of f al l obj ect audi t i ng */

/ * obt ai n i nf o on audi t */
sel ect * f r om DBA_STMT_AUDI T_OPTS;
sel ect OS_USERNAME, USERNAME, USERHOST, ACTI ON_NAME,
t o_char ( LOGOFF_TI ME, ' dd- mm- yy hh24: mi : ss' ) LOGOFF, SESSI ON_CPU
f r om DBA_AUDI T_SESSI ON;

sel ect USERNAME, USERHOST, ACTI ON_NAME, OBJ _NAME
f r om DBA_AUDI T_OBJ ECT
Page 326 Oracle DBA Code Examples

ORDER BY USERNAME;


/ * f l ushi ng db audi t */
CONN / AS SYSDBA
DELETE FROM SYS. AUD$;
Customizing Database Auditing with Triggers
/ * The f ol l owi ng pr ocedur e gener at e code r equi r ed t o wr i t e an audi t i ng
t r i gger
Usage: execut e t he pr ocedur e and pass t he t abl e name. Then sel ect f r omVW
or der by I t o vi ew t he code */
CREATE TABLE VW( I NUMBER, X VARCHAR2( 4000) ) ;
SEQUENCE SEQ_I ;

CREATE PROCEDURE CREATE_AUDI T2 ( P_TABLE VARCHAR2)
I S
V_NCOL_LI ST VARCHAR2( 4000) ;
V_OCOL_LI ST VARCHAR2( 4000) ;
V_NCOL_LI ST2 VARCHAR2( 4000) ;
V_OCOL_LI ST2 VARCHAR2( 4000) ;
V_OUTPUT VARCHAR2( 4000) ;

PROCEDURE I NSERT_VW( V VARCHAR2) I S
BEGI N
I NSERT I NTO VW VALUES( SEQ_I . NEXTVAL, V ) ;
END;

BEGI N
- - ** gener at e t he t ar get Audi t Tabl e
- - cr eat e sequence
I NSERT_VW( ' CREATE SEQUENCE SEQ_' | | P_TABLE | | ' _AUDI T ; ' ) ;
I NSERT_VW( ' CREATE TABLE ' | | P_TABLE | | ' _AUDI T ( ' ) ;
I NSERT_VW( ' I D NUMBER CONSTRAI NT ' | | P_TABLE | | ' _AUDI T_I D PRI MARY KEY, ' ) ;
- - N Col umns
FOR R I N ( SELECT
TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECI SI ON, DATA_SCALE FROM
USER_TAB_COLUMNS WHERE TABLE_NAME = UPPER( P_TABLE) ) LOOP
I F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NULL THEN
I NSERT_VW( ' N' | | R. COLUMN_NAME | | ' NUMBER , ' ) ;
V_NCOL_LI ST : = V_NCOL_LI ST | | ' N' | | R. COLUMN_NAME | | ' , ' ;
V_NCOL_LI ST2 : = V_NCOL_LI ST2 | | ' : NEW. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NOT NULL AND
R. DATA_SCALE = 0 THEN
I NSERT_VW( ' N' | | R. COLUMN_NAME | | ' NUMBER( ' | | R. DATA_PRECI SI ON | | ' ) , ' ) ;
V_NCOL_LI ST : = V_NCOL_LI ST | | ' N' | | R. COLUMN_NAME | | ' , ' ;
V_NCOL_LI ST2 : = V_NCOL_LI ST2 | | ' : NEW. ' | | R. COLUMN_NAME | | ' , ' ;
Page 327 Oracle DBA Code Examples

ELSI F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NOT NULL AND
R. DATA_SCALE <> 0 THEN
I NSERT_VW( ' N' | | R. COLUMN_NAME | | ' NUMBER( ' | | R. DATA_PRECI SI ON | | ' , ' | |
R. DATA_SCALE | | ' ) , ' ) ;
V_NCOL_LI ST : = V_NCOL_LI ST | | ' N' | | R. COLUMN_NAME | | ' , ' ;
V_NCOL_LI ST2 : = V_NCOL_LI ST2 | | ' : NEW. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' VARCHAR2' THEN
I NSERT_VW( ' N' | | R. COLUMN_NAME | | ' VARCHAR2( ' | | R. DATA_LENGTH | | ' ) , ' ) ;
V_NCOL_LI ST : = V_NCOL_LI ST | | ' N' | | R. COLUMN_NAME | | ' , ' ;
V_NCOL_LI ST2 : = V_NCOL_LI ST2 | | ' : NEW. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' DATE' THEN
I NSERT_VW( ' N' | | R. COLUMN_NAME | | ' DATE, ' ) ;
V_NCOL_LI ST : = V_NCOL_LI ST | | ' N' | | R. COLUMN_NAME | | ' , ' ;
V_NCOL_LI ST2 : = V_NCOL_LI ST2 | | ' : NEW. ' | | R. COLUMN_NAME | | ' , ' ;
END I F;
END LOOP;
- - O col umns
FOR R I N ( SELECT
TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECI SI ON, DATA_SCALE FROM
USER_TAB_COLUMNS WHERE TABLE_NAME = UPPER( P_TABLE) ) LOOP
I F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NULL THEN
I NSERT_VW( ' O' | | R. COLUMN_NAME | | ' NUMBER , ' ) ;
V_OCOL_LI ST : = V_OCOL_LI ST | | ' O' | | R. COLUMN_NAME | | ' , ' ;
V_OCOL_LI ST2 : = V_OCOL_LI ST2 | | ' : OLD. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NOT NULL AND
R. DATA_SCALE = 0 THEN
I NSERT_VW( ' O' | | R. COLUMN_NAME | | ' NUMBER( ' | | R. DATA_PRECI SI ON | | ' ) , ' ) ;
V_OCOL_LI ST : = V_OCOL_LI ST | | ' O' | | R. COLUMN_NAME | | ' , ' ;
V_OCOL_LI ST2 : = V_OCOL_LI ST2 | | ' : OLD. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' NUMBER' AND R. DATA_PRECI SI ON I S NOT NULL AND
R. DATA_SCALE <> 0 THEN
I NSERT_VW( ' O' | | R. COLUMN_NAME | | ' NUMBER( ' | | R. DATA_PRECI SI ON | | ' , ' | |
R. DATA_SCALE | | ' ) , ' ) ;
V_OCOL_LI ST : = V_OCOL_LI ST | | ' O' | | R. COLUMN_NAME | | ' , ' ;
V_OCOL_LI ST2 : = V_OCOL_LI ST2 | | ' : OLD. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' VARCHAR2' THEN
I NSERT_VW( ' O' | | R. COLUMN_NAME | | ' VARCHAR2( ' | | R. DATA_LENGTH | | ' ) , ' ) ;
V_OCOL_LI ST : = V_OCOL_LI ST | | ' O' | | R. COLUMN_NAME | | ' , ' ;
V_OCOL_LI ST2 : = V_OCOL_LI ST2 | | ' : OLD. ' | | R. COLUMN_NAME | | ' , ' ;
ELSI F R. DATA_TYPE = ' DATE' THEN
I NSERT_VW( ' O' | | R. COLUMN_NAME | | ' DATE, ' ) ;
V_OCOL_LI ST : = V_OCOL_LI ST | | ' O' | | R. COLUMN_NAME | | ' , ' ;
V_OCOL_LI ST2 : = V_OCOL_LI ST2 | | ' : OLD. ' | | R. COLUMN_NAME | | ' , ' ;
END I F;
END LOOP;
I NSERT_VW( ' ACTI ON VARCHAR2( 6) , ' ) ;
I NSERT_VW( ' ACTI ON_TI ME DATE, ' ) ;
I NSERT_VW( ' HOST_NAME VARCHAR2( 300) , ' ) ;
I NSERT_VW( ' OS_USERNAME VARCHAR2( 250) ) ; ' ) ;
- - gener at e t he Audi t i ng Tr i gger
Page 328 Oracle DBA Code Examples

I NSERT_VW( ' CREATE OR REPLACE TRI GGER TRG_' | | P_TABLE | | ' _AUDI T' ) ;
I NSERT_VW( ' AFTER I NSERT OR UPDATE OR DELETE ON ' | | P_TABLE) ;
I NSERT_VW( ' FOR EACH ROW' ) ;
I NSERT_VW( ' BEGI N' ) ;
I NSERT_VW( ' I F I NSERTI NG THEN' ) ;
I NSERT_VW( ' I NSERT I NTO ' | | P_TABLE | | ' _AUDI T( I D, ' ) ;
I NSERT_VW( V_NCOL_LI ST) ;
I NSERT_VW( ' ACTI ON, ACTI ON_TI ME, HOST_NAME, OS_USERNAME) ' ) ;
I NSERT_VW( ' VALUES' ) ;
I NSERT_VW( ' ( SEQ_' | | P_TABLE | | ' _AUDI T. NEXTVAL, ' ) ;
I NSERT_VW( V_NCOL_LI ST2) ;
I NSERT_VW( ' ' ' I NSERT' ' , sysdat e,
SYS_CONTEXT( ' ' USERENV' ' , ' ' HOST' ' ) , SYS_CONTEXT( ' ' USERENV' ' , ' ' OS_USER' ' ) ) ; ' ) ;
I NSERT_VW( ' END I F; ' ) ;
I NSERT_VW( ' I F DELETI NG THEN' ) ;
I NSERT_VW( ' I NSERT I NTO ' | | P_TABLE | | ' _AUDI T( I D, ' ) ;
I NSERT_VW( V_OCOL_LI ST) ;
I NSERT_VW( ' ACTI ON, ACTI ON_TI ME, HOST_NAME, OS_USERNAME) ' ) ;
I NSERT_VW( ' VALUES' ) ;
I NSERT_VW( ' ( SEQ_' | | P_TABLE | | ' _AUDI T. NEXTVAL, ' ) ;
I NSERT_VW( V_OCOL_LI ST2) ;
I NSERT_VW( ' ' ' DELETE' ' ,
SYSDATE, SYS_CONTEXT( ' ' USERENV' ' , ' ' HOST' ' ) , SYS_CONTEXT( ' ' USERENV' ' , ' ' OS_USER' ' )
) ; ' ) ;
I NSERT_VW( ' END I F; ' ) ;
I NSERT_VW( ' I F UPDATI NG THEN' ) ;
I NSERT_VW( ' I NSERT I NTO ' | | P_TABLE | | ' _AUDI T( I D, ' ) ;
I NSERT_VW( V_NCOL_LI ST ) ;
I NSERT_VW( V_OCOL_LI ST) ;
I NSERT_VW( ' ACTI ON, ACTI ON_TI ME, HOST_NAME, OS_USERNAME) ' ) ;
I NSERT_VW( ' VALUES' ) ;
I NSERT_VW( ' ( SEQ_' | | P_TABLE | | ' _AUDI T. NEXTVAL, ' ) ;
I NSERT_VW( V_NCOL_LI ST2 ) ;
I NSERT_VW( V_OCOL_LI ST2 ) ;
I NSERT_VW( ' ' ' UPDATE' ' ,
SYSDATE, SYS_CONTEXT( ' ' USERENV' ' , ' ' HOST' ' ) , SYS_CONTEXT( ' ' USERENV' ' , ' ' OS_USER' ' )
) ; ' ) ;
I NSERT_VW( ' END I F; ' ) ;
I NSERT_VW( ' END; ' ) ;
COMMI T;
END CREATE_AUDI T2;
Auditing the Database Using System Trigger
System-Level trigger types:
o Database startup
o Logon and Logoff
o DDL
o Server error
Page 329 Oracle DBA Code Examples

/ * Requi r ed pr i vs */
gr ant ADMI NI STER DATABASE TRI GGER t o user 1;

/ * Obt ai n I nf o about DB t r i gger s */
- - l i st t he db t r i gger s
SELECT a. obj #, a. sys_evt s, b. name
FROM t r i gger $ a, obj $ b
WHERE a. sys_evt s > 0
AND a. obj #=b. obj #
AND baseobj ect = 0;

/ * Exampl es */

/ * I f db cannot st ar t because of an er r or i n t he AFTER STARTUP t r i gger */
set l i nesi ze 150
col NAME f or mat a30
col VALUE f or mat a20
col DESCRI PTI ON f or mat a60
SELECT x. ksppi nmNAME, y. ksppst vl VALUE, ksppdesc DESCRI PTI ON
FROM x$ksppi x, x$ksppcv y
WHERE x. i nst _i d = user env( ' I nst ance' )
AND y. i nst _i d = user env( ' I nst ance' )
AND x. i ndx = y. i ndx
AND x. ksppi nm= ' _syst em_t r i g_enabl ed' ;
- - enabl e or di sabl e db t r i gger s
ALTER SYSTEM SET " _syst em_t r i g_enabl ed" = TRUE SCOPE=BOTH;

- - Log On Log Of f t r i gger
CREATE OR REPLACE TRI GGER l ogon_audi t
AFTER LOGON ON DATABASE
BEGI N
I NSERT I NTO connect i on_audi t
( l ogi n_dat e, user _name)
VALUES
( SYSDATE, USER) ;
END l ogon_audi t ;
/
CREATE OR REPLACE TRI GGER l ogof f _audi t _t r i g
AFTER LOGOFF
ON DATABASE
BEGI N
I NSERT I NTO l ogon_audi t
VALUES
( user ,
sys_cont ext ( ' user env' , ' sessi oni d' ) ,
nul l ,
sysdat e,
sys_cont ext ( ' user env' , ' host ' ) ) ;
END;
/

- - t r i gger t o t r ap unsuccessf ul l ogons
/ *
ot her er r or s t hat coul d be t r apped i ncl ude:
ORA- 01004 - def aul t user name f eat ur e not suppor t ed
ORA- 01005 - nul l passwor d gi ven
ORA- 01035 - Or acl e onl y avai l abl e t o user s wi t h r est r i ct ed sessi on pr i v
ORA- 01045 - cr eat e sessi on pr i vi l ege not gr ant ed
*/
CREATE OR REPLACE TRI GGER l ogon_f ai l ur es
AFTER SERVERERROR
ON DATABASE
BEGI N
Page 330 Oracle DBA Code Examples

I F ( I S_SERVERERROR( 1017) ) THEN
I NSERT I NTO connect i on_audi t
( l ogi n_dat e, user _name)
VALUES
( SYSDATE, ' ORA- 1017' ) ;
END I F;
END l ogon_f ai l ur es;
/

- - DDL t r i gger s
/ * BEFORE / AFTER ALTER
BEFORE / AFTER ANALYZE
BEFORE / AFTER ASSOCI ATE STATI STI CS
BEFORE / AFTER AUDI T
BEFORE / AFTER COMMENT
BEFORE / AFTER CREATE
BEFORE / AFTER DDL
BEFORE / AFTER DI SASSOCI ATE STATI STI CS
BEFORE / AFTER DROP
BEFORE / AFTER GRANT
BEFORE / AFTER NOAUDI T
BEFORE / AFTER RENAME
BEFORE / AFTER REVOKE
BEFORE / AFTER TRUNCATE
AFTER SUSPEND */
CREATE OR REPLACE TRI GGER ddl _l og_t r i g
AFTER DDL ON DATABASE
BEGI N
I NSERT I NTO ddl _l og
( user name, change_dat e, obj ect _t ype, obj ect _owner , dat abase, event _name )
VALUES
( ORA_LOGI N_USER, sysdat e, or a_di ct _obj _t ype, or a_di ct _obj _owner ,
or a_dat abase_name, or a_sysevent )
END;
/
- - Di sabl e gr ant i ng pr i vi l eges t o PUBLI C
CREATE OR REPLACE TRI GGER ddl _t r i g
BEFORE GRANT
ON DATABASE
DECLARE
g_l i st DBMS_STANDARD. ORA_NAME_LI ST_T;
n PLS_I NTEGER;
BEGI N
n : = ORA_GRANTEE( g_l i st ) ;
FOR i I N 1. . n LOOP
I F g_l i st ( i ) = ' PUBLI C' THEN
RAI SE_APPLI CATI ON_ERROR( - 20997, ' Publ i c Gr ant s Not Al l owed' ) ;
END I F;
END LOOP;
END;
/

- - Syst emEr r or s
CREATE TABLE ser ver er r or _l og (
er r or _dat et i me TI MESTAMP,
er r or _user VARCHAR2( 30) ,
db_name VARCHAR2( 9) ,
er r or _st ack VARCHAR2( 2000) ,
capt ur ed_sql VARCHAR2( 1000) ) ;

CREATE OR REPLACE TRI GGER l og_ser ver _er r or s
AFTER SERVERERROR
ON DATABASE
Page 331 Oracle DBA Code Examples

DECLARE
capt ur ed_sql VARCHAR2( 1000) ;
BEGI N
SELECT q. sql _t ext
I NTO capt ur ed_sql
FROM gv$sql q, gv$sql _cur sor c, gv$sessi on s
WHERE s. audsi d = audsi d
AND s. pr ev_sql _addr = q. addr ess
AND q. addr ess = c. par ent _handl e;

I NSERT I NTO ser ver er r or _l og
( er r or _dat et i me, er r or _user , db_name,
er r or _st ack, capt ur ed_sql )
VALUES
( syst i mest amp, sys. l ogi n_user , sys. dat abase_name,
dbms_ut i l i t y. f or mat _er r or _st ack, capt ur ed_sql ) ;
END l og_ser ver _er r or s;
/
Using Fine Grained Auditing
- - - - -
- - Show al l cur r ent l y act i ve FGA Pol i ci es i n t he dat abase
- - - - -
COL obj ect _schema FORMAT A10 HEADI NG ' Obj ect | Schema'
COL obj ect _name FORMAT A20 HEADI NG ' Obj ect Name' WRAP
COL pol i cy_name FORMAT A16 HEADI NG ' Pol i cy Name' WRAP
COL pol i cy_t ext FORMAT A24 HEADI NG ' Pol i cy Text ' WRAP
COL pol i cy_col umn FORMAT A16 HEADI NG ' Pol i cy Col umn' WRAP
COL enabl ed FORMAT A05 HEADI NG ' On?'
COL si ud_opt i ons FORMAT A04 HEADI NG ' SI UD| Set '
SELECT
pol i cy_name
, pol i cy_t ext
, pol i cy_col umn
, enabl ed
, obj ect _schema
, obj ect _name
, DECODE( sel , ' YES' , ' Y' , ' N' ) | | DECODE( i ns, ' YES' , ' Y' , ' N' ) | |
DECODE( upd, ' YES' , ' Y' , ' N' ) | | DECODE( del , ' YES' , ' Y' , ' N' ) si ud_opt i ons
FROM dba_audit_policies;

- - r equi r ed pr i v
gr ant execut e on DBMS_FGA t o hr ;

- - - - -
- - Show Fi ne- Gr ai ned Audi t i ng r esul t s so f ar
- - t he vi ew i s based on SYS.FGA_LOG$
- - - - -
TTI TLE ' Cur r ent Fi ne- Gr ai ned Audi t i ng ( FGA) Resul t s'
COL audi t _dat e FORMAT A10 HEADI NG ' Audi t | Dat e'
COL pol i cy_name FORMAT A16 HEADI NG ' Pol i cy Name' WRAP
COL obj ect _schema FORMAT A10 HEADI NG ' Obj ect | Schema'
COL obj ect _name FORMAT A20 HEADI NG ' Obj ect Name' WRAP
COL db_user FORMAT A10 HEADI NG ' DBUser '
COL sql _t ext FORMAT A36 HEADI NG ' SQL Text ' WRAP
SELECT
TO_CHAR( t i mest amp, ' dd/ mm/ yyyy hh24: mi : ss' ) audi t _dat e
, db_user
, obj ect _schema
, obj ect _name
Page 332 Oracle DBA Code Examples

, pol i cy_name
, sql _t ext
FROM dba_fga_audit_trail
ORDER BY t i mest amp;


- - - - -
- - Use t he new combi ned audi t t r ai l vi ew ( DBA_COMMON_AUDI T_TRAI L)
- - t o see r esul t s of bot h St andar d ( i . e. AUDI T) and Fi ne- Gr ai ned
- - Audi t i ng ( i . e. vi a DBMS_FGA)
- - - - -
COL audt ype FORMAT A03 HEADI NG ' Aud| Typ'
COL db_user FORMAT A10 HEADI NG ' DBUser '
COL obj ect _schema FORMAT A06 HEADI NG ' Obj ect | Schema'
COL obj ect _name FORMAT A20 HEADI NG ' Obj ect Name' WRAP
COL pol i cy_name FORMAT A16 HEADI NG ' Pol i cy Name' WRAP
COL audi t _dat e FORMAT A10 HEADI NG ' Audi t | Dat e'
COL sql _t ext FORMAT A32 HEADI NG ' SQL Text ' WRAP
SELECT
DECODE( audi t _t ype,
' Fi ne Gr ai ned Audi t ' , ' FGA'
, ' St andar d Audi t ' , ' STD'
, ' UNK' ) audt ype
, db_user
, obj ect _schema
, obj ect _name
, pol i cy_name
, TO_CHAR( ext ended_t i mest amp, ' mm/ dd/ yyyy hh24: mi : ss' ) audi t _dat e
, sql _t ext
FROM dba_common_audit_trail
WHERE db_user NOT I N ( ' SYS' , ' SYSTEM' , ' DBSNMP' , ' SYSMAN' )
ORDER BY ext ended_t i mest amp, db_user , obj ect _schema, obj ect _name;

- - - - -
BEGI N
DBMS_FGA.ADD_POLICY(
obj ect _schema => ' AP' - - i f nul l , l ogon user schema
, obj ect _name => ' VENDORS'
, pol i cy_name => ' VENDORS_LO'
, audi t _condi t i on => ' ACTI VE_I ND <> ' ' Y' ' ' - - i f NULL=TRUE
, audi t _col umn => ' ACTI VE_I ND, CREDI T_CARD, CREDI T_LI MI T'
, handl er _schema => NULL
, handl er _modul e => NULL - - t he pr ocedur e wi l l f i r e on audi t
, enabl e => TRUE - - def aul t i s TRUE
, st at ement _t ypes => ' SELECT'
, audi t _t r ai l => DBMS_FGA. DB_EXTENDED
, audi t _col umn_opt s => DBMS_FGA. ANY_COLUMNS - - or DBMS_FGA. ALL_COLUMNS
) ;
END;
/

BEGI N
DBMS_FGA. ADD_POLI CY(
obj ect _schema => ' AP'
, obj ect _name => ' RV_I NVOI CE_DETAI LS'
, pol i cy_name => ' RV_I NVOI CE_LO'
, audi t _condi t i on => NULL
, audi t _col umn =>
' VENDOR_NAME, I NVOI CE_I D, EXTENDED_AMT, VENDOR_CREDI T_LI MI T'
, handl er _schema => NULL
, handl er _modul e => NULL
, enabl e => FALSE
, st at ement _t ypes => ' SELECT'
Page 333 Oracle DBA Code Examples

, audi t _t r ai l => DBMS_FGA. DB_EXTENDED
, audi t _col umn_opt s => DBMS_FGA. ALL_COLUMNS
) ;
END;
/



/ *
| | Li st i ng 1. 5: FGA Pol i cy Mai nt enance
*/

BEGI N
- - - - -
- - Di sabl i ng an enabl ed, exi st i ng FGA pol i cY
- - - - -
DBMS_FGA.DISABLE_POLICY(
obj ect _schema => ' AP'
, obj ect _name => ' I NVOI CES'
, pol i cy_name => ' I NVOI CES_HI '
) ;

- - - - -
- - Dr oppi ng an enabl ed, exi st i ng FGA pol i cY
- - - - -
DBMS_FGA.DROP_POLICY(
, pol i cy_name => ' RV_I NVOI CE_LOW'
, obj ect _name => ' RV_I NVOI CE_DETAI LS'
, pol i cy_name => ' RV_I NVOI CE_LO'
) ;
END;
/
Page 334 Oracle DBA Code Examples

Using Data Encryption
Oracle Transparent Data Encryption (TDE)
Caution: Wallet file must be included in your backup.
Column length changes on disk. Actual lengths not reported by DUMP or VSIZE.
The Wallet must be opened after instance restart.
/ * Set t i ng up TDE */
- - 1. Cr eat e t he Wal l et f i l e:
- - add t he f ol l owi ng t o t he sql net . or a
ENCRYPTI ON_WALLET_LOCATI ON =
( SOURCE=
( METHOD=f i l e)
( METHOD_DATA=
( DI RECTORY=C: \ or acl e\ Or aDb10g\ admi n\ or a10g\ wal l et ) ) )

- - 2. Set t he mast er key: t hi s i s done onl y once:
ALTER SYSTEM SET ENCRYPTI ON KEY I DENTI FI ED BY <passwor d>;

- - 3. Cr eat e t abl es t hat cont ai n encr ypt ed col umns
- - possi bl e al gor i t hms ar e AES128, ( AES192) , AES256, or 3DES168
- - t he sal t i ncr eases t he pr ot ect i on but pr event s i ndexi ng on t he col umn.
CREATE TABLE emp (
f i r st _name VARCHAR2( 128) ,
. . .
empI D NUMBER ENCRYPT NO SALT,
sal ar y NUMBER( 6) ENCRYPT USI NG ' 3DES168' ,
commNUMBER( 6) ENCRYPT) ;
ALTER TABLE EMP MODI FY ( SAL ENCRYPT NO SALT ) ;
DESC EMP

/ * Exi st i ng Tabl es and TDE */
- - Add encr ypt ed col umns:
ALTER TABLE emp ADD ( ssn VARCHAR2( 11) ENCRYPT) ;
Encr ypt unencr ypt ed col umns:
ALTER TABLE emp MODI FY ( f i r st _name ENCRYPT) ;
Di sabl e col umn encr ypt i on:
ALTER TABLE emp MODI FY ( f i r st _name DECRYPT) ;
- - Add or r emove sal t :
ALTER TABLE emp MODI FY ( f i r st _name ENCRYPT [ NO] SALT) ;
- - Change keys and t he encr ypt i on al gor i t hm:
ALTER TABLE emp REKEY USI NG ' 3DES168' ;

- - To Test TDE
SELECT
DBMS_ROWI D. ROWI D_TO_ABSOLUTE_FNO ( ROWI D, USER, ' EMP' ) ,
DBMS_ROWI D. ROWI D_BLOCK_NUMBER ( ROWI D)
Page 335 Oracle DBA Code Examples

FROM EMP;
Fi l e Nu Bl ock Number
- - - - - - - - - - - - - - - - - - -
4 63
ALTER SESSI ON SET EVENTS ' 10389 t r ace name cont ext f or ever , l evel 1' ;
ALTER SYSTEM DUMP DATAFI LE 4 BLOCK 63;

/ * Openi ng and Cl osi ng t he Wal l et */
- - The Wal l et must be opened af t er i nst ance r est ar t .
ALTER SYSTEM SET ENCRYPTI ON WALLET OPEN I DENTI FI ED BY passwor d>
ALTER SYSTEM SET ENCRYPTI ON WALLET CLOSE
- - To ver i f y t hat a wal l et i s open, you can quer y t he V$ENCRYPTI ON_WALLET:
sel ect WRL_PARAMETER, STATUS
f r omV$ENCRYPTI ON_WALLET
Tablespace Encryption
In Oracle Database 11g, you can encrypt an entire tablespace.
Encrypted Tablespace Limitations
You cannot encrypt an existing tablespace.
exp and i mp utilities are not supported with objects in the encrypted tablespaces.
Whereas expdp and i mpdp utilities are supported.
You cannot re-create the tablespace encryption key.
The NO SALT option is not supported.
Temporary and undo tablespaces cannot be encrypted.
You cannot transport an encrypted tablespace to a database that already has an Oracle
wallet for TDE. In this case, use Oracle Data Pump to export the objects in the tablespace
using the expdp with ENCRYPTI ON_MODE=password and then import them to the
destination database.
BFILES and external tables are not encrypted.
Logically, encrypted tablespace is less efficient than normal un-encrypted tablespace.

Caution
Losing the master key or the wallet file will lead to losing the data in the encrypted
tablespace.
Encrypting a Tablespace
Create and open a wallet file, as explained in the previous section.
The tablespace creation statement for an encrypted tablespace has the following syntax:
CREATE TABLESPACE <t bsp_name> . . .
[ ENCRYPTI ON [ USI NG <ALGORI THM>] ] - - speci f y encr ypt i on al gor i t hm
DEFAULT STORAGE( ENCRYPT) - - encr ypt obj ect s i n t he t abl espace

CREATE TABLESPACE t bsp1
DATAFI LE ' / u01/ app/ or acl e/ t est / t bsp1_01. dbf ' SI ZE 500m
ENCRYPTI ON
Page 336 Oracle DBA Code Examples

DEFAULT STORAGE ( ENCRYPT) ;

CREATE TABLESPACE myt bsp2
DATAFI LE ' / u01/ app/ or acl e/ t est / myt bsp2_01. dbf ' si ze 500m
ENCRYPTI ON USI NG ' 3DES168'
DEFAULT STORAGE ( ENCRYPT) ;
The ALGORI THMclause accepts one of the following values:
o AES192 Advanced Encryption Standard (the default).
o 3DES168 Triple Data Encryption Standard 168-bit encryption
o AES128 Advanced Encryption Standard 128-bit encryption
o AES256 Advanced Encryption Standard 256-bit encryption
To know whether an existing tablespace is encrypted or not, issue the following query:
sel ect vt . NAME, vet . ENCRYPTI ONALG, vet . ENCRYPTEDTS
f r om V$ENCRYPTED_TABLESPACES vet , V$TABLESPACE vt
wher e vet . TS#=vt . TS#

SELECT t abl espace_name, encr ypt ed
2 FROM dba_t abl espaces;
Page 337 Oracle DBA Code Examples

Fine-Grained Access Control for UTL_* Packages
Oracle Database 11g provides a mechanism to refine the level of access to the network
access packages UTL_TCP, UTL_SMTP, UTL_MAI L, UTL_HTTP, and UTL_I NADDR.
Creating ACL
You can use the DBMS_NETWORK_ACL_ADMI N package to facilitate management of the UTL_*
network access packages as in the following steps:
1) Create an Access Control List (ACL): All ACL definitions are stored in XML DB in the form of
XML documents. The ACL XML files reside in the / sys/ acl s directory of the XML DB
repository. Following is an example of using the CREATE_ACL procedure to create an XML
file called dba. xml :
begi n
DBMS_NETWORK_ACL_ADMI N. CREATE_ACL (
ACL => ' dba. xml ' , - - case sensi t i ve
DESCRI PTI ON=> ' Net wor k Access Cont r ol f or t he DBAs' ,
PRI NCI PAL => ' SCOTT' , - - user or r ol e t he pr i vi l ege i s gr ant ed or deni ed
( upper case)
I S_GRANT => TRUE, - - pr i vi l ege i s gr ant ed or deni ed
PRI VI LEGE => ' connect ' , - - or ' r esol ve' ( case sensi t i ve)
START_DATE => nul l , - - when t he access cont r ol ent i t y ACE wi l l be val i d
END_DATE => nul l ) ; - - ACE expi r at i on dat e ( TI MESTAMP WI TH TI MEZONE f or mat )
end;
Regarding the PRI VI LEGE parameter, the database user needs the connect privilege to an
external network host computer if he or she is connecting using the UTL_TCP, UTL_HTTP,
UTL_SMTP, and UTL_MAI L utility packages. To resolve a host name that was given as a host IP
address, or the IP address that was given as a host name, with the UTL_I NADDR package,
grant the database user the r esol ve privilege.
You can then query the RESOURCE_VI EWview to find the dba. xml ACL in the / sys/ acl s
directory:
sel ect ANY_PATH
f r om RESOURCE_VI EW
wher e ANY_PATH LI KE ' / sys/ acl s/ dba%'
Too may entries in the ACL may lead to significant XML DB performance drop because ACL
are checked for each access to Oracle XML DB repository. As general rule of thumb, ACL
check operations perform best when the number of ACEs in the ACL is at 16 entries or less.
2) Add Access Control Entries: Once you create the initial ACL, you can continue to add more
privileges to the XML file. The following example will add the user RAMI to the dba. xml file
and grant him network access:
begi n
DBMS_NETWORK_ACL_ADMI N. ADD_PRI VI LEGE (
ACL => ' dba. xml ' ,
PRI NCI PAL => ' RAMI ' ,
I S_GRANT => TRUE,
Page 338 Oracle DBA Code Examples

PRI VI LEGE => ' connect ' ,
START_DATE => nul l , - - i f t he t i me i nt er val i s def i ned,
END_DATE => nul l ) ; - - t he ACE wi l l expi r e af t er t he speci f i ed dat e r ange
end;
/
COMMI T;
In ACL, the security entries are evaluating in order precedence. If you have two contradicting
entries in the list, the first one in the order will take effect. You can control the order number
of an added entry as follows:
begi n
DBMS_NETWORK_ACL_ADMI N. ADD_PRI VI LEGE (
POSI TI ON => 1, - - on t he t op
ACL => ' dba. xml ' , PRI NCI PAL => ' SAMI ' ,
I S_GRANT => FALSE, PRI VI LEGE => ' connect ' ,
START_DATE => nul l , END_DATE => nul l ) ;
end;
3) Assign Hosts: The ASSI GN_ACL procedure is used to authorize access to one or more
network hosts as follows:
begi n
DBMS_NETWORK_ACL_ADMI N. ASSI GN_ACL (
ACL => ' dba. xml ' , HOST => ' dbaexper t . com' ,
LOWER_PORT => 80, UPPER_PORT => 443) ;
end;
COMMI T;
The lower port and the upper port define the lower and the upper boundaries of the allowable
port range. They should be set for connect privileges not resolve privileges.
4) Validate that the ACL permissions worked accordingly. Following is an example to test the
code in the previous step.
sel ect UTL_HTTP. REQUEST( ' ht t p: / / www. ahmedbar aka. com' ) f r omdual ;
If the sufficient ACL privileges or ACL assignments are not provided, you will receive the ORA-
24247 error.
Access Control Lists Maintenance
Use DELETE_PRI VI LEGE to remove an access control entry from the XML file.
exec DBMS_NETWORK_ACL_ADMI N. DELETE_PRI VI LEGE( ACL=>' dba. xml ' , PRI NCI PAL=> ' RAMI ' ) ;
Use the DROP_ACL procedure to remove the XML file from the / sys/ acl s directory as follows:
exec DBMS_NETWORK_ACL_ADMI N. DROP_ACL ( ACL=>' dba. xml ' ) ;
Page 339 Oracle DBA Code Examples

Query Your Access Control List
To display list of the ACLs created in the database, use the following query:
sel ect HOST, LOWER_PORT, UPPER_PORT, ACL f r omDBA_NETWORK_ACLS
You can query the DBA_NETWORK_ACL_PRI VI LEGES view to query network privileges granted or
denied for the access control list as follows:
sel ect PRI NCI PAL, PRI VI LEGE, I S_GRANT
f r om DBA_NETWORK_ACL_PRI VI LEGES
wher e ACL l i ke ' %dba. xml '
Logged on users can use the following query to see their access entries in the dba. xml file:
sel ect HOST, LOWER_PORT, UPPER_PORT, STATUS pr i vi l ege
f r om USER_NETWORK_ACL_PRI VI LEGES
wher e HOST i n
( sel ect * f r om
t abl e( DBMS_NETWORK_ACL_UTI LI TY. DOMAI NS( ' dbaexper t . com' ) ) )
and PRI VI LEGE = ' connect '
or der by DBMS_NETWORK_ACL_UTI LI TY. DOMAI N_LEVEL( host ) desc, LOWER_PORT;
Page 340 Oracle DBA Code Examples

Part 5 Oracle Database Performance
Tuning
Page 341 Oracle DBA Code Examples

Managing Performance Statistics
Managing OS Statistics
CPU Statistics:
o doesn't exceed 95% in total.
o check DB share on CPU
Virtual Memory Statistics:
o validate that memory usage does not increase after the system has reached a steady
state after startup.
Disk I/O Statistics:
o current response time should be between 5 to 20 ms for a single block IO
o the length of the disk queues shouldn't exceed two.
Network Statistics:
o Look at the network round-trip ping time and the number of collisions. Investigate it,
if the network is causing large delays in response time.

Reducing Disk Contention:
o Increase the number of disks in the storage system
o Separate the database and the redo log files
o For a large table, use partitions to reduce I/O
o Stripe the data either manually or by using a RAID disk-striping system
o Invest in cutting-edge technology, such as file caching, to avoid I/O bottlenecks
o Consider using ASM
/* from the database */
- - t o gat her syst emst at s
see Gat her i ng Syst emSt at i st i cs

- - al l st at s
sel ect STAT_NAME, VALUE, OSSTAT_I D, COMMENTS, CUMULATI VE
f r omV$OSSTAT;

/ * CPU */
- - one- hour hi st or y of t he Host CPU Ut i l i zat i on
sel ect BEGI N_TI ME, END_TI ME, GROUP_I D, METRI C_I D, METRI C_NAME, VALUE, METRI C_UNI T
f r omV$SYSMETRI C_HI STORY
wher e METRI C_NAME LI KE ' %Host CPU%'

- - t op sessi on CPU- comsumer s
SELECT
n. user name,
s. si d,
s. val ue
FROM v$sesst at s, v$st at name t , v$sessi on n
WHERE s. st at i st i c# = t . st at i st i c#
AND n. si d = s. si d
AND t . name=' CPU used by t hi s sessi on'
Page 342 Oracle DBA Code Examples

AND s. val ue <> 0
ORDER BY s. val ue desc;

- - Decomposi t i on of Tot al CPU Usage
- - i f t he par si ng or r ecur si ve CPU usage PCT i s hi gh, t hen t uni ng i s r equi r ed
- - Recur si ve CPU Usage i s f or dat a di ct l ookups and execut i ng PL/ SQL pr ogr ams
SELECT name, val ue,
r ound( val ue/ ( sel ect sum( val ue) f r omv$sysst at WHERE NAME I N ( ' CPU used by t hi s
sessi on' , ' r ecur si ve cpu usage' , ' par se t i me cpu' ) ) *100, 2) PCT
FROM V$SYSSTAT
WHERE NAME I N ( ' CPU used by t hi s sessi on' , ' r ecur si ve cpu usage' , ' par se t i me
cpu' )
or der by val ue DESC


/ * i o t uni ng */
- - I O r el at ed wai t s
sel ect
EVENT,
TOTAL_WAI TS_FG,
TOTAL_TI MEOUTS_FG,
TI ME_WAI TED_FG,
AVERAGE_WAI T_FG,
WAI T_CLASS,
TOTAL_WAI TS,
TOTAL_TI MEOUTS,
TI ME_WAI TED,
AVERAGE_WAI T
f r om
V$SYSTEM_EVENT
WHERE WAI T_CLASS = ' User I / O'
or der by WAI T_CLASS;

- - i o st at s
sel ect
FI LE_NO,
FI LETYPE_NAME,
SMALL_READ_MEGABYTES " Si ngl e- bl ock MegaByt es Reads" ,
SMALL_WRI TE_MEGABYTES " Si ngl e- bl ock MegaByt es Wr i t es" ,
SMALL_READ_REQS " Si ngl e- bl ock Read Request s" ,
SMALL_WRI TE_REQS " Si ngl e- bl ock Wr i t e Request s" ,
SMALL_READ_SERVI CETI ME " Tot al S- Bl ock Read Ti me" ,
SMALL_WRI TE_SERVI CETI ME " Tot al S- Bl ock Wr i t e Ti me" ,
- - decode( SMALL_READ_REQS, 0, 0, SMALL_READ_SERVI CETI ME/ SMALL_READ_REQS) " Per S-
Bl ock Read Response T" ,
SMALL_SYNC_READ_REQS,
SMALL_SYNC_READ_LATENCY " S- Bl ock Sync Read Lat ency ( ms) " ,
LARGE_READ_MEGABYTES " Mul t i - bl ock MegaByt es Reads" ,
LARGE_WRI TE_MEGABYTES " Mul t i - bl ock MegaByt es Wr i t es" ,
LARGE_READ_REQS " Mul t i - bl ock Read Request s" ,
LARGE_WRI TE_REQS " Mul t i - bl ock Wr i t e Request s" ,
LARGE_READ_SERVI CETI ME " Tot al M- Bl ock Read Ti me" ,
LARGE_WRI TE_SERVI CETI ME " Tot al M- Bl ock Wr i t e Ti me" ,
ASYNCH_I O,
RETRI ES_ON_ERROR
f r omV$I OSTAT_FI LE
or der by FI LE_NO
/
Page 343 Oracle DBA Code Examples


- - Dat af i l es I O si nce i nst ance st ar t up
SELECT d. name,
f . phyr ds r eads,
f . phywr t s wr t s,
( f . r eadt i m/ decode( f . phyr ds, 0, - 1, f . phyr ds) ) / 10 ReadRespoi nseTi me_ms,
( f . wr i t et i m/ decode( f . phywr t s, 0, - 1, phywr t s) ) / 10 Wr i t eRespoi nseTi me_ms,
SI NGLEBLKRDTI M/ 10 Si ngl e_Bl ock_ReadTi me_ms
FROM
v$dat af i l e d, v$f i l est at f
WHERE d. f i l e# = f . f i l e#
ORDER BY d. name;

- - Dat af i l es I O Hi st or y
SELECT
f . snap_i d,
f . f i l ename,
f . phyr ds r eads,
f . phywr t s wr t s,
( f . r eadt i m/ decode( f . phyr ds, 0, - 1, f . phyr ds) ) / 10 ReadRespoi nseTi me_ms,
( f . wr i t et i m/ decode( f . phywr t s, 0, - 1, phywr t s) ) / 10 Wr i t eRespoi nseTi me_ms,
SI NGLEBLKRDTI M/ 10 Si ngl e_Bl ock_ReadTi me_ms,
wai t _count , t i me wai t t i me
FROM DBA_HI ST_FI LESTATXS f
ORDER BY f . snap_i d desc, f i l ename



/* on Windows */
- - Per f or mance Moni t or t ool .
For Wi ndows Ser ver 2003, can be downl oaded f r om:
ht t p: / / www. mi cr osof t . com/ downl oads/ det ai l s. aspx?f ami l yi d=09115420- 8c9d- 46b9- a9a5-
9bf f cd237da2&di spl ayl ang=en

- - see usi ng Usi ng Per f or mance Tool i n Wi ndows
- - see usi ng OS Wat cher
- - see al so Opt i mi zi ng Wi ndows Ser ver


/* on Unix */
/ * CPU */
# pr ocess per second
sar - c 2 10 - - f or al l CPUs wi t hout i nt er val , si nce l ast r eboot
sar - c P 0 - - f or f i r st CPU

# CPU%ut i l i zat i on
sar - u 4 5

# f r omvmst at out put
# us: user CPU Ti me %
sy: syst emCPU Ti me %
i d: i dl e CPU Ti me %
wa: Wai t i ng f or I O CPU Ti me %

# al t er nat i vel y
vmst at - s | gr ep " cpu t i cks"
# CPU%ut i l i zat i on
Page 344 Oracle DBA Code Examples

i ost at c
i ost at 4 5 c - - 5 t i mes ever y 4 seconds



/ * Vi r t ual Memor y St at i st i cs */
- - Obt ai n i nf o about memor y
cat / pr oc/ memi nf o

- - Page i ns and page out s
vmst at - s | gr ep " pages paged"
sar - B 2 50 - - ever y 2 seconds f or 50 t i mes

- - Swap i ns and swap out s
# f r omvmst at out put : swpd ( so ( swapped out ) or si ) shoul d i deal l y be 0
# al t er nat i vel y:
vmst at s - S M | gr ep " swap"

sar r
sar - W

- - Act i ve and i nact i ve pages: you shoul dn' t have t oo f ew i nact i ve memor y pages:
vmst at - S M
# al t er nat i vel y:
vmst at - s - S M | gr ep " memor y"

sar r
sar R



/ * Di sk I / O St at i st i cs */
# di sk usage
df h

# f r omvmst at out put : bi ( bl ocks i n) bo ( bl ocks out )
# al t er nat i vel y:
#vmst at - s - S M | gr ep " pages"
# r epor t s di sk st at i st i cs
vmst at - d | gr ep d
# t ps: t r ansf er per second
i ost at d
i ost at 4 5 d - - 5 t i mes ever y 4 seconds
i ost at - d k - - di spl ay out put i n ki l obyt es i nst ead of bl ocks
i ost at - d x - - ext ended r epor t

# r t ps wt ps r ead/ wr i t e r equest s per second i ssued t o t he physi cal di sk
# br ead/ s bwr t n/ s dat a r ead/ wr i t e f r omt he dr i ve i n bl ocks per second
sar b 5 10
# bl oc devi ce usage
# number of sect or s ( 512 byt e) r ead/ wr i t t en per second
# i f avque i s gr eat er l ar ger t han 1, di sk cont ent i on i s t her e
sar - d



/ * Net wor k St at i st i cs */
Page 345 Oracle DBA Code Examples

# pi ng and check t he l at ency
pi ng . . .

# sar - n DEV | EDEV | SOCK | FULL
# DEV= net wor k devi ces
r xpck/ s packet s r ecei ved per second
t xpck/ s packet s t r ansmi t t ed per second
r xbyt / s byt es r ecei ved per second
t xbyt / s byt es t r ansmi t t ed per second
# EDEV = f ai l ur es f r omt he net wor k devi ces
r xer r / s bad packet s r ecei ved per second.
t xer r / s er r or s t hat happened per second whi l e t r ansmi t t i ng packet s
col l / s col l i si ons t hat happened per second whi l e t r ansmi t t i ng packet s
r xdr op/ s r ecei ved packet s dr opped per second because of a l ack of space i n l i nux
buf f er s
t xdr op/ s t r ansmi t t ed packet s dr opped per second because of a l ack of space i n
l i nux buf f er s
t xcar r / s car r i er - er r or s t hat happened per second whi l e t r ansmi t t i ng packet s
r xf r am/ s f r ame al i gnment er r or s t hat happened per second on r ecei ved packet s.
r xf i f o/ s FI FO over r un er r or s t hat happened per second on r ecei ved packet s.
t xf i f o/ s FI FO over r un er r or s t hat happened per second on t r ansmi t t ed packet s.
# SOCK = socket s
t ot sck Tot al number of used socket s.
t cpsck Number of TCP socket s cur r ent l y i n use.
udpsck Number of UDP socket s cur r ent l y i n use.
r awsck Number of RAWsocket s cur r ent l y i n use.
i p- f r ag Number of I P f r agment s cur r ent l y i n use.

# di spl ay net wor k i nt er f aces
net st at i
# summar y st at s on each pr ot ocol
net st at s | l ess
Managing Database Statistics
System and Session Statistics (and their executed statements)
Time Model Statistics
Wait Events
Active Session History
System and Session Statistics
/* System stats */
sel ect
NAME,
decode( CLASS,
' 1' , ' User ' , ' 2' , ' Redo' , ' 4' , ' Enqueue' , ' 8' , ' Cache' , ' 16' , ' OS' , ' 32' , ' RAC' , ' 64' , ' SQL' , ' 1
28' , ' Debug' , CLASS) STAT_CLASS,
VALUE
f r omV$SYSSTAT
or der by NAME;


/* Session stats */
sel ect
Page 346 Oracle DBA Code Examples

T. SI D, S. USERNAME, S. MACHI NE, S. MODULE, S. ACTI ON,
N. NAME,
decode( N. CLASS,
' 1' , ' User ' , ' 2' , ' Redo' , ' 4' , ' Enqueue' , ' 8' , ' Cache' , ' 16' , ' OS' , ' 32' , ' RAC' , ' 64' , ' SQL' , ' 1
28' , ' Debug' , N. CLASS) STAT_CLASS,
VALUE
f r omV$SESSTAT T, V$STATNAME N, V$SESSI ON S
WHERE T. STATI STI C#=N. STATI STI C# and T. SI D=S. SI D
and S. USERNAME NOT I N ( ' SYSTEM' , ' SYS' , ' DBSNMP' , ' SYSMAN' )
or der by S. SI D , N. NAME;


/* SQL Stats */
hi gh buf f er get s = usi ng t he wr ong i ndex, t he wr ong dr i vi ng t abl e i n a j oi n, or a
si mi l ar SQL- r el at ed er r or
buf f er get s and di sk r eads ar e at i dent i cal l evel s = a mi ssi ng i ndex


- - t op i o consumer s
SELECT execut i ons, buf f er _get s, di sk_r eads, r ows_pr ocessed, SORTS, sql _t ext
FROM V$SQL
WHERE buf f er _get s > 100000 OR di sk_r eads > 100000
ORDER BY buf f er _get s + 100*di sk_r eads DESC;


- - t op CPU consumer s
SELECT execut i ons,
ROUND( el apsed_t i me/ 1000000, 2) el apsed_seconds,
ROUND( cpu_t i me/ 1000000, 2) cpu_secs ,
sql _t ext
f r om( sel ect * f r omv$sql or der by el apsed_t i me desc)
WHERE r ownum<6
Time Model Statistics
DB Time is an indicator instance workload.
DB Time = CPU time + non-idle Wait time (of all the sessions accumulatively)
- - how l ong si nce t he i nst ance st ar t ed
sel ect STARTUP_TI ME , ROUND( ( SYSDATE- STARTUP_TI ME) *24, 2) HOURS
f r omv$i nst ance;

- - syst em- wi de t i me- based st at
SELECT STAT_NAME " St at . Name" ,
r ound( VALUE/ 1000000) " Val ue ( s) " ,
r ound( VALUE/ 1000000/ 60) " Val ue ( mi n) "
FROM V$SYS_TI ME_MODEL;


- - SESSI ON- wi de t i me- based st at s
SELECT
E. SI D, S. USERNAME, S. MACHI NE, S. MODULE, S. ACTI ON,
STAT_NAME " St at . Name" ,
r ound( VALUE/ 1000000) " Val ue ( s) " ,
r ound( VALUE/ 1000000/ 60) " Val ue ( mi n) "
FROM V$SESS_TI ME_MODEL E, V$SESSI ON S
WHERE E. SI D = S. SI D
and S. USERNAME NOT I N ( ' SYSTEM' , ' SYS' , ' DBSNMP' , ' SYSMAN' )
Page 347 Oracle DBA Code Examples

or der by E. SI D;
Wait Events
The wait events are only the symptoms of problems, most likely within the application
code.
After defining the troubled waiting event, you can get further info by tracing the suspected
session.
- - TI MED_STATI STI CS must be t r ue ( def aul t )
show par amet er TI MED_STATI STI CS

/ * Wai t t i me f or t he whol e i nst ance */
- - Syst emmet r i cs capt ur ed i n r ecent 60- sec or 15- sec
- - I f ' Dat abase Wai t Ti me Rat i o' i s hi gher t han ' Dat abase CPU Ti me Rat i o' ,
- - consi der l ooki ng f or bot t l enecks
sel ect
GROUP_I D,
METRI C_NAME,
VALUE,
METRI C_UNI T,
I NTSI ZE_CSEC/ 100 I nt er val _Dur at i on,
TO_CHAR( BEGI N_TI ME, ' HH24: MI : SS' ) BEGI N_TI ME,
TO_CHAR( END_TI ME, ' HH24: MI : SS' ) END_TI ME
f r omV$SYSMETRI C
- - wher e METRI C_NAME I N ( ' Dat abase Wai t Ti me Rat i o' , ' Dat abase CPU Ti me Rat i o' )
or der BY END_TI ME DESC

- - i n t he r ecent hour
SELECT
GROUP_I D,
METRI C_NAME,
VALUE,
METRI C_UNI T,
ROUND( I NTSI ZE_CSEC/ 100) I nt er val _Dur at i on,
TO_CHAR( BEGI N_TI ME, ' HH24: MI : SS' ) BEGI N_TI ME,
TO_CHAR( END_TI ME, ' HH24: MI : SS' ) END_TI ME
FROM V$SYSMETRI C_HI STORY
WHERE METRI C_NAME I N ( ' Dat abase Wai t Ti me Rat i o' , ' Dat abase CPU Ti me Rat i o' )
ORDER BY END_TI ME DESC


/ * WAI T EVENTS */
- - wai t e event s i n t he i nst ance:
- - Top Wai t Cl asses By I nst ance Tot al
- - AWR r epor t s coul d al so assi st you
sel ect
WAI T_CLASS,
TI ME_WAI TED, r ound( TI ME_WAI TED/ TOT_WAI T*100, 2) TI ME_WAI TED_PCT, TI ME_WAI TED_FG,
r ound( TI ME_WAI TED_FG/ TOT_WAI T*100, 2) TI ME_WAI TED_FG_PCT
f r omV$SYSTEM_WAI T_CLASS, ( sel ect sum( TI ME_WAI TED) TOT_WAI T f r om
V$SYSTEM_WAI T_CLASS wher e WAI T_CLASS <>' I dl e' ) ,
( sel ect sum( TI ME_WAI TED_FG) TOT_WAI T_FG f r omV$SYSTEM_WAI T_CLASS wher e WAI T_CLASS
<>' I dl e' )
wher e WAI T_CLASS <>' I dl e'
or der by TI ME_WAI TED_FG_PCT DESC


Page 348 Oracle DBA Code Examples

- - Wai t Cl asses by I nst ance Wi de i n t he Last Hour
sel ect
TO_CHAR( BEGI N_TI ME, ' HH24: MI ' ) BEGI N_TI ME,
TO_CHAR( END_TI ME, ' HH24: MI ' ) END_TI ME,
I NTSI ZE_CSEC/ 100 I nt er val _sec,
WAI T_CLASS#,
( SELECT DI STI NCT WAI T_CLASS FROM V$EVENT_NAME X WHERE
X. WAI T_CLASS#=W. WAI T_CLASS#) WAI T_CLASS_NAME,
TI ME_WAI TED, DBTI ME_I N_WAI T " Pct of DB Ti me spent " , WAI T_COUNT
f r omV$WAI TCLASSMETRI C_HI STORY W
wher e WAI T_CLASS#<>6 - - I dl e
or der by BEGI N_TI ME DESC, TI ME_WAI TED DESC;


- - Wai t Event s by I nst ance Tot al
- - t ypi cal l y wai t s by f or egr ound pr ocesses ar e what we car e about
sel ect
EVENT,
TI ME_WAI TED_FG,
ROUND( TI ME_WAI TED_FG/ TOT_WAI T_FG*100, 2) TI ME_WAI TED_PCT,
TOTAL_WAI TS_FG,
TOTAL_TI MEOUTS_FG,
AVERAGE_WAI T_FG,
WAI T_CLASS,
TOTAL_WAI TS,
TOTAL_TI MEOUTS,
TI ME_WAI TED,
AVERAGE_WAI T
f r omV$SYSTEM_EVENT, ( SELECT SUM( TI ME_WAI TED_FG) TOT_WAI T_FG FROM V$SYSTEM_EVENT
wher e WAI T_CLASS <> ' I dl e' )
wher e WAI T_CLASS <> ' I dl e'
or der by TI ME_WAI TED_FG DESC;

- - i f buf f er busy was on t he t op wai t s, get mor e i nf o about
- - bl ock cont ent i on st at i st i cs
sel ect CLASS, TI ME, COUNT
f r omV$WAI TSTAT
or der by TI ME desc


- - Wai t Event s by Sessi ons
- - det ai l ed i nf or mat i on on V$SESSI ON ( or V$SESSI ON_WAI T )
- - col s i n V$SESSI ON_WAI T al r eady cont ai ned i n V$SESSI ON
sel ect
E. SI D, S. USERNAME, S. MACHI NE, S. MODULE, S. ACTI ON,
S. STATUS,
E. WAI T_CLASS,
E. EVENT,
S. STATE,
WAI T_TI ME,
TI ME_WAI TED,
SECONDS_I N_WAI T,
AVERAGE_WAI T,
P1TEXT,
P1,
P2TEXT,
P2,
Page 349 Oracle DBA Code Examples

P3TEXT,
P3,
TOTAL_WAI TS,
MAX_WAI T,
TOTAL_TI MEOUTS,
ROW_WAI T_OBJ # WAI TED_OBJ ECT,
TO_CHAR( S. LOGON_TI ME, ' HH24: MI ' ) LOGON_TI ME,
S. BLOCKI NG_SESSI ON
f r omV$SESSI ON_EVENT E, V$SESSI ON S
wher e E. SI D = S. SI D
and S. USERNAME NOT I N ( ' SYSTEM' , ' SYS' , ' DBSNMP' , ' SYSMAN' )
and E. WAI T_CLASS <> ' I dl e'
or der by E. TI ME_WAI TED desc
/


- - i f t he pr obl emi n t he l at ch, f ur t her det ai l s can be obt ai ned:
SELECT
ADDR Lat ch_Obj ect _Addr ess,
LATCH#,
LEVEL#,
NAME,
HASH,
GETS,
MI SSES,
case mi sses when 0 t hen 0 el se mi sses/ ( mi sses+GETS+SLEEPS) end MI SSES_RATI O,
SLEEPS,
I MMEDI ATE_GETS,
I MMEDI ATE_MI SSES,
SPI N_GETS,
WAI T_TI ME WAI T_TI ME_US
FROM V$LATCH
or der by MI SSES desc
Active Session History (ASH)
Used when you want to analyze for a previous period not taken yet by AWR (let's say last
10 minutes).
V$ACTIVE_SESSION_HISTORY is flushed into DBA_HIST_ACTIVE_SESS_HISTORY when
AWR is taken (every hour by default).
-- ASH list
SELECT SAMPLE_I D, SAMPLE_TI ME, SESSI ON_I D, SESSI ON_SERI AL#, SESSI ON_TYPE,
FLAGS, USER_I D, SQL_I D, SQL_CHI LD_NUMBER, SQL_OPCODE, FORCE_MATCHI NG_SI GNATURE,
TOP_LEVEL_SQL_I D, TOP_LEVEL_SQL_OPCODE, SQL_PLAN_HASH_VALUE, SQL_PLAN_LI NE_I D,
SQL_PLAN_OPERATI ON, SQL_PLAN_OPTI ONS, SQL_EXEC_I D, SQL_EXEC_START,
PLSQL_ENTRY_OBJ ECT_I D, PLSQL_ENTRY_SUBPROGRAM_I D, PLSQL_OBJ ECT_I D,
PLSQL_SUBPROGRAM_I D, QC_I NSTANCE_I D, QC_SESSI ON_I D, QC_SESSI ON_SERI AL#,
EVENT, EVENT_I D, EVENT#, SEQ#, P1TEXT, P1, P2TEXT, P2, P3TEXT, P3, WAI T_CLASS,
WAI T_CLASS_I D, WAI T_TI ME, SESSI ON_STATE, TI ME_WAI TED, BLOCKI NG_SESSI ON_STATUS,
BLOCKI NG_SESSI ON, BLOCKI NG_SESSI ON_SERI AL#, CURRENT_OBJ #, CURRENT_FI LE#,
CURRENT_BLOCK#, CURRENT_ROW#, CONSUMER_GROUP_I D, XI D, REMOTE_I NSTANCE#,
I N_CONNECTI ON_MGMT, I N_PARSE, I N_HARD_PARSE, I N_SQL_EXECUTI ON,
I N_PLSQL_EXECUTI ON, I N_PLSQL_RPC, I N_PLSQL_COMPI LATI ON, I N_J AVA_EXECUTI ON,
I N_BI ND, I N_CURSOR_CLOSE, SERVI CE_HASH, PROGRAM, MODULE, ACTI ON, CLI ENT_I D
FROM V$ACTI VE_SESSI ON_HI STORY
Wher e SESSI ON_TYPE <> ' BACKGROUND'
and USER_I D not i n ( sel ect u. user _i d f r omdba_user s u wher e user name I N
Page 350 Oracle DBA Code Examples

( ' SYS' , ' SYSTEM' , ' DBSNMP' , ' SYSMAN' ) )
or der by Sampl e_Ti me desc


-- ASH report
- - i nf o about t he SQL t hat r an dur i ng t he t i me you speci f y
$ORACLE_HOME/ r dbms/ admi n/ ashr pt . sql
The ashr pt i . sql l et s you speci f y t he db i nst ance


-- Top Waited-for Objects
SELECT ( SELECT o. obj ect _name
FROM dba_obj ect s o
WHERE o. obj ect _i d = cur r ent _obj #) obj ect _name,
( SELECT o. obj ect _t ype
FROM dba_obj ect s o
WHERE o. obj ect _i d = cur r ent _obj #) obj ect _t ype,
a. event ,
SUM ( a. wai t _t i me + a. t i me_wai t ed) t ot al _wai t _t i me
FROM v$act i ve_sessi on_hi st or y a
WHERE ( a. wai t _t i me + a. t i me_wai t ed ) > 0
AND a. cur r ent _obj # I S NOT NULL
AND a. sampl e_t i me BETWEEN SYSDATE - 15 / 1440 AND SYSDATE
GROUP BY a. event ,
cur r ent _obj #
ORDER BY t ot al _wai t _t i me DESC;


-- Top Waits
SELECT a. event ,
SUM( a. wai t _t i me + a. t i me_wai t ed) t ot al _wai t _t i me
FROM v$act i ve_sessi on_hi st or y a
WHERE a. sampl e_t i me bet ween
sysdat e - 30/ 2880 and sysdat e
GROUP BY a. event
ORDER BY t ot al _wai t _t i me DESC;


-- Top Waiting Users
SELECT s. si d, s. user name,
SUM( a. wai t _t i me +
a. t i me_wai t ed) t ot al _wai t _t i me
FROM v$act i ve_sessi on_hi st or y a,
v$sessi on s
WHERE a. sampl e_t i me bet ween sysdat e - 30/ 2880 and sysdat e
AND a. sessi on_i d=s. si d
GROUP BY s. si d, s. user name
ORDER BY t ot al _wai t _t i me DESC;


-- Top Waiting SQL Statements
SELECT a. user _i d, d. user name, s. sql _t ext ,
SUM( a. wai t _t i me + a. t i me_wai t ed) t ot al _wai t _t i me
FROM v$act i ve_sessi on_hi st or y a,
v$sql ar ea s,
dba_user s d
WHERE a. sampl e_t i me bet ween sysdat e - 30/ 2880 and sysdat e
Page 351 Oracle DBA Code Examples

AND a. sql _i d = s. sql _i d
AND a. user _i d = d. user _i d
GROUP BY a. user _i d, s. sql _t ext , d. user name;

-- Top Resource Consuming SQL
SELECT hash_val ue, execut i ons,
ROUND ( el apsed_t i me/ 1000000, 2) t ot al _t i me,
ROUND ( cpu_t i me/ 1000000, 2) cpu_seconds
FROM ( SELECT * FROM V$SQL
ORDER BY el apsed_t i me desc) ;

-- ASH history
SELECT *
FROM DBA_HI ST_ACTI VE_SESS_HI STORY
Wher e SESSI ON_TYPE <> 2 - - ' BACKGROUND' ( SESSI ON_TYPE i n V$ i s var char 2)
or der by SNAP_I D desc
Segment Statistics
You drill down into segment stats from the instance, sessions or ASM wait stats.
sel ect OWNER, OBJ ECT_TYPE, OBJ ECT_NAME, TABLESPACE_NAME, STATI STI C_NAME, VALUE
f r omV$SEGMENT_STATI STI CS
- - WHERE st at i st i c_name=' buf f er busy wai t s'
or der by val ue desc;
Handling Important Oracle Wait Events
Buffer Busy Waits Check type of block is causing the wait.
Use locally managed tablespaces with ASSM.
Consider using global hash-partitioned indexes.
Tune SQL statements as necessary to fix these waits.
Check that the sar -d utility might indicate high request queues and
service times.
Check your core dump directory is not too big.
db file scattered
read
Reduce the demand for physical I/Os: Raising the buffer cache
component, add missing indexes on key tables, Optimize SQL
statements. Increase the capacity of the system to handle more I/Os.
Db File Sequential
Read
Indicate index usage.
Increase PGA_AGGREGATE_TARGET.
If the objects arent too large, you can use the DEFAULT and KEEP
buffer pools to retain them in memory.
When you have file# and Block# from wait details, you can get the
object name:
sel ect segment _name f r omdba_ext ent s
wher e f i l e_i d = <f i l e#> and <bl ock#> bet ween bl ock_i d and
bl ock_i d + bl ocks - 1 and r ownum= 1
Direct Path Read
and Direct Path
Write
It occurs while performing a direct read or write into the PGA,
bypassing the SGA buffer cache.
Enable PGA auto tuning.
Increase the number of disks.
Page 352 Oracle DBA Code Examples

Free Buffer Waits The number of dirty buffers in cache too high for the db writer.
Increase Db Buffer Cache
Increase DB_WRITER_PROCESSES (one per CPU)
Check the IO
Enqueue Waits

Sessions are waiting for locks held by other sessions.
Query V$ENQUEUE_STAT
sel ect * f r omV$ENQUEUE_STAT
wher e CUM_WAI T_TI ME<>0 OR FAI LED_REQ#<>0
May caused by infrequent commits and dictionary managed tbs.
Latch Free

SELECT a. name " Lat ch Name" ,
a. get s " Get s ( Wai t ) " ,
a. mi sses " Mi sses ( Wai t ) " ,
( 1 - ( mi sses / get s) ) * 100 " Lat ch Hi t Rat i o %"
FROM V$LATCH a
WHERE a. get s ! = 0
UNI ON
SELECT a. name " Lat ch Name" ,
a. get s " Get s ( Wai t ) " ,
a. mi sses " Mi sses ( Wai t ) " ,
100 " Lat ch Hi t Rat i o"
FROM V$LATCH a
WHERE a. get s = 0
ORDER BY 4;
shar ed pool l at ch (and t he l i br ar y cache l at ches) reasons:
An undersized shared pool
Failure to use bind variables
Using dissimilar SQL statements and failing to reuse statements
Users frequently logging off and logging back into the application
Failure to keep cursors open after each execution
Using a shared pool size thats too large
cache buf f er s LRU chai n and cache buf f er chai n may be caused
by table full scan or unselective indexes.

Log Buffer Space

Check I/O to the redo log disk
Consider increasing LOG_BUFFER (so that Log File Sync wait event
doesn't increase as well)
For a materialized view with COMPLETE refresh, consider setting
ATOMIC_REFRESH=false in DBMS_MVIEW.REFRESH to avoid logging
Log File Switch Check the archive destination isn't full.
Increase sizes of redo log files.
Increase the number of archiver (ARCn) processes. Small values lead to
"redo log space requests" in V$SYSSTAT
Log File Sync

Too-frequent commits
Redo Log I/O bottleneck
library cache pin It occurs when you are compiling or parsing a PL/SQL object or a view
and Oracle wants to pin an object in memory in the library cache and
Page 353 Oracle DBA Code Examples

ensure no other processes can update the object at the same time.

This is my script for tracking down who is blocking who in the event of
a library cache pin event:
sel ect decode( l ob. kgl obt yp, 0, ' NEXT OBJ ECT' , 1, ' I NDEX' , 2,
' TABLE' , 3, ' CLUSTER' ,
4, ' VI EW' , 5, ' SYNONYM' , 6, ' SEQUENCE' ,
7, ' PROCEDURE' , 8, ' FUNCTI ON' , 9, ' PACKAGE' ,
11, ' PACKAGE BODY' , 12, ' TRI GGER' ,
13, ' TYPE' , 14, ' TYPE BODY' ,
19, ' TABLE PARTI TI ON' , 20, ' I NDEX PARTI TI ON' , 21, ' LOB' ,
22, ' LI BRARY' , 23, ' DI RECTORY' , 24, ' QUEUE' ,
28, ' J AVA SOURCE' , 29, ' J AVA CLASS' , 30, ' J AVA RESOURCE' ,
32, ' I NDEXTYPE' , 33, ' OPERATOR' ,
34, ' TABLE SUBPARTI TI ON' , 35, ' I NDEX SUBPARTI TI ON' ,
40, ' LOB PARTI TI ON' , 41, ' LOB SUBPARTI TI ON' ,
42, ' MATERI ALI ZED VI EW' ,
43, ' DI MENSI ON' ,
44, ' CONTEXT' , 46, ' RULE SET' , 47, ' RESOURCE PLAN' ,
48, ' CONSUMER GROUP' ,
51, ' SUBSCRI PTI ON' , 52, ' LOCATI ON' ,
55, ' XML SCHEMA' , 56, ' J AVA DATA' ,
57, ' SECURI TY PROFI LE' , 59, ' RULE' ,
62, ' EVALUATI ON CONTEXT' ,
' UNDEFI NED' ) obj ect _t ype,
l ob. KGLNAOBJ obj ect _name,
pn. KGLPNMOD l ock_mode_hel d,
pn. KGLPNREQ l ock_mode_r equest ed,
ses. si d,
ses. ser i al #,
ses. user name
FROM x$kgl pn pn, v$sessi on ses, x$kgl ob l ob, v$sessi on_wai t vsw
WHERE
pn. KGLPNUSE = ses. saddr and
pn. KGLPNHDL = l ob. KGLHDADR
and l ob. kgl hdadr = vsw. p1r aw
and vsw. event = ' l i br ar y cache pi n'
or der by l ock_mode_hel d desc
direct path read
temp
This happens in:
The sorts are too large to fit in memory and some of the sort data is
written out directly to disk.
Parallel slaves are used for scanning data.
This is the biggest wait for large data warehouse sites.
Consider setting sort_area_size or pga_aggreagate_target
enq: JI - contention The session is waiting for a materialized view to finish its undergoing
refresh. For example, you are trying to refresh two materialized views
reading from same master table(s) in the same time. Another example,
you are trying to compile a materialized view when another session is
refreshing it.
List of Idle Waits Events
On Oracle 10g, the idle waits events are:
AQ Pr oxy Cl eanup Wai t
ASM backgr ound t i mer
DI AG i dl e wai t
EMON i dl e wai t
Page 354 Oracle DBA Code Examples

KSV mast er wai t
LNS ASYNC ar chi ve l og
LNS ASYNC dest act i vat i on
LNS ASYNC end of l og
LogMi ner : cl i ent wai t i ng f or t r ansact i on
LogMi ner : sl ave wai t i ng f or act i vat e message
LogMi ner : wakeup event f or bui l der
LogMi ner : wakeup event f or pr epar er
LogMi ner : wakeup event f or r eader
Nul l event
PX Deq Cr edi t : need buf f er
PX Deq Cr edi t : send bl kd
PX Deq: Execut e Repl y
PX Deq: Execut i on Msg
PX Deq: Par Recov Execut e
PX Deq: Si gnal ACK
PX Deq: Tabl e Q Nor mal
PX Deq: Tabl e Q Sampl e
PX Deque wai t
PX I dl e Wai t
Queue Moni t or Shut down Wai t
Queue Moni t or Sl ave Wai t
Queue Moni t or Wai t
SQL*Net message f r omcl i ent
SQL*Net message t o cl i ent
SQL*Net mor e dat a f r omcl i ent
STREAMS appl y coor d wai t i ng f or sl ave message
STREAMS appl y sl ave i dl e wai t
STREAMS appl y sl ave wai t i ng f or coor d message
STREAMS capt ur e pr ocess f i l t er cal l back wai t f or r ul eset
STREAMS f et ch sl ave wai t i ng f or t xns
STREAMS wai t i ng f or subscr i ber s t o cat ch up
St r eams AQ: RAC qmn coor di nat or i dl e wai t
St r eams AQ: deal l ocat e messages f r omSt r eams Pool
St r eams AQ: del et e acknowl edged messages
St r eams AQ: qmn coor di nat or i dl e wai t
St r eams AQ: qmn sl ave i dl e wai t
St r eams AQ: wai t i ng f or messages i n t he queue
St r eams AQ: wai t i ng f or t i me management or cl eanup t asks
St r eams f et ch sl ave: wai t i ng f or t xns
cl ass sl ave wai t
cl i ent message
di spat cher t i mer
gcs f or act i on
gcs r emot e message
ges r emot e message
i / o sl ave wai t
j obq sl ave wai t
knl qdeq
l ock manager wai t f or r emot e message
mast er wai t
nul l event
par al l el quer y dequeue
pi pe get
pmon t i mer
queue messages
r dbms i pc message
Page 355 Oracle DBA Code Examples

r dbms i pc r epl y
r el i abl e message
sl ave wai t
smon t i mer
vi r t ual ci r cui t st at us
wai t f or act i vat e message
wai t f or unr ead message on br oadcast channel
wakeup event f or bui l der
wakeup event f or pr epar er
wakeup event f or r eader
wakeup t i me manager
Using Performance Monitor Tool in Windows
Instant monitor: click on the '+' icon to start up new counters. Click on 'Process' under
'Performance Object'. Select counters, 'Private Bytes' (what Task Manager shows),
Thread Count, 'Handle Count', and 'Virtual Bytes' in the 'Select counters from list' window.
Also select the process, 'Oracle' in the 'Select instance from list' window. Click on the
'Add' button.
Scheduled monitor: click Counter Logs node, right click on the right hand side pane, select
New Log Settings, type the name, select the objects to monitor, set the schedule and the
generated log file.
Using OS Watcher for Windows
OS Watcher for Unix and Linux, see Using OS Watcher for Linux.
OS Watcher for Windows (OSWFW) is several batch files that run the Windows utility
logman and schtasks.
If OSWFW is installed on RAC, when it is first run, it will read the Cluster Registry and
copy itself to the other nodes in a directory that is the same name as the directory it was
first unzipped in.
Its reference is Note 433472.1
/ * Removi ng OSWFW*/
oswat cher r emove


/ * I ni t i al l y conf i gur e OSWFW*/
OSWat cher {ARG1} {ARG2} {ARG3}
ARG1 = Snapshot i nt er val i n seconds
ARG2 = Runt i me I nt er val - hour s OSWat cher wi l l r un
ARG3 = RAC - det ect Real Appl i cat i on Cl ust er

OSWat cher 30 48


/ * OSWat cher st op */
OSWat cher st op {node name}


/ * Get t i ng t he St at us of OSWFW*/
OSWat cher st at us

Page 356 Oracle DBA Code Examples


/ * Quer yi ng det ai l s of a speci f i c count er or t ask */
OSWat cher quer y {node name} {count er / OSWCl eanup / OSWPr i vNet }
OSWat cher quer y al l
oswat cher quer y OSWThr ead


/ * Ext r act i ng t he Names of t he Count er s i n a Capt ur e Fi l e */
r el og {t r ace_f i l e_name} - q
# t o sor t t he out put :
r el og {t r ace_f i l e_name} - q | sor t / +1
Page 357 Oracle DBA Code Examples

Optimizing Performance in Windows Server
Optimizing Performance in Windows Server 2003
/ * di sabl e un- r equi r ed ser vi ces */
Usual l y, t he f ol l owi ng ser vi ces ar e not r equi r ed i n a dat abase ser ver and can be
di sabl ed:
Al er t er
Cl i pBook
Comput er Br owser
DHCP Cl i ent
DHCP Ser ver
Fax Ser vi ce
Fi l e Repl i cat i on
I Nf r ar ed Moni t or
I nt er net Connect i on Shar i ng
Messenger
Net Meet i ng Remot e Deskt op Shar i ng
Net wor k DDE
Net wor k DDE DSDM
NWLi nk Net BI OS
NWLi nk I PX/ SPX
Pr i nt Spool er
TCP/ I P Net BI OS Hel per Ser vi ce: unl ess member of a domai n
Tel ephony
Tel net
Uni nt er r upt i bl e Power Suppl y


/ * Opt i mi ze Per f or mance f or Backgr ound Ser vi ces */
Or acl e dat abase r uns as a backgr ound ser vi ce.
To i ncr ease per f or mance f or backgr ound ser vi ces, f ol l ow t hese st eps:
1. Cl i ck St ar t , cl i ck Cont r ol Panel , and t hen cl i ck Syst em.
2. Cl i ck t he Advanced t ab, and t hen cl i ck Set t i ngs under Per f or mance.
3. Cl i ck t he Advanced t ab, cl i ck Backgr ound ser vi ces, and t hen cl i ck OK


/ * Opt i mi ze Dat a Thr oughput f or Net wor k Appl i cat i ons */
1. I n Wi ndows Expl or er , r i ght - cl i ck My Net wor k Pl aces, and t hen cl i ck Pr oper t i es.
2. Ri ght - cl i ck t he Local Ar ea Connect i on t hat you want t o opt i mi ze, t hen cl i ck
Pr oper t i es.
3. I n t he Thi s connect i on uses t he f ol l owi ng i t ems l i st , cl i ck ( but do not cl ear
i t s check box) Fi l e and Pr i nt er Shar i ng f or Mi cr osof t Net wor ks, and t hen cl i ck
Pr oper t i es.
4. Cl i ck Maxi mumdat a t hr oughput f or net wor k appl i cat i ons, cl i ck OK, t hen Cl ose.


Page 358 Oracle DBA Code Examples

Tuning the Database Instance
Tuning the Shared Pool
/* Data Dictionary Hit Ratio */
- - ar ound 90 ( dependi ng on t he appl i cat i on, l ow val ue i n some cases accept abl e)
SELECT ( sum( get s - get mi sses - f i xed) ) / SUM( get s) " dat a di ct i onar y hi t r at i o"
f r omv$r owcache;



/* Pinning Objects in the Shared Pool (LC)*/
SELECT t ype, COUNT( *) OBJ ECTS,
SUM( DECODE( KEPT, ' YES' , 1, 0) ) KEPT,
SUM( l oads) - count ( *) r el oads
FROM V$DB_OBJ ECT_CACHE
GROUP BY t ype
ORDER BY obj ect s DESC;

sel ect *
FROM V$DB_OBJ ECT_CACHE
or der by l oads desc;

- - pi n obj ect s wi t h hi gh l oads:
- - un- r et ai ned af t er db r est ar t
- - you can make scr i pt t o l oad t hen when db st ar t s
EXECUTE SYS. DBMS_SHARED_POOL. KEEP( NEW_EMP. PKG, PACKAGE) ;
EXECUTE SYS. DBMS_SHARED_POOL. UNKEEP( NEW_EMP. PKG, PACKAGE) ;


/* Measuring Library Cache Efficiency */
- - l i b cache hi t r at i o
SELECT SUM( pi nhi t s) / sum( pi ns) Li br ar y_cache_hi t _r at i o
FROM V$LI BRARYCACHE;


- - st at ement r el oads
SELECT namespace, pi ns, pi nhi t s, r el oads
FROM V$LI BRARYCACHE
ORDER BY namespace;


- - l i b cache memor y usage
sel ect LC_NAMESPACE, LC_I NUSE_MEMORY_OBJ ECTS, LC_I NUSE_MEMORY_SI ZE,
LC_FREEABLE_MEMORY_OBJ ECTS, LC_FREEABLE_MEMORY_SI ZE
f r omV$LI BRARY_CACHE_MEMORY
or der by LC_I NUSE_MEMORY_OBJ ECTS desc, LC_I NUSE_MEMORY_SI ZE desc,
LC_FREEABLE_MEMORY_OBJ ECTS desc, LC_FREEABLE_MEMORY_SI ZE desc;


- - t o est i mat e t he opt i mal shar ed pool si ze
- - you can j ust set t he MEMORY_TARGET
sel ect SHARED_POOL_SI ZE_FOR_ESTI MATE, SHARED_POOL_SI ZE_FACTOR, ESTD_LC_SI ZE,
ESTD_LC_MEMORY_OBJ ECTS, ESTD_LC_TI ME_SAVED, ESTD_LC_TI ME_SAVED_FACTOR,
ESTD_LC_LOAD_TI ME, ESTD_LC_LOAD_TI ME_FACTOR, ESTD_LC_MEMORY_OBJ ECT_HI TS
f r omV$SHARED_POOL_ADVI CE
Page 359 Oracle DBA Code Examples

or der by SHARED_POOL_SI ZE_FOR_ESTI MATE desc;


- - i f l i t er al val ues r at her t han bi nd val ues ar e used
- - by t he appl i cat i ons ( hi gh har d par se) :
CURSOR_SHARI NG=FORCE ( r ecommended) or SI MI LAR ( not EXACT)


/* Setting CURSOR_SPACE_FOR_TIME */
I f CURSOR_SPACE_FOR_TI ME=TRUE, you ensur e t hat t he cur sor s f or t he appl i cat i on
cannot be deal l ocat ed whi l e t he appl i cat i on cur sor s ar e st i l l open. I t wi l l t hen
el i mi nat e t he Or acl e s over head t o check whet her t he cur sor i s f l ushed f r omt he
l i br ar y cache.
I t wi l l r esul t i n i ncr ease i n t he shar ed pool memor y.


/* Setting SESSION_CACHED_CURSORS */
I t ensur es t hat f or any cur sor f or whi ch mor e t han t hr ee par se r equest s ar e made,
t he par se r equest s ar e aut omat i cal l y cached i n t he sessi on cur sor cache. I t avoi ds
hi gh sof t par se.
Good t o use i n For ms- based apps.
ALTER SESSI ON SET SESSI ON_CACHED_CURSORS = val ue;

I f t he val ue of sessi on cur sor cache hi t s i s l ow compar ed t o t he t ot al par se count
f or a sessi on, t hen t he SESSI ON_CACHED_CURSORS par amet er val ue shoul d be i ncr eased
( al so good t o make i t l ar ger t han OPEN_CURSORS) :

sel ect NAME, VALUE
f r omv$sysst at
wher e name = ' sessi on cur sor cache hi t s'

sel ect SI D, NAME, VALUE
f r omv$sesst at , V$STATNAME
wher e V$SESSTAT. STATI STI C# = V$STATNAME. STATI STI C#
and NAME LI KE ' par se count ( t ot al ) '
or der by VALUE desc

al t er syst emset SESSI ON_CACHED_CURSORS=300 scope=spf i l e ;
Tuning the Buffer Cache
/* Sizing the Buffer Cache */
- - use MEMORY_TARGET
- - si ze assi gned t o i t
sel ect cur r ent _si ze/ 1024/ 1024
f r omV$SGA_DYNAMI C_COMPONENTS
wher e component = ' DEFAULT buf f er cache'


- - di f f er ent ar eas i n t he buf f er cache
sel ect count ( *) bl ocks, St at e
f r om(
sel ect decode ( st at e,
0, ' Fr ee' ,
1, decode ( l r ba_seq, 0, ' Avai l abl e' , ' Bei ng Used' ) ,
3, ' Bei ng Used' ,
Page 360 Oracle DBA Code Examples

st at e) St at e
f r omx$bh )
gr oup by r ol l up( st at e)
or der by count ( *) desc;


- - t o get t he buf f er cache hi t r at i o
SELECT NAME, PHYSI CAL_READS, DB_BLOCK_GETS, CONSI STENT_GETS,
r ound( 1 - ( PHYSI CAL_READS/ ( DB_BLOCK_GETS + CONSI STENT_GETS) ) , 4) *100 " Hi t Rat i o"
FROM V$BUFFER_POOL_STATI STI CS;


/* Using Multiple Pools for the Buffer Cache */
- - x$bh: cont ai ns a r ecor d ( t he buf f er header ) f or each bl ock i n t he buf f er
sel ect count ( *) , St at e f r om(
sel ect decode ( st at e,
0, ' Fr ee' ,
1, decode ( l r ba_seq, 0, ' Avai l abl e' , ' Bei ng Used' ) ,
3, ' Bei ng Used' ,
st at e) St at e
f r omx$bh )
gr oup by st at e


/* Sizing the Buffer Cache */
- - use MEMORY_TARGET

- - t o get t he buf f er cache hi t r at i o
SELECT NAME, PHYSI CAL_READS, DB_BLOCK_GETS, CONSI STENT_GETS,
r ound( 1 - ( PHYSI CAL_READS/ ( DB_BLOCK_GETS + CONSI STENT_GETS) ) , 4) *100 " Hi t Rat i o"
FROM V$BUFFER_POOL_STATI STI CS;


/* Using Multiple Pools for the Buffer Cache */
- - To det er mi ne obj ect s t hat ar e candi dat es f or t he r ecycl e buf f er pool
- - x$bh: cont ai ns a r ecor d ( t he buf f er header ) f or each bl ock i n t he buf f er
sel ect
obj obj ect ,
o. obj ect _name,
count ( *) buf f er s,
r ound( ( count ( *) / t ot si ze) * 100, 2) per cent _cache
FROM x$bh, ( sel ect count ( *) t ot si ze FROM x$bh ) , DBA_OBJ ECTS o
WHERE ( t ch=1 - - t ouch count
OR ( t ch = 0 and l r u_f l ag <10) )
and obj =o. obj ect _i d( +)
GROUP BY obj , o. obj ect _name, t ot si ze
havi ng r ound( ( count ( *) / t ot si ze) * 100, 2) > 1
or der by per cent _cache desc;

- - obj ect s candi dat e f or keep pool
- - obj ect s of at l east 25 buf f er s and have an aver age t ouch count of mor e t han 5
SELECT obj obj ect , o. obj ect _name,
count ( *) buf f er s,
AVG( t ch) aver age_t ouch_count
FROM x$bh, dba_obj ect s o
WHERE obj =o. obj ect _i d( +) and
l r u_f l ag = 8
Page 361 Oracle DBA Code Examples

GROUP BY obj , o. obj ect _name
HAVI NG avg( t ch) > 5 AND count ( *) > 25
or der by avg( t ch) desc


- - def i ne t he ar eas
DB_KEEP_CACHE_SI ZE=16MB
DB_RECYCLE_CACHE_SI ZE=16MB


- - change t he t abl e' s pool
ALTER TABLE t est 1 STORAGE ( buf f er _pool keep) ;
ALTER TABLE t est 2 STORAGE ( buf f er _pool r ecycl e) ;
Tuning PGA
- - PGA st at s
SELECT NAME, VALUE, UNI T FROM V$PGASTAT

- - PGA used by each sessi on
SELECT
s. si d, a. user name, r ound( s. val ue/ 1024, 2) KB
FROM
V$SESSTAT S, V$STATNAME N, V$SESSI ON A
WHERE
n. STATI STI C# = s. STATI STI C# and
name = ' sessi on pga memor y'
AND s. si d=a. si d
ORDER BY s. val ue desc;

- - PGA used by sessi ons
sel ect PI D, SERI AL#, CATEGORY, r ound( ALLOCATED/ 1024, 2) ALLOCATED_KB1,
USED, r ound( MAX_ALLOCATED/ 1024, 2) MAX_ALLOCATED_KB
f r omV$PROCESS_MEMORY

- - PGA used by pr ocesses
SELECT
pr ogr am,
pga_used_mem,
pga_al l oc_mem,
pga_f r eeabl e_mem,
pga_max_mem
f r omV$PROCESS;
Dumping the PGA
SQL>conn / as sysdba
SQL> al t er syst emset max_dump_f i l e_si ze=unl i mi t ed;
SQL> connect sys as sysdba
SQL> or adebug set ospi d <OSpi d f r omquer y above f or uni x syst ems>

I f on a MSwi ndows pl at f or myou wi l l need t o at t ach usi ng t he set or api d i nst ead of
set ospi d
SQL> or adebug set or api d <Or api d f r omquer y above>
Page 362 Oracle DBA Code Examples


SQL> or adebug unl i mi t
SQL> or adebug dump er r or st ack 10
SQL> or adebug dump heapdump 536870917
SQL> or adebug t r acef i l e_name ( shows t he pat h and f i l ename i nf or mat i on)
SQL> or adebug cl ose_t r ace ( cl oses t he t r ace f i l e)
SQL>exi t
Using Server Result Cache
For SQL Result Cache, if an underlying table is updated, the result cache will be invalidate
and the statement will be re-executed.
Caution When a session reads from a PL/SQL function result cache, the function body is not
executed. This means, if the function includes any IO or auditing code, this code will not
actually be executed.

SQL Result Cache Restrictions:
Queries against data dictionary objects and temporary tables are not supported.
Queries that use the following SQL functions: CURRENT_DATE, CURRENT_TIMESTAMP,
LOCAL_TIMESTAMP, USERENV/SYS_CONTEXT, SYS_GUID, SYSDATE and SYS_TIMESTAMP
are not supported.
Queries with bind variables can reuse a cached result only for identical variable values.
Results of the queries retrieving non current version of data are not cached in the result
cache.
Results of the flashback queries are not cached.
Restrictions on PL/SQL Function Result Cache include:
The function cannot be defined in a module using invokers rights.
The function cannot be used in an anonymous block.
The function cannot have any OUT or IN OUT parameters.
The function cannot have IN parameters that are BLOB, CLOB, NCLOB, REF CURSOR,
collections, objects, or records.
The function cannot return a BLOB, CLOB, NCLOB, REF CURSOR, OBJECTS, or records. It
can return a collection as long as the collection does not contain one of these types.
/ * Conf i gur i ng Resul t Cache */
RESULT_CACHE_MAX_SI ZE maxi mumamount of SGA memor y ( i n byt es) t hat can be used by
t he Resul t Cache ( t aken f r omshar ed pool ) .
I f t he val ue of t hi s par amet er i s 0, t hen t he f eat ur e i s di sabl ed.

show par amet er RESULT_CACHE_MAX_SI ZE

ALTER SYSTEM SET RESULT_CACHE_MAX_SI ZE =8M;

The par amet er RESULT_CACHE_MAX_RESULT speci f i es t he per cent age of
RESULT_CACHE_MAX_SI ZE t hat any si ngl e r esul t can use.
I t s def aul t val ue i s f i ve.
ALTER SYSTEM SET RESULT_CACHE_MAX_RESULT =25;


Page 363 Oracle DBA Code Examples

The par amet er RESULT_CACHE_REMOTE_EXPI RATI ON speci f i es t he number of mi nut es t hat
a r esul t usi ng a r emot e obj ect i s al l owed t o r emai n val i d. Set t i ng t hi s par amet er
t o 0 ( t he def aul t ) i mpl i es t hat r esul t s usi ng r emot e obj ect s shoul d not be cached.



/ * Cont r ol l i ng Resul t Cache Behavi or */
The RESULT_CACHE_MODE i ni t i al i zat i on par amet er :
MANUAL The Resul t Cache oper at or i s added, onl y i f you use t he RESULT_CACHE hi nt i n
t he SQL quer y.
FORCE The Resul t Cache oper at or i s added t o t he r oot of al l SELECT st at ement s, i f
t hat i s possi bl e. However , i f t he st at ement cont ai ns a NO_RESULT_CACHE hi nt , t hen
t he hi nt t akes pr ecedence over t he par amet er set t i ng.

ALTER SYSTEM SET RESULT_CACHE_MODE =FORCE;
ALTER SESSI ON SET RESULT_CACHE_MODE =FORCE;


SELECT / *+ r esul t _cache */
AVG( SALARY) , E. DEPARTMENT_I D
FROM HR. EMPLOYEES E, HR. DEPARTMENTS D
WHERE E. DEPARTMENT_I D = D. DEPARTMENT_I D GROUP BY E. DEPARTMENT_I D;



/ * PL/ SQL Funct i on Resul t Cache */
CREATE OR REPLACE FUNCTI ON get _name ( i d NUMBER) RETURN VARCHAR2
RESULT_CACHE RELI ES_ON( emp) I S . . .

- - Package speci f i cat i on
CREATE OR REPLACE PACKAGE depar t ment _pks I S
- - Funct i on decl ar at i on
FUNCTI ON get _dept _i nf o ( dept _i d NUMBER) RETURN dept _i nf o_r ecor d RESULT_CACHE;
END depar t ment _pks;

CREATE OR REPLACE PACKAGE BODY depar t ment _pks AS
- - Funct i on def i ni t i on
FUNCTI ON get _dept _i nf o ( dept _i d NUMBER) RETURN dept _i nf o_r ecor d
RESULT_CACHE RELI ES_ON ( EMPLOYEES)
I S
BEGI N . . .


/ * Bypass Resul t Cache */
begi n
DBMS_RESULT_CACHE. BYPASS( TRUE) ;
DBMS_RESULT_CACHE. FLUSH;
end;

exec DBMS_RESULT_CACHE. BYPASS( FALSE) ;



/ * Moni t or i ng Resul t Cache */
- - Memor y t aken f or Resul t Cache
SELECT NAME, ROUND( BYTES/ 1024, 2) KB
FROM V$SGAst at
WHERE upper ( name) l i ke ' %RESULT%' ;
Page 364 Oracle DBA Code Examples


- - obj ect s i n t he r esul t cache
sel ect I D, TYPE, STATUS, BUCKET_NO, HASH, NAME, NAMESPACE, CREATOR_UI D,
DEPEND_COUNT, BLOCK_COUNT, SCN, COLUMN_COUNT, PI N_COUNT, SCAN_COUNT, ROW_COUNT,
ROW_SI ZE_MAX, ROW_SI ZE_MI N, ROW_SI ZE_AVG, BUI LD_TI ME, LRU_NUMBER, OBJ ECT_NO,
I NVALI DATI ONS, SPACE_OVERHEAD, SPACE_UNUSED, CACHE_I D, CACHE_KEY,
t o_char ( CREATI ON_TI MESTAMP, ' HH12: MI AM' ) CREATE_TI ME
f r om V$RESULT_CACHE_OBJ ECTS
or der by t ype desc;

- - r esul t cache st at s
sel ect I D, NAME, VALUE
f r omV$RESULT_CACHE_STATI STI CS;

- - usi ng DBMS_RESULT_CACHE
- - check t he st at us of t he Resul t Cache
- - Not e: t hi s i s t he r el i abl e met hod t o know whet her r esul t cache i s enabl ed or
not
SQL>sel ect DBMS_RESULT_CACHE. STATUS f r omdual ;

- - di spl ay r epor t on r esul t cache memor y
SQL>set ser ver out put on
SQL>exec DBMS_RESULT_CACHE. MEMORY_REPORT

- - t ur n bypass mode on and of f
SQL>exec DBMS_RESULT_CACHE. BYPASS ( TRUE) ;

- - t o f l ush t he r esul t cache
SQL>exec DBMS_RESULT_CACHE. FLUSH
Obtaining Information about Object Locks
- - DML l ocks by t r ansact i ons on obj ect s
SELECT l . obj ect _i d,
l . sessi on_i d,
l . or acl e_user name,
DECODE( l . l ocked_mode,
1, ' No Lock' ,
2, ' Row Shar e' ,
3, ' Row Excl usi ve' ,
4, ' Shar ed Tabl e' ,
5, ' Shar ed Row Excl usi ve' ,
6, ' Excl usi ve' ) l ocked_mode,
( sel ect o. obj ect _name f r om DBA_OBJ ECTS o WHERE o. obj ect _i d=l . obj ect _i d)
obj ect _name
FROM V$LOCKED_OBJ ECT l
or der by ORACLE_USERNAME;

SELECT dbl . l ock_t ype, dbl . mode_hel d, dbl . bl ocki ng_ot her s,
dbo. obj ect _name obj ect _l ocked, dbo. obj ect _t ype
FROM dba_l ocks dbl , v$sessi on v, dba_obj ect s dbo
WHERE v. user name not i n
( ' SYS' , ' SYSTEM' , ' DBSNMP' , ' SYSMAN' , ' OUTLN' , ' TSMSYS' , ' WMSYS' , ' EXFSYS' , ' CTXSYS' , ' XDB'
, ' ORDSYS' , ' MDSYS' , ' OLAPSYS' , ' WKSYS' , ' WK_TEST' , ' I X' )
AND dbl . sessi on_i d = v. si d AND dbo. obj ect _i d = dbl . l ock_i d1;

Page 365 Oracle DBA Code Examples


- - bl ocki ng sessi on
sel ect ADDR, KADDR, l . SI D, s. USERNAME, S. MACHI NE, S. TERMI NAL, S. PROGRAM,
decode( l . TYPE, ' TM' , ' DML enqueue' , ' TX' , ' Tr ansact i on enqueue' , ' UL' , ' User suppl i ed' )
Bl ock_Type,
I D1, I D2, LMODE, REQUEST, CTI ME, BLOCK
f r omv$l ock l , v$sessi on s
wher e s. si d = l . si d
and l . bl ock=1;


- - bl ocki ng and bl ocked sessi ons
SELECT SUBSTR( TO_CHAR( w. sessi on_i d) , 1, 5) WSI D, p1. spi d WPI D,
SUBSTR( s1. user name, 1, 12) " WAI TI NG User " ,
SUBSTR( s1. osuser , 1, 8) " OS User " ,
SUBSTR( s1. pr ogr am, 1, 20) " WAI TI NG Pr ogr am" ,
s1. cl i ent _i nf o " WAI TI NG Cl i ent " ,
SUBSTR( TO_CHAR( h. sessi on_i d) , 1, 5) HSI D, p2. spi d HPI D,
SUBSTR( s2. user name, 1, 12) " HOLDI NG User " ,
SUBSTR( s2. osuser , 1, 8) " OS User " ,
SUBSTR( s2. pr ogr am, 1, 20) " HOLDI NG Pr ogr am" ,
s2. cl i ent _i nf o " HOLDI NG Cl i ent " ,
o. obj ect _name " HOLDI NG Obj ect "
FROM gv$pr ocess p1, gv$pr ocess p2, gv$sessi on s1,
gv$sessi on s2, dba_l ocks w, dba_l ocks h, dba_obj ect s o
WHERE - - w. l ast _conver t > 120 AND ( Obj ect s l ocked f or 2 mi ns)
h. mode_hel d ! = ' None'
AND h. mode_hel d ! = ' Nul l '
AND w. mode_r equest ed ! = ' None'
AND s1. r ow_wai t _obj # = o. obj ect _i d
AND w. l ock_t ype( +) = h. l ock_t ype
AND w. l ock_i d1( +) = h. l ock_i d1
AND w. l ock_i d2 ( +) = h. l ock_i d2
AND w. sessi on_i d = s1. si d ( +)
AND h. sessi on_i d = s2. si d ( +)
AND s1. paddr = p1. addr ( +)
AND s2. paddr = p2. addr ( +)
ORDER BY w. l ast _conver t desc;
Handling a Hanging Database
Archiver Process Stuck. In the alert log file, you'll see: ORA-00257: archiver error.
Connect internal only, until freed.
o Redirect archiving to a different directory.
o Clear the archive log destination by removing some archive logs.
Sys Audit is full. Check and delete $ORACLE_HOME/rdbms/audit
Make sure the OS isn't swapping.
Accurately Measuring Process Size
Some tools like ps and top give you a misleading idea as to the process size, because they
include the common shared TEXT sizes in individual processes.
Page 366 Oracle DBA Code Examples

- - memor y occupi ed by ever y sessi on
SELECT si d, n. name| | ' ( ' | | s. st at i st i c#| | ' ) ' , t o_char ( r ound( val ue/ 1024) , ' 999, 999' )
| | ' KB' KB
FROM v$sesst at s, v$st at name n
WHERE s. st at i st i c# = n. st at i st i c#
AND n. name l i ke ' %ga memor y%'
ORDER BY SI D, val ue DESC;


- - t ot al memor y al l ocat ed t o t he PGA and UGA memor y
SELECT ' Tot al PGA' , r ound( SUM( val ue) / 1024/ 1024, 2) MB
FROM V$SESSTAT s, V$STATNAME n
WHERE s. st at i st i c# = n. st at i st i c#
AND n. name i n ( ' sessi on pga memor y' )
gr oup by n. name
uni on
SELECT ' Tot al UGA' , r ound( SUM( val ue) / 1024/ 1024, 2) MB
FROM V$SESSTAT s, V$STATNAME n
WHERE s. st at i st i c# = n. st at i st i c#
AND n. name i n ( ' sessi on uga memor y' )
gr oup by n. name;


- - anot her way t o know PGA used si ze
sel ect r ound( val ue/ 1024/ 1024, 2) MB f r omV$PGASTAT wher e name=' t ot al PGA i nuse' ;
Page 367 Oracle DBA Code Examples

Managing Automatic Workload Repository (AWR)
The AWR and ADDM are Oracle products that need special licensing through the purchase
of the Diagnostic Pack.
- - To manual l y cr eat i ng a snapshot :
dbms_wor kl oad_r eposi t or y. cr eat e_snapshot ( )


- - t o l i st snapshot s t aken by AWR
sel ect SNAP_I D, STARTUP_TI ME, BEGI N_I NTERVAL_TI ME, END_I NTERVAL_TI ME,
FLUSH_ELAPSED, SNAP_LEVEL, ERROR_COUNT
f r omDBA_HI ST_SNAPSHOT
or der by STARTUP_TI ME DESC, SNAP_I D DESC


- - To dr op a r ange of snapshot s:
dbms_wor kl oad_r eposi t or y. dr op_snapshot _r ange ( l ow_snap_i d => 40, hi gh_snap_i d =>
60, dbi d => 2210828132)

- - To modi f y a AWR set t i ng:
begi n
DBMS_WORKLOAD_REPOSI TORY. MODI FY_SNAPSHOT_SETTI NGS(
r et ent i on => 43200, - - i n mi ns
i nt er val => 30, - - bet ween snaps i n mi ns
dbi d => 3310949047 - - I f NULL, t he l ocal dbi d wi l l be used
) ;
end;
/

- - To get AWR set t i ng
sel ect DBI D, SNAP_I NTERVAL, RETENTI ON
f r omDBA_HI ST_WR_CONTROL;



/ * Cr eat i ng and Del et i ng AWR Snapshot Basel i nes */
begi n
dbms_wor kl oad_r eposi t or y. cr eat e_basel i ne
( st ar t _snap_i d => 125,
end_snap_i d => 185,
basel i ne_name => ' peak_t i me basel i ne' ,
dbi d => 2210828132 ) ;
end;
/

- - t o l i st cr eat ed basel i nes:
sel ect DBI D, BASELI NE_I D, BASELI NE_NAME, START_SNAP_I D, START_SNAP_TI ME,
END_SNAP_I D, END_SNAP_TI ME
f r omDBA_HI ST_BASELI NE
or der by START_SNAP_I D;

- - To dr op a snapshot basel i ne:
- - i f cascade i s t r ue, t he snaps wi l l al so be del et ed
exec dbms_wor kl oad_r eposi t or y. dr op_basel i ne ( basel i ne_name => ' peak_t i me
basel i ne' , cascade => FALSE)
Page 368 Oracle DBA Code Examples




/ * Cr eat i ng AWR Repor t s */
<ORACLE_HOME>\ RDBMS\ ADMI N\ awr r pt . sql
- - al l ows you t o sel ect a si ngl e i nst ance:
<ORACLE_HOME>\ RDBMS\ ADMI N\ awr r pt i . sql
Page 369 Oracle DBA Code Examples

Managing Automated Maintenance Tasks
Automatic Optimizer Statistics Collection
Automatic Segment Advisor
Automatic SQL Tuning Advisor
/ * Obt ai n I nf o about AMTs ( 11g) */

sel ect *
f r omDBA_AUTOTASK_TASK


/ * Moni t or i ng AMT */
SELECT cl i ent _name, st at us,
at t r i but es, wi ndow_gr oup, ser vi ce_name
FROM dba_aut ot ask_cl i ent ;



/ * Enabl i ng and Di sabl ei ng a Mai nt enance Task */
begi n
DBMS_AUTO_TASK_ADMI N. ENABLE
( cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => ' aut omat i c sql t uni ng t ask' ,
wi ndow_name => ' monday_wi ndow' ) ;
end;
/

begi n
dbms_aut o_t ask_admi n. di sabl e
( cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => ' aut omat i c sql t uni ng t ask' ,
wi ndow_name => ' monday_wi ndow' ) ;
end;
/
Using Automatic Database Diagnostic Monitor (ADDM)
The AWR and ADDM are Oracle products that need special licensing through the purchase
of the Diagnostic Pack.
/* Obtain info about ADDM */
- - l i st of al l advi sor s t asks
sel ect * f r omDBA_ADVI SOR_TASKS;

- - f i ndi ngs ( al l advi sor s)
sel ect * f r omDBA_ADVI SOR_FI NDI NGS wher e t ask_name=' ADDM 01012009' ;

- - f i ndi ngs onl y add ADDM
sel ect * f r omDBA_ADDM_FI NDI NGS wher e t ask_name=' ADDM 01012009' ;

- - r ecommendat i ons
sel ect * f r omDBA_ADVI SOR_RECOMMENDATI ONS wher e t ask_name=' ADDM 01012009' ;

Page 370 Oracle DBA Code Examples


/* Setting Up ADDM */
- - CONTROL_MANAGEMENT_PACK_ACCESS shoul d be DI AGNOSTI C or DI AGNOSTI C+TUNI NG
- - STATI STI CS_LEVEL shoul d be TYPI CAL or ALL ( not BASI C)
sel ect name, val ue
f r omv$par amet er wher e upper ( name) i n
( ' CONTROL_MANAGEMENT_PACK_ACCESS' , ' STATI STI CS_LEVEL' ) ;

al t er syst emset cont r ol _management _pack_access=' DI AGNOSTI C+TUNI NG'



/* Determining Optimal I/O Performance */
- - Or acl e assumes t he val ue of t he par amet er ( not i nt i al i zat i on par amet er )
- - DBI O_EXPECTED i s 10 mi l l i seconds.
SELECT PARAMETER_VALUE
FROM DBA_ADVI SOR_DEF_PARAMETERS
WHERE ADVI SOR_NAME=' ADDM'
AND PARAMETER_NAME=' DBI O_EXPECTED'
I f your har dwar e i s si gni f i cant l y di f f er ent , you can set t he par amet er val ue one
t i me f or al l subsequent ADDM execut i ons:
DBMS_ADVI SOR. SET_DEFAULT_TASK_PARAMETER( ' ADDM' , ' DBI O_EXPECTED' , 8000) ;



/* Retreiving AWR snapshots */
SELECT SNAP_I D , I NSTANCE_NUMBER ,
TO_CHAR( BEGI N_I NTERVAL_TI ME, ' DD- MON- RR HH24: MI ' ) BEGI N_TI ME,
TO_CHAR( END_I NTERVAL_TI ME, ' DD- MON- RR HH24: MI ' ) END_TI ME
FROM DBA_HI ST_SNAPSHOT
or der by SNAP_I D desc;



/* Running ADDM in Database Mode */
DECLARE
- - t ask name shoul dn' t exi st s i n db
TNAME VARCHAR2( 50) : =' ADDM DB 01012009' ;
BEGI N
DBMS_ADDM. ANALYZE_DB (
t ask_name =>TNAME, - - i t i s I N OUT par a
begi n_snapshot =>43,
end_snapshot =>44) ;
END;
/

- - al so t he r epor t wi l l t hen be gener at ed
@C: \ or acl e\ or acl edb11g\ RDBMS\ ADMI N\ addmr pt . sql



/* Running ADDM in Instance Mode */
- - used i n RAC
DECLARE
TNAME VARCHAR2( 50) : =' ADDM I NST 01012009' ;
BEGI N
DBMS_ADDM. ANALYZE_I NST (
Page 371 Oracle DBA Code Examples

t ask_name =>TNAME, - - i t i s I N OUT par a
begi n_snapshot =>43,
end_snapshot =>44,
i nst ance_number =>1) ;
END;
/



/* Running ADDM in Partial Mode */
- - subset of al l dat abase i nst ances ( i n RAC)
DECLARE
- - t ask name shoul dn' t exi st s i n db
TNAME VARCHAR2( 50) : =' ADDM PART 01012009' ;
BEGI N
DBMS_ADDM. ANALYZE_PARTI AL (
t ask_name =>TNAME,
begi n_snapshot =>43,
end_snapshot =>44,
i nst ance_number s=>' 1, 2, 3' ) ;
END;
/



/* Displaying an ADDM Report */
SET LONG 1000000 PAGESI ZE 0;
SELECT DBMS_ADDM. GET_REPORT( ' ADDM DB 01012009' ) FROM DUAL;



/* Deleting already created tasks */
exec DBMS_ADDM. DELETE( t ask_name=>' ADDM I NST 01012009' ) ;
Using Automatic SQL Tuning Advisor
When SQL Tunining Advisor is running as an automatic task, it avoids analysing the following:
Parallel queries
Ad hoc queries
Recursive statements
SQL statements that use the INSERT and DELETE statements
SQL statements that use DDL statements such as CREATE TABLE AS SELECT
/ * Obt ai n I nf o about Aut omat i c SQL Tuni ng Advi sor */
sel ect OWNER, TASK_I D, TASK_NAME, EXECUTI ON_NAME, DESCRI PTI ON,
EXECUTI ON_TYPE, EXECUTI ON_TYPE#, EXECUTI ON_START, EXECUTI ON_END,
ADVI SOR_NAME, STATUS, STATUS_MESSAGE, ERROR_MESSAGE
f r omDBA_ADVI SOR_EXECUTI ONS
or der by t ask_i d desc

- - al l SQL compi l at i on and execut i on st at i st i cs
DBA_ADVI SOR_SQLSTATS


Page 372 Oracle DBA Code Examples

DBA_ADVI SOR_SQLPLANS



/ * Conf i gur i ng Aut omat i c SQL Tuni ng */
- - Aut omat i c SQL Tuni ng Advi sor j ob r uns f or a maxi mumof one hour by def aul t
- - i n seconds
exec dbms_sql t une. set _t uni ng_t ask_par amet er ( ' SYS_AUTO _SQL_TUNI NG_TASK' ,
' TI ME_LI MI T' , 14400)

- - ot her par amet er s t o set
ACCEPT_SQL_PROFI LES: TRUE/ FALSE whet her t he dat abase must aut omat i cal l y accept a
SQL pr of i l e
MAX_AUTO_SQL_PROFI LES: maxi mumnumber of aut omat i c SQL pr of i l es al l owed on t he
syst em, i n sum
MAX_SQL_PROFI LES_PER_EXEC: maxi mumnumber of SQL pr of i l es t hat can be
aut omat i cal l y i mpl ement ed per execut i on of t he t ask.

- - t o vi ew cur r ent par amet er val ues:
COLUMN par amet er _val ue FORMAT A30
SELECT par amet er _name, par amet er _val ue
FROM dba_advi sor _par amet er s
WHERE t ask_name = ' SYS_AUTO_SQL_TUNI NG_TASK'
AND par amet er _name I N ( ' ACCEPT_SQL_PROFI LES' ,
' MAX_SQL_PROFI LES_PER_EXEC' ,
' MAX_AUTO_SQL_PROFI LES' ) ;



/ * Enabl i ng and Di sabl e t he aut omat i c advi sor */
- - enabl e i t i n al l mai nt enance wi ndows
begi n
dbms_aut o_t ask_admi n. enabl e (
cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => ' NULL' ,
wi ndow_name=' NULL' ) ;
end;
/

- - i n a speci f i c wi ndow
begi n
dbms_aut o_t ask_admi n. enabl e (
cl i ent _name => ' sql t uni ng advi sor ' ,
oper at i on => ' NULL' ,
wi ndow_name=' monday_ni ght _wi ndow' ) ;
end;
/



/ * Vi ew t he Repor t */
- - di spl ay r epor t of most r ecent execut i on:
VARI ABLE l _r epor t CLOB;
BEGI N
: l _r epor t : = DBMS_SQLTUNE. r epor t _aut o_t uni ng_t ask(
begi n_exec => NULL,
end_exec => NULL,
t ype => DBMS_SQLTUNE. t ype_t ext , - - ' TEXT'
Page 373 Oracle DBA Code Examples

l evel => DBMS_SQLTUNE. l evel _t ypi cal , - - ' TYPI CAL'
sect i on => DBMS_SQLTUNE. sect i on_al l , - - ' ALL'
obj ect _i d => NULL,
r esul t _l i mi t => NULL) ;
END;
/
pr i nt : l _r epor t
Page 374 Oracle DBA Code Examples

Implementing Automatic Memory Management
When you configure the database to use MEMORY_TARGET, you should take into consideration
the following:
The parameter STATISTICS_LEVEL must be set to TYPICAL
If you set the parameters SGA_TARGET and PGA_TARGET, Oracle will consider the values
as the minimum values for SGA and PGA.

Note
You may set PGA_AGGREGATE_TARGET to a value and then a command issued that is heavy on
PGA, Oracle will try to expand the actual PGA size to serve the command. If Oracle could not
find enough free memory in the machine, the following error will be returned:
ORA- 04030: out of pr ocess memor y when t r yi ng t o al l ocat e 8192 byt es ( sor t
subheap, sor t key)
Resolving the issue can be done by reducing the PGA to a lower value. Also, high value of
SORT_AREA_SIZE may cause it. Consider reducing its value (to something like 1MB).

If you do not set the parameters SGA_TARGET and PGA_TARGET (or set them to zero), no
minimum value is considered by Oracle for the SGA and PGA. When the instance starts, it
assigns 60 percent to SGA and 40 percent to the PGA.
When MEMORY_TARGET is configured, the following components are auto tuned: DB
BUFFER CACHE, SHARED POOL, JAVA POOL, LARGE POOL and STREAMS POOL.

Note
On Linux systems, if you receive the following error after setting the MEMORY_TARGET parameter,
most likely the reason is that the /dev/shm is allocated a size (can be known by issuing the
command df - k) less than SGA_MAX_SI ZE:
ORA- 00845: MEMORY_TARGET not suppor t ed on t hi s syst em.
Resolving the issue can be done by the following OS commands:
#umount / dev/ shm
#mount - t t mpf s shmf s - o *si ze=><xx>m* / dev/ shm

show par amet er MEMORY_TARGET
show par amet er MEMORY_MAX_SI ZE

- - dynami c par amet er
ALTER SYSTEM SET MEMORY_TARGET = 410M ;


- - To set a pr oper val ue t o t he par amet er MEMORY_TARGET ( 11g) :
V$MEMORY_TARGET_ADVI CE.
SELECT * FROM V$MEMORY_TARGET_ADVI CE or der by MEMORY_SI ZE desc;


- - To di spl ay cur r ent st at us of t he memor y component s, use t he f ol l owi ng
quer y:
col COMPONENT f or mat a30
SELECT COMPONENT, ROUND( CURRENT_SI ZE/ 1024/ 1024) CURRENT_SI ZE ,
ROUND( MI N_SI ZE/ 1024/ 1024) MI N, ROUND( MAX_SI ZE/ 1024/ 1024) MAX
FROM V$MEMORY_DYNAMI C_COMPONENTS
or der by CURRENT_SI ZE desc;
Page 375 Oracle DBA Code Examples



- - To know how Or acl e has modi f i ed t he memor y ar ea si zes by t i me ( 11g) :
sel ect START_TI ME, END_TI ME, STATUS, COMPONENT, OPER_TYPE, OPER_MODE,
PARAMETER, I NI TI AL_SI ZE/ 1024/ 1024 I NI TI AL_SI ZE_MB,
TARGET_SI ZE/ 1024/ 1024 TARGET_SI ZE_MB, FI NAL_SI ZE/ 1024/ 1024 FI NAL_SI ZE_MB
f r omV$MEMORY_RESI ZE_OPS
or der by START_TI ME, END_TI ME
Page 376 Oracle DBA Code Examples

Configuring DB_nK_CACHE_SIZE
ALTER SYSTEM SET DB_16K_CACHE_SI ZE =1024M;

CREATE TABLESPACE bi g_bl ock_t bs
DATAFI LE ' / t est 01/ app/ or acl e/ bi g_bl ock_01. dbf ' SI ZE 1000M
BLOCKSI ZE 16K;

ALTER TABLE names2 MOVE TABLESPACE bi g_bl ock_t bs;

Page 377 Oracle DBA Code Examples

Managing Optimizer Operations
Setting the Optimizer Mode
OPTI MI ZER_MODE:
ALL_ROWS ( = CHOOSE) maxi mumt hr oughput ( good f or pat ch pr ocessi ng)
FI RST_ROWS_n wher e n 1, 10, 100, 1000 maxi mumr esponse t i me ( good f or i nt er act i ve
apps)
FI RST_ROWS ( depr ecat ed) same as above

SHOWPARAMETER OPTI MI ZER_MODE

sel ect val ue f r omv$par amet er wher e upper ( name) =' OPTI MI ZER_MODE' ;


- - i nst ance l evel :
ALTER SYSTEM SET opt i mi zer _mode = f i r st _r ows_10;

- - sessi on l evel ( PL/ SQL bl ocks won' t be af f ect ed)
ALTER SESSI ON SET opt i mi zer _mode = f i r st _r ows_10;


- - st at ement l evel
sel ect / *+ f i r st _r ows( 10) */ . .
SELECT / *+ ALL_ROWS */ . . .
Defining Access Paths and Joins for the Query Optimizer
Access Paths:
Full Table Scans (FULL)
Rowid Scans
Index Scans:
o Index Unique Scans (INDEX): using UNIQUE or PRIMARY KEY indexes
o Index Range Scans (INDEX, INDEX_ASC, INDEX_DESC, NO_INDEX_RS): <,>,=, Like
on index key
o Index Range Scans Descending (INDEX_DESC): when an order by descending clause
can be satisfied by an index
o Index Skip Scans (INDEX_SS, INDEX_SS_ASC, INDEX_SS_DESC): when there are
few distinct values in the leading column of the composite index and many distinct
values in the nonleading key of the index. For example: INDEX(sex, emp_id) and
select ... where emp_id=100
o Full Scans: it is available if a predicate references one of the columns in the index or
all of the columns in the table referenced in the query are included in the index. It
read single blocks.
o Fast Full Index Scans (INDEX_FFS, INDEX_FFS_ASC, INDEX_FFS_DESC,
NO_INDEX_FFS): when the index contains all the columns that are needed for the
query, and at least one column in the index key has the NOT NULL constraint. It
reads the entire index using multiblock reads, unlike a full index scan, and can be
parallelized.
Page 378 Oracle DBA Code Examples

o Index Joins (INDEX_JOIN): it is a hash join of several indexes that together contain
all the table columns that are referenced in the query.
o Bitmap Indexes (INDEX_COMBINE or INDEX): the optimizer uses a bitmap index to
get the rowids. It requires EE license.
Cluster Access (CLUSTER): when a table is stored in an indexed cluster.
Hash Access (HASH): is used to locate rows in a hash cluster, based on a hash value.
Sample Table Scans: when using SAMPLE [BLOCK] keyword in the select statement.
Joins:
Nested Loop Join (USE_NL, No_USE_NL): for every row in the outer table, Oracle accesses
all the rows in the inner table.
Hash Join (USE_HASH, NO_USE_HASH): used when joining one large table with a small
one. The smaller data source is built into memory as hash table. It then scans the larger
table, probing the hash table to find the joined rows. Euality condition is a must.
Sort Merge (USER_MERGE, NO_USE_MERGE): It performs well when no order is required
on the data source (or already sorted) and the join condition is NOT equality.
Outer Joins: extends the result of a simple join:
o Nested Loop Outer Joins: The outer table will be the one with rows that are
being preserved.
o Hash Join Outer Joins
o Sot Merge Outer Joins
o Full Outer Join
Cartesian: two or more tables with no joins.
/* Access Path Hints */
- - Ful l Tabl e Scans
sel ect / * FULL( t abl e_al i as) */

- - " or der by" mi ght be ser ved by t he i ndex
sel ect / *+ index_DESC( n names3i 2) */
*
f r omnames3 n
wher e name l i ke ' %J Z'
or der by NAME DESC

- - you can i ndi cat e whet her t o save t he bl ock i n buf f er cache
sel ect / * CACHE .
sel ect / * NOCACHE .



- - I ndex Uni que Scan Hi nt s
- - I ndex Uni que Scan as access pat h i s aut o used by t he opt i mi zer
- - you can def i ne t he hi nt t o use t he i ndex t hough:
sel ect / * I NDEX( t abl e_al i as i ndex_name) */ . . .
sel ect / *+ I NDEX( e1 emp_emp_i d_pk) . . */ f r omempl oyees e1, . .

SELECT / *+ i ndex( t 1 t 1_abc) i ndex( t 2 t 2_abc) */ COUNT( *)
FROM t 1, t 2
WHERE t 1. col 1 = t 2. col 1;

Page 379 Oracle DBA Code Examples



- - I ndex Range Scan Hi nt s
- - t o i nst r uct t he opt i mi zer t o use a speci f i c i ndex ( t o avoi d f t s) :
sel ect / * I NDEX( t abl e_al i as i ndex_name) */ . . .
sel ect / *+ I NDEX( e1 emp_emp_i d_pk) . . */ f r omempl oyees e1, . .



- - I ndex Range Scan Descendi ng Hi nt s
- - use i t when an or der by descendi ng cl ause can be sat i sf i ed by an i ndex
sel ect / *+ I NDEX_DESC( t i ndexC) */
* f r omt r y t wher e C < sysdat e or der by C desc

- - excl ude t he i ndex r ange scan access pat h
SELECT / *+ NO_I NDEX_RS( e emp_name_i x) */ l ast _name
FROM empl oyees e
WHERE f i r st _name BETWEEN ' A' AND ' B' ;


- - Fast Ful l I ndex Scan Hi nt s
sel ect / *+ I NDEX_FFS( t i ndexb) */
b
f r omt r y t
wher e t . b=' b'

sel ect / *+ i ndex_f f s_asc( n i 1) */
name
f r omnames2 n
or der by name

SELECT / *+ NO_I NDEX_FFS( i pk_ser v_i nst ) NO_I NDEX_FFS( i i x_ser v_i nst ) */
l at i t ude
FROM ser ver s s, ser v_i nst i
WHERE s. sr vr _i d = i . sr vr _i d;



- - I ndex J oi n Hi nt s
SELECT / *+ I NDEX_J OI N( e emp_manager _i x emp_depar t ment _i x) */ depar t ment _i d
FROM empl oyees e
WHERE manager _i d < 110
AND depar t ment _i d < 50;



- - Bi t map I ndex
- - bi t map i ndexes shoul d be t her e
SELECT / *+ I NDEX_COMBI NE( e emp_manager _i x emp_depar t ment _i x) */ *
FROM empl oyees e
WHERE ( manager _i d = 108) OR ( depar t ment _i d = 110) ;



- - Cl ust er
CREATE CLUSTER sc_sr vr _i d (
sr vr _i d NUMBER( 10) ) SI ZE 1024;
Page 380 Oracle DBA Code Examples


CREATE I NDEX i dx_sc_sr vr _i d ON CLUSTER sc_sr vr _i d;

CREATE TABLE cser ver s
CLUSTER sc_sr vr _i d ( sr vr _i d) AS SELECT * FROM ser ver s;

CREATE TABLE cser v_i nst
CLUSTER sc_sr vr _i d ( sr vr _i d) AS SELECT * FROM ser v_i nst ;

SELECT / *+ CLUSTER( cser ver s) */ sr vr _i d
FROM cser ver s
WHERE sr vr _i d = 503
GROUP BY sr vr _i d;



- - Hash
CREATE CLUSTER st hc_si ( sr vr _i d NUMBER( 10) )
SI ZE 1024 SI NGLE TABLE HASHKEYS 11
TABLESPACE uwdat a;

CREATE TABLE si _hash
CLUSTER st hc_si ( sr vr _i d) AS
SELECT *
FROM ser v_i nst ;

SELECT / *+ HASH( si _hash) */ sr vr _i d
FROM si _hash
WHERE sr vr _i d = 503
GROUP BY sr vr _i d;


- - Sampl e dat a
- - SAMPLE ( 1) : r ead 1%of r ows
- - SAMPLE BLOCK ( 1) : r ead 1%of bl ocks
SELECT * FROM empl oyees SAMPLE BLOCK ( 1) ;



/* Join Operations Hints */

- - Nest ed Loops
sel ect / *+ use_nl ( e d) use_nl ( e j ) */ - - or No_use_nl
empl oyee_i d , depar t ment _name, sal ar y, j . j ob_t i t l e
f r omempl oyees e , depar t ment s d, j obs j
wher e e. depar t ment _i d = d. depar t ment _i d
and e. j ob_i d = j . j ob_i d
and d. depar t ment _i d>10
/


- - Hash J oi n
SELECT / *+ USE_HASH( o l ) */
o. cust omer _i d, l . uni t _pr i ce * l . quant i t y
FROM or der s o , or der _i t ems l
WHERE l . or der _i d = o. or der _i d;

Page 381 Oracle DBA Code Examples


- - Sor t Mer ge
sel ect / *+ use_mer ge( e g) */
empl oyee_i d , l ast _name, gr ade
f r omempl oyees e, gr ades g
wher e e. sal ar y bet ween g. ssal and g. esal ;


- - Ful l Out er J oi n
SELECT d. depar t ment _i d, e. empl oyee_i d
FROM empl oyees e
FULL OUTER J OI N depar t ment s d
ON e. depar t ment _i d = d. depar t ment _i d
ORDER BY d. depar t ment _i d;
Gathering Optimizer Statistics
Gathering Object Statistics
See Collecting Object Statistics. Preferences can be set. See next section.
Collecting Dictionary Object Stats, see below. Recommended every week in off beak
times. It may take considerable time (hours).
/ * Ret r ei ve Gat her ed St at s */
- - t abl e st at s
sel ect OWNER, TABLE_NAME, PARTI TI ON_NAME, PARTI TI ON_POSI TI ON,
SUBPARTI TI ON_NAME, SUBPARTI TI ON_POSI TI ON, OBJ ECT_TYPE, NUM_ROWS, BLOCKS,
EMPTY_BLOCKS, AVG_SPACE, CHAI N_CNT, AVG_ROW_LEN, AVG_SPACE_FREELI ST_BLOCKS,
NUM_FREELI ST_BLOCKS, AVG_CACHED_BLOCKS, AVG_CACHE_HI T_RATI O, SAMPLE_SI ZE,
LAST_ANALYZED, GLOBAL_STATS, USER_STATS, STATTYPE_LOCKED, STALE_STATS
f r omDBA_TAB_STATI STI CS
wher e owner not i n
( ' SYS' , ' SYSTEM' , ' DBSNMP' , ' SYSMAN' , ' OUTLN' , ' TSMSYS' , ' WMSYS' , ' EXFSYS' , ' CTXSYS' , '
XDB' , ' ORDSYS' , ' MDSYS' , ' OLAPSYS' , ' WKSYS' , ' WK_TEST' , ' I X' )
and owner NOT LI KE ' FLOWS_%'
or der by OWNER, LAST_ANALYZED DESC;

- - col st at s
sel ect OWNER, TABLE_NAME, COLUMN_NAME, NUM_DI STI NCT, LOW_VALUE, HI GH_VALUE,
DENSI TY, NUM_NULLS, NUM_BUCKETS, LAST_ANALYZED, SAMPLE_SI ZE, GLOBAL_STATS,
USER_STATS, AVG_COL_LEN, HI STOGRAM
f r omDBA_TAB_COL_STATI STI CS
wher e owner not i n
( ' SYS' , ' SYSTEM' , ' DBSNMP' , ' SYSMAN' , ' OUTLN' , ' TSMSYS' , ' WMSYS' , ' EXFSYS' , ' CTXSYS' , '
XDB' , ' ORDSYS' , ' MDSYS' , ' OLAPSYS' , ' WKSYS' , ' WK_TEST' , ' I X' )
and owner NOT LI KE ' FLOWS_%'
or der by OWNER, LAST_ANALYZED DESC;



/ * Col l ect i ng dat a di ci onar y st at s */
- - f or f i xed t abl es
conn / as sysdba
EXECUTE DBMS_STATS. GATHER_FI XED_OBJ ECTS_STATS

- - f or r eal di ct i onar y t abl es:
- - SYS and SYSTEM user s as wel l as t he owner s of al l dat abase component s
Page 382 Oracle DBA Code Examples

conn / as sysdba
- - i t may t ake hour s t o f i ni sh
EXECUTE DBMS_STATS. GATHER_DI CTI ONARY_STATS
Gathering System Statistics
Gathering mode controlled by GATHERING_MODE parameter:
o No-Workload Mode: implemented by passed NOWORKLOAD. It gathers general I/O
stats.
o Workload Mode: START will manually start the gathering. STOP will manually stops it.
INTERVAL gathering is controlled by INTERVAL parameter.
See Managing OS statistics.
- - st ar t gat her i ng
EXECUTE dbms_st at s. gat her _syst em_st at s( ' st ar t ' ) ;


- - st op gat her i ng and save t he st at s
EXECUTE dbms_st at s. gat her _syst em_st at s( ' st op' ) ;


- - f or t hr ee mi nut es i nt er val
EXECUTE dbms_st at s. gat her _syst em_st at s( ' I NTERVAL' , 3) ;


- - vi ew gat her ed st at s
SELECT
SNAME,
PNAME,
decode( PNAME,
' I OTFRSPEED' , ' I / O t r ansf er Speed ( B/ ms) ' ,
' I OSEEKTI M' , ' Seek+Lat ency+OS Over head Ti me ( ms) ' ,
' SREADTI M' , ' Si ngl e- Bl ock Read Aver age Ti me ( ms) ' ,
' MREADTI M' , ' MBRC Bl ock Sequent i al Aver age Read Ti me ( ms) ' ,
' CPUSPEED' , ' Aver age Number of CPU Cycl es Capt ur ed f or t he Wor kl oad' ,
' CPUSPEEDNW' , ' Aver age Number of CPU Cycl es Capt ur ed f or t he Non- Wor kl oad' ,
' MBR' , ' Aver age Mul t i bl ock Read Count f or Sequent i al r ead ( i n Bl ocks) ' ,
' MAXTHR' , ' Maxi mumI / O Syst emThr oughput ( B/ s) ' ,
' SLAVETHR' , ' Aver age Sl ave I / O Thr oughput ( B/ s) ' ,
PNAME) Descr i pt i on,
PVAL1,
PVAL2
FROM sys. aux_st at s$;
Changing Statistics Preferences
The function DBMS_STATS.GET_PARAMis used to in Oracle 10g to return the default values of parameters of
the DBMS_STATS package. This function is now obsolete in Oracle 11g and replaced with GET_PREFS
procedure. Following is an example:
SET SERVEROUTPUT ON
decl ar e
v_val ue var char 2( 100) ;
begi n
v_val ue : = DBMS_STATS. GET_PREFS (
PNAME =>' STALE_PERCENT' ,
Page 383 Oracle DBA Code Examples

OWNNAME =>' HR' ,
TABNAME =>' EMPLOYEES' ) ;
DBMS_OUPTPUT. PUT_LI NE( v_val ue) ;
end;
Regarding the GET_PREFS function, consider the following:
PNAME parameter indicates the preference name and can take one of the following values:
CASCADE, DEGREE, ESTI MATE_PERCENT, METHOD_OPT, NO_I NVALI DATE, GRANULARI TY, PUBLI SH,
I NCREMENTAL and STALE_PERCENT.
If the OWNNAME and TABNAME are provided and a preference has been entered for the table, the
function returns the preference as specified for the table. In all other cases it returns the global
preference if it has been specified, otherwise the default value is returned.
SET_GLOBAL_PREFS, SET_DATABASE_PREFS, SET_SCHEMA_PREFS, SET_TABLE_PREFS procedures are used
to set the statistics preferences for the global, database, schema or table levels respectively. Following is
an example:
begi n
DBMS_STATS. SET_GLOBAL_PREFS ( PNAME =>' ESTI MATE_PERCENT' , PVALUE =>' 75' ) ;
end;
Similarly, the procedures DELETE_*_PREFS are used to delete current statistics preferences.
EXPORT_*_PREFS and I MPORT_*_PREFS procedures are used to export and import statistics preferences.
Following is an example:
begi n
DBMS_STATS. EXPORT_DATABASE_PREFS(
STATTAB =>' myt abl e' , - - t abl e name t o wher e st at i st i cs shoul d be expor t ed
STATI D =>' pr od_pr ef s' , - - i dent i f i er t o associ at e wi t h t hese st at i st i cs
STATOWN =>' HR' ) ; - - Schema cont ai ni ng st at t ab ( i f ot her t han ownname)
end;
Managing Pending and Published Statistics
Starting with Oracle 11g, when gathering statistics, you have the option to automatically publish the
statistics at the end of the gather operation (default behavior), or to have the new statistics saved as
pending. Saving the new statistics as pending allows you to validate the new statistics and publish them
only if they are satisfactory.
You can check whether or not the statistics will be automatically published checking the value of the
PUBLI SH attribute using the DBMS_STATS package as in the following example:
SELECT DBMS_STATS. GET_PREFS( ' PUBLI SH' ) PUBLI SH FROM DUAL;
You can change the PUBLI SH setting at either the schema or table level. Following are examples to do so:
- - set t i ng PUBLI SH at schema l evel
exec DBMS_STATS. SET_SCHEMA_PREFS( ' HR' , ' PUBLI SH' , ' FALSE' ) ;
- - set t i ng PUBLI SH at t abl e l evel
exec DBMS_STATS. SET_TABLE_PREFS( ' HR' , ' EMPLOYEES' , ' PUBLI SH' , ' FALSE' ) ;
Published statistics are stored in data dictionary views, such as DBA_TAB_STATI STI CS and USER_I ND_
STATI STI CS. Pending statistics are stored in views such as DBA_TAB_PENDI NG_STATI STI CS and
DBA_I ND_PENDI NG_STATI STI CS.
sel ect NUM_ROWS, BLOCKS, AVG_ROW_LEN, SAMPLE_SI ZE, LAST_ANALYZED
f r om DBA_TAB_PENDI NG_STATI STI CS wher e OWNER=' HR' AND TABLE_NAME =' EMPLOYEES' ;
By default, the optimizer uses the published statistics stored in the data dictionary views. If you want the
optimizer to use the newly collected pending statistics, set the initialization parameter
Page 384 Oracle DBA Code Examples

OPTI MI ZER_PENDI NG_STATI STI CS to TRUE (the default value is FALSE), and then run a workload against
the table or schema or just gather its statistics:
ALTER SESSI ON SET OPTI MI ZER_PENDI NG_STATI STI CS = TRUE;
The optimizer will use the pending statistics (if available) instead of the published statistics when
compiling SQL statements. If the pending statistics are valid, they can be made public by executing the
following statement:
- - f or t he whol e dat abase
exec DBMS_STATS. PUBLI SH_PENDI NG_STATS( nul l , nul l ) ;
- - publ i shi ng speci f i c dat abase obj ect pendi ng st at i st i cs
exec DBMS_STATS. PUBLI SH_PENDI NG_STATS( ' HR' , ' EMPLOYEES' ) ;
If you do not want to publish the pending statistics, delete them by executing the following statement:
exec DBMS_STATS. DELETE_PENDI NG_STATS( ' HR' , ' EMPLOYEES' ) ;
Managing Extended Statistics
MultiColumn Statistics
When multiple columns from a single table are used together in the where clause of a query (multiple
single column predicates), Oracle optimizer in previous versions (before 11g) does not understand the
relationship between the columns. In Oracle 11g, statistics on these columns as a group (column group)
can be gathered and thus resulting in high enhancement in CBO cardinality estimation.
You can also create column groups manually by using the CREATE_EXTENDED_STATS function in the
DBMS_STATS package. This function creates a column statistics entry in the system for a user specified
column group or an expression in a table. This function returns a system-generated name of this newly
created entry for the extension.
Note: The optimizer will only use MultiColumn statistics with equality predicates.
Following is an example:
decl ar e
V_NAME VARCHAR2( 30) ;
begi n
- - st at s of t he combi ned col umns wi l l be col l ect ed next t i me t he st at s i s gat her ed
V_NAME : = DBMS_STATS. CREATE_EXTENDED_STATS(
OWNNAME => NULL,
TABNAME => ' EMPLOYEES' ,
EXTENSI ON => ' ( STATE_I D, COUNTRY_I D) ' ) ;
- - you can t hen i ssue t he gat her i ng pr ocess
DBMS_STATS. GATHER_TABLE_STATS ( NULL, ' EMPLOYEES' , METHOD_OPT=' f or al l col umns si ze
skewonl y' ) ;
end;
The DBMS_STATS. GATHER_TABLE_STATS procedure can also be used to create column group and gather its
statistics all in one step. The keyword FOR COLUMNS is used in this case as shown in the following
example:
begi n
DBMS_STATS. GATHER_TABLE_STATS ( ' HR' , ' EMPLOYEES' ,
METHOD_OPT=>' f or al l col umns si ze skewonl y f or col umns ( STATE_I D, COUNTRY_I D) ' ) ;
end;
Page 385 Oracle DBA Code Examples


Note
The default value of METHOD_OPT is 'FOR ALL COLUMNS SI ZE AUTO' which makes Oracle create
column groups for a table, based on the workload analysis, similar to how it is done for
histograms.
You can use the methods in the following code examples to retrieve information on column groups that
have been created:
- - you can quer y t he dat a di ct i onar y USER_STAT_EXTENSI ONS
sel ect EXTENSI ON_NAME, EXTENSI ON f r omUSER_STAT_EXTENSI ONS wher e TABLE_NAME=' EMPLOYEES' ;
- - you can quer y USER_TAB_COL_STATI STI CS ( ext ensi on name appear s as COLUMN_NAME)
sel ect COLUMN_NAME, NUM_DI STI NCT, HI STOGRAM
f r omUSER_TAB_COL_STATI STI CS wher e TABLE_NAME = ' EMPLOYEES' ;
- - you can use DBMS_STATS. SHOW_EXTENDED_STATS_NAME f unct i on
sel ect DBMS_STATS. SHOW_EXTENDED_STATS_NAME( OWNNAME => ' HR' ,
TABNAME => ' EMPLOYEES' ,
EXTENSI ON => ' STATE_I D, COUNTRY_I D' ) AS E_NAME
f r omdual ;
After gathering the multi-column statistics as show in the example, when you check the explain plan for a
query of a where condition like "STATE_I D = ' CA' AND COUNTRY_I D = ' US' ", you will notice that the
optimizer has retrieved the correct number of expected retrieved rows. Practically, this will lead to a
significant improvement in the statement execution.
Following is how to drop a column group that you have previously defined:
exec DBMS_STATS. DROP_EXTENDED_STATS( ' HR' , ' EMPLOYEES' , ' ( STATE_I D, COUNTRY_I D) ' ) ;
Expression Statistics
In Oracle 11g, you can create statistics on an expression. Following are examples to do that:
decl ar e
V_NAME VARCHAR2( 30) ;
begi n
- - t o cr eat e expr essi on ext ended st at s ( not st at i st i cs ar e yet gat her ed)
V_NAME : = DBMS_STATS. CREATE_EXTENDED_STATS(
OWNNAME => NULL,
TABNAME => ' EMPLOYEES' ,
EXTENSI ON => ' ( l ower ( l ast _name) ) ' ) ;
end;
begi n
- - t o cr eat e expr essi on ext ended st at s and gat her t he st at i st i cs i n one st ep
DBMS_STATS. GATHER_TABLE_STATS( OWNNAME=>NULL, TABLE_NAME=>' EMPLOYEES' ,
METHOD_OPT=>' f or al l col umns si ze skewonl y f or col umns ( l ower ( l ast _name) ) ' ) ;
end;
After executing the code above, if you issue a query from EMPLOYEES table with a condition like
LOWER( LAST_NAME) =' ABC' , the optimizer has statistics about the retrieved rows and thus will be able to
estimate the correct number of returned rows. Consequently, the optimizer will most likely create a more
efficient plan than if those statistics were not present.
Use the DBA_STAT_EXTENSI ONS data dictionary view to retrieve information on expression statistics that
have been created in the database.
sel ect EXTENSI ON_NAME, EXTENSI ON f r omUSER_STAT_EXTENSI ONS wher e TABLE_NAME=' EMPLOYEES' ;
Following is an example of the removal of an extended expression statistic:
exec DBMS_STATS. DROP_EXTENDED_STATS( nul l , ' EMPLOYEES' , ' ( l ower ( l at _name) ) ' ) ;
Note that you will not be able to drop an extended expression statistics, if a function-based index is
dependent on that statistic (ORA-20000 error will be returned).
Page 386 Oracle DBA Code Examples

A Simple Approach to Tuning SQL Statements
Identify Problem Statements
o Using V$SQL or SQL Tracing
o AWR report and the ADDM analysis
Locate the Source of the Inefficiency
o Show the EXPLAIN PLAN of the statement
o Use the SQL Access Advisor and SQL Tunining Advisor
Page 387 Oracle DBA Code Examples

Using Application Tracing Tools
Using the SQL Trace Facility and TKPROF
1. Set i ni t par amet er s f or t r ace f i l e management .
They ar e al l syst emand sessi on l evel
STATI STI CS_LEVEL = Typi cal or ALL
Even i f STATI STI CS_LEVEL i s set t o TYPI CAL or ALL, you can keep t he dat abase
f r omt r aci ng by
usi ng:
ALTER SESSI ON st at ement t o set TI MED_STATI STI CS t o FALSE.

show par amet er USER_DUMP_DEST

show par amet er MAX_DUMP_FI LE_SI ZE

2. Enabl e t he SQL Tr ace f aci l i t y f or t he desi r ed sessi on.
- - cur r ent sessi on
ALTER SESSI ON SET sql _t r ace=t r ue;

begi n
sys. dbms_sessi on. set _sql _t r ace( t r ue) ;
end;
/


- - speci f i c sessi on
exec DBMS_SYSTEM. SET_SQL_TRACE_I N_SESSI ON( SI D=>123, SERI AL#=>567, SQL_TRACE=>
t r ue) ;
exec DBMS_MONI TOR. SESSI ON_TRACE_ENABLE( sessi on_i d => 27, ser i al _num=> 60,
wai t s => TRUE, bi nds => FALSE) ;


3. Run TKPROF t o t r ansl at e t he t r ace f i l e i nt o a r eadabl e out put f i l e and
opt i onal l y cr eat e a SQL scr i pt t hat can be used t o st or e t he st at i st i cs i n a
dat abase.
t kpr of f i nance_or a_16340. t r c t est . t xt sys=no expl ai n=y AGGREGATE =yes| no WAI TS
=yes| no


4. I nt er pr et t he out put f i l e.
Row Sour ce Oper at i ons
cr speci f i es consi st ent r eads per f or med by t he r ow sour ce
speci f i es physi cal r eads per f or med by t he r ow sour ce
w speci f i es physi cal wr i t es per f or med by t he r ow sour ce
t i me speci f i es t i me i n mi cr oseconds
Using the Event 10046 to Trace SQL Code
This method is more advanced than the SQL Trace utility.
al t er sessi on set t i med_st at i st i cs = t r ue;
al t er sessi on set st at i st i cs_l evel =al l ;
al t er sessi on set max_dump_f i l e_si ze=unl i mi t ed;
al t er sessi on set event s ' 10046 t r ace name cont ext f or ever , l evel 12' ;
Page 388 Oracle DBA Code Examples

r un t he code t o t r ace
ALTER SESSI ON SET EVENT=' 10046 t r ace name cont ext of f ' ;
- - t r ace f i l e wi l l be i n USER_DUMP_DEST ( usual l y udump f ol der )

- - not r ecommended
ALTER SYSTEM SET EVENT=' 10046 t r ace name cont ext f or ever , l evel 4'
SCOPE=spf i l e;
ALTER SYSTEM SET EVENT=' ' SCOPE=spf i l e;


- - Set t i ng t he 10046 Event For a Sessi on Ot her t han Your Own
- - Met hod 1
- - SPI D known ( OR next )
or adebug set ospi d 1864;
- - PI D known
or adebug set pi d 21;

- - t hen
or adebug event 10046 t r ace name cont ext f or ever , l evel 12
or adebug event 10046 t r ace name cont ext of f

- - Met hod 2
Dbms_syst em. set _ev (
si bi nar y_i nt eger , - - SI D
se bi nar y_i nt eger , - - Ser i al #
ev bi nar y_i nt eger , - - Event code or number t o set .
l e bi nar y_i nt eger , - - Usual l y l evel t o t r ace
cmbi nar y_i nt eger - - When t o t r i gger ( NULL = cont ext f or ever . )
Tracing End to End Application
/ * To speci f y modul e and act i on names */
exec
DBMS_APPLI CATI ON_I NFO. SET_MODULE( MODULE_NAME=>' FI NANCI AL' , ACTI ON_NAME=>' PAYROL
L' ) ;
exec DBMS_APPLI CATI ON_I NFO. SET_ACTI ON( ACTI ON_NAME=>' PAY SLI P' ) ;



/ * To add your own mar ker t o t he t r ace f i l e names */
- - so you can mor e easi l y f i nd t he gener at ed f i l es.
ALTER SESSI ON SET TRACEFI LE_I DENTI FI ER =" f i n_payr ol " ;



/ * Enabl i ng Col l ect i on of Cl i ent and Ser vi ce St at i st i cs */
For cl i ent - Level St at i st i cs use:
DBMS_MONI TOR. CLI ENT_I D_STAT_ENABLE( <cl i ent _i d>)

For Ser vi ce- Level St at i st i cs:
SELECT NAME FROM V$ACTI VE_SERVI CES ;
sel ect ser vi ce_name f r omv$sessi on wher e user name=' HR' ;

- - ser vi ce name case sensi t i ve
DBMS_MONI TOR. SERV_MOD_ACT_TRACE_ENABLE( <ser vi ce_name>, <modul e_name>,
<act i on_name>)
Page 389 Oracle DBA Code Examples

For exampl e:
DBMS_MONI TOR. SERV_MOD_ACT_TRACE_ENABLE( ser vi ce_name=>' APPS1' , modul e_name
=>' PAYROLL' )

To enabl e t r aci ng f or a Ser vi ce named APPS1:
DBMS_MONI TOR. SERV_MOD_ACT_TRACE_ENABLE( ' APPS1' , DBMS_MONI TOR. ALL_MODULES,
DBMS_MONI TOR. ALL_ACTI ONS, TRUE, FALSE, NULL)

To enabl e t r aci ng f or a sessi on:
DBMS_MONI TOR. SESSI ON_TRACE_ENABLE ( SESSI ON_I D=>139, SERI AL_NUM=>53,
WAI TS=>TRUE, BI NDS=>FALSE) ;

To enabl e t r ace i n t he whol e dat abase
DBMS_MONI TOR. DATABASE_TRACE_ENABLE

To enabl e t r ace i n t he i nst ance l evel
DBMS_MONI TOR. DATABASE_TRACE_ENABLE ( I NSTANCE_NAME=>' RAC1' )

To di sabl e t r aci ng:
DBMS_MONI TOR. CLI ENT_I D_STAT_DI SABLE( <Cl i ent _i d>)
DBMS_MONI TOR. SERV_MOD_ACT_TRACE_DI SABLE( ' APPS1' )
DBMS_MONI TOR. DATABASE_TRACE_DI SABLE( I NSTANCE_NAME=>' RAC1' )


/ * Usi ng t he TRCSESS Tool t o Anal yze Tr ace Fi l es */
show par amet er USER_DUMP_DEST

t r csess out put =" hr _r epor t . t r c" ser vi ce=" APPS1" modul e=" PAYROLL" act i on=" bul k
l oad"

You can t hen r un TKPROF agai nst t he consol i dat ed t r ace f i l e t o gener at e a
r epor t :
t kpr of hr _r epor t . t r c out put =hr _t r c_r epor t sys=np SORT=( EXEELA, PRSELA, FCHELA)
Enabling and Disabling Statistic Gathering for End to End Tracing
- - f i r st make sur e t he t r ci ng i s enabl ed, see sect i ons above.


- - St at i st i c Gat her i ng f or Cl i ent I dent i f i er
sel ect CLI ENT_I DENTI FI ER f r omV$SESSI ON wher e user name=' SA' ;

EXECUTE DBMS_MONI TOR. CLI ENT_I D_STAT_ENABLE( cl i ent _i d => ' OE. OE' ) ;
EXECUTE DBMS_MONI TOR. CLI ENT_I D_STAT_DI SABLE( cl i ent _i d => ' OE. OE' ) ;


- - St at i st i c Gat her i ng f or Ser vi ce, Modul e, and Act i on
EXECUTE DBMS_MONI TOR. SERV_MOD_ACT_STAT_ENABLE( ser vi ce_name => ' ACCTG' ,
modul e_name => ' PAYROLL' ) ;
EXECUTE DBMS_MONI TOR. SERV_MOD_ACT_STAT_ENABLE( ser vi ce_name => ' ACCTG' ,
modul e_name => ' GLEDGER' , act i on_name => ' I NSERT I TEM' ) ;
EXECUTE DBMS_MONI TOR. SERV_MOD_ACT_STAT_DI SABLE( ser vi ce_name => ' ACCTG' ,
modul e_name => ' GLEDGER' , act i on_name => ' I NSERT I TEM' ) ;



/ * Vi ewi ng t he New St at i st i cs */
Page 390 Oracle DBA Code Examples

DBA_ENABLED_AGGREGATI ONS enabl ed st at i st i cs aggr egat i on
DBA_ENABLED_TRACES enabl ed t r aces i n t he syst em
V$CLI ENT_STATS st at i st i cs on a cl i ent l evel ( CLI ENT_I DENTI FI ER based)
V$SERVI CE_STATS Di spl ays basi c per f or mance st at i st i cs
V$SERV_MOD_ACT_STATS st at i st i cs f or a combi nat i on of ser ve / modul e/ act i on
names.
Page 391 Oracle DBA Code Examples

Writing Efficient SQL
Efficient WHERE Clauses
o Select with high selectivity gets advantage from index. FTS performs better with low
selectivity queries.
o Whe using SQL functions, consider using function-based indexes.
Using the Right Joins
o Performing filtering operations early reduces the number of rows to be joined in later
steps.
o Always consider usinjg the equi join.
o Join in the order that will produce the least number of rows as output to the parent step.
Combine Multiples Scans with CASE Statements
o When you need to calculate multiple aggregates from the same table, avoid writing a
separate query for each aggregate. Use CASE statement instead.
- - t he f ol l owi ng sel ect s:
SELECT COUNT ( *)
FROM empl oyees
WHERE sal ar y < 2000;
SELECT COUNT ( *)
FROM empl oyees
WHERE sal ar y BETWEEN 2000 AND 4000;
SELECT COUNT ( *)
FROM empl oyees
WHERE sal ar y>4000;

- - can be r e wr i t t en as:
SELECT COUNT ( CASE WHEN sal ar y < 2000 THEN 1 ELSE nul l END) count 1,
COUNT ( CASE WHEN sal ar y BETWEEN 2001 AND 4000 THEN 1 ELSE nul l END) count 2,
COUNT ( CASE WHEN sal ar y > 4000 THEN 1 ELSE nul l END) count 3
FROM empl oyees;
Efficient Subquery Execution
o Oracle recommends using the IN clause if the subquery has the selective WHERE clause.
o If the parent query contains the selective WHERE clause, use the EXISTS clause rather
than the IN clause.
- - t he f ol l woi ng ( sel ect i ve pr edi cat e i n t he sub quer y)
WHERE EXI STS ( SELECT 1 FROM or der s o
WHERE e. empl oyee_i d = o. sal es_r ep_i d
AND o. cust omer _i d = 144) ;
- - can be conver t ed i nt o:
WHERE e. empl oyee_i d I N ( SELECT o. sal es_r ep_i d
FROM or der s o
WHERE o. cust omer _i d = 144) ;

- - i n t he f ol l owi ng ( sel ect i ve pr edi cat e i n t he par ent quer y) :
WHERE e. depar t ment _i d = 80
AND e. j ob_i d = ' SA_REP'
AND e. empl oyee_i d I N ( SELECT o. sal es_r ep_i d FROM or der s o) ;
- - can be r ewr i t t en as:
WHERE e. depar t ment _i d = 80
Page 392 Oracle DBA Code Examples

AND e. j ob_i d = ' SA_REP'
AND EXI STS ( SELECT 1 FROM or der s o WHERE e. empl oyee_i d = o. sal es_r ep_i d)
Avoid Transformed Columns in the WHERE Clause such as: charcol = numexpr, col1 = NVL
(:b1,col1), NVL (col1,-999) = ., TO_DATE(), TO_NUMBER(), and so on.
Add the predicate versus using NVL() technique.
SELECT empl oyee_num, f ul l _name Name, empl oyee_i d
FROM mt l _empl oyees_cur r ent _vi ew
WHERE ( empl oyee_num= NVL ( : b1, empl oyee_num) ) AND ( or gani zat i on_i d=: 1)
ORDER BY empl oyee_num;
Write Separate SQL Statements for Specific Tasks: make a very complex statement slightly
less complex by using the UNION ALL operator or use PL/SQL blocks, if possible.
- - t hi s code won' t use t he i ndex bcz somecol i n bot h si des
. .
WHERE . . .
AND somecol umn BETWEEN DECODE( : l oval , ' ALL' , somecol umn, : l oval )
AND DECODE( : hi val , ' ALL' , somecol umn, : hi val ) ;

- - i t can be r ewr i t t en as
. .
WHERE . . .
AND somecol umn BETWEEN : l oval AND : hi val
AND ( : hi val ! = ' ALL' AND : l oval ! = ' ALL' )
UNI ON ALL
. .
WHERE . . .
AND ( : hi val = ' ALL' OR : l oval = ' ALL' ) ;
If possible, define the Join Order using ORDERED or STAR hints. Table with the lowest
percentage of retireved compared to its tolal it candidate to be the driving table.
- - i n t hi s exampl e, a i s t he dr i vi ng t abl e.
SELECT i nf o
FROM t aba a, t abb b, t abc c
WHERE a. acol BETWEEN 100 AND 200
AND b. bcol BETWEEN 10000 AND 20000
AND c. ccol BETWEEN 10000 AND 20000
AND a. key1 = b. key1
AND a. key2 = c. key2;

SELECT / *+ LEADI NG( e2 e1) USE_NL( e1) I NDEX( e1 emp_emp_i d_pk)
USE_MERGE( j ) FULL( j ) */
e1. f i r st _name, e1. l ast _name, j . j ob_i d, sum( e2. sal ar y) t ot al _sal
FROM empl oyees e1, empl oyees e2, j ob_hi st or y j
WHERE e1. empl oyee_i d = e2. manager _i d
AND e1. empl oyee_i d = j . empl oyee_i d
AND e1. hi r e_dat e = j . st ar t _dat e
GROUP BY e1. f i r st _name, e1. l ast _name, j . j ob_i d
ORDER BY t ot al _sal ;
Modifying or Disabling Triggers and Constraints
Restructuring the Data: like using vitual columns, adding new columns or using partitions.
Maintaining Execution Plans Over Time: by using stored statistics or SQL plan baselines.
Use DML with RETURNING Clause: INSERT, UPDATE, or DELETE... RETURNING modify and
then return the data in one call.
Page 393 Oracle DBA Code Examples

var bnd1 NUMBER
var bnd2 VARCHAR2( 30)
var bnd3 NUMBER

UPDATE empl oyees
SET j ob_i d =' SA_MAN' , sal ar y = sal ar y + 1000,
depar t ment _i d = 140
WHERE l ast _name = ' J ones'
RETURNI NG sal ar y*0. 25, l ast _name, depar t ment _i d
I NTO : bnd1, : bnd2, : bnd3;
Consider using Test Case Builder.
Consider using Bitmap Join Indexes on a star model query.
Selecting the Best Join Order: If youre joining three tables, the one with the more
restrictive filter (driving table) should be joined first (after the FROM keyword) to one of the
other two tables.
- - t hi s st at ement i s l ess ef f i ci ent t han t he f ol l owi ng one
sel ect / *+ or der ed */
or der _dat e, or der _t ot al , l i ne_i t em_i d i d, pr oduct _name , quant i t y,
quant i t y*uni t _pr i ce i t em_t pr i ce
f r omor der _i t ems i , PRODUCT_I NFORMATI ON p, or der s o
wher e
or der _dat e bet ween t o_dat e( ' 01- 01- 2010' , ' dd- mm- yyyy' ) and t o_dat e( ' 31- 03-
2010' , ' dd- mm- yyyy' ) and
o. or der _i d=i . or der _i d and
i . pr oduct _i d=p. pr oduct _i d;


- - mor e ef f i ci ent
sel ect / *+ or der ed */
or der _dat e, or der _t ot al , l i ne_i t em_i d i d, pr oduct _name , quant i t y,
quant i t y*uni t _pr i ce i t em_t pr i ce
f r omor der s o, or der _i t ems i , PRODUCT_I NFORMATI ON p
wher e
or der _dat e bet ween t o_dat e( ' 01- 01- 2010' , ' dd- mm- yyyy' ) and t o_dat e( ' 31- 03-
2010' , ' dd- mm- yyyy' ) and
o. or der _i d=i . or der _i d and
i . pr oduct _i d=p. pr oduct _i d;
Page 394 Oracle DBA Code Examples

Improving SQL Processing Techniques
Following are the tips to improve SQL processing, even if you cannot change the code:
Using Partitioned Tables
Using Compression Techniques
CREATE I NDEX i t em_pr oduct _x
ON or der _i t ems( pr oduct _i d)
TABLESPACE or der _i t ems_i ndx_01
COMPRESS;
CREATE I NDEX i t em_pr oduct _x
ON or der _i t ems( pr oduct _i d)
TABLESPACE or der _i t ems_i ndx_01 COMPRESS;
Using Materialized Views
Using Stored Outlines to Stabilize the CBO (and SQL Plan Management in Oracle 11g).
Using Parallel Execution
Page 395 Oracle DBA Code Examples

Using SQL Tuning Advisor
The advisor possible inputs are:
a single statement
SQL tuning set or STS
a SQL identifier from the AWR
a SQL identifier from the cursor cache
To manage the Automatic SQL Tuning Advisor, see Using Automatic SQL Tuning Advisor.
- - r equi r ed pr i v
gr ant advi sor t o your user ;


/ * A si ngl e SQL St at ement */
DECLARE
my_t ask_name VARCHAR2( 30) ;
my_sql t ext CLOB;
BEGI N
my_sql t ext : = ' SELECT / *+ ORDERED */ *
FROM empl oyees e, l ocat i ons l , depar t ment s d
WHERE e. depar t ment _i d = d. depar t ment _i d AND
l . l ocat i on_i d = d. l ocat i on_i d AND
e. empl oyee_i d < : bnd' ;
my_t ask_name : = DBMS_SQLTUNE. CREATE_TUNI NG_TASK(
sql _t ext => my_sql t ext ,
bi nd_l i st => sql _bi nds( anydat a. Conver t Number ( 90) ) ,
user _name => ' HR' ,
scope => ' COMPREHENSI VE' ,
t i me_l i mi t => 60,
t ask_name => ' my_sql _t uni ng_t ask' ,
descr i pt i on => ' Task t o t une a quer y on a speci f i ed empl oyee' ) ;
END;
/


BEGI N
DBMS_SQLTUNE. EXECUTE_TUNI NG_TASK( t ask_name => ' my_sql _t uni ng_t ask' ) ;
END;
/


SET LONG 1000
SET LONGCHUNKSI ZE 1000
SET LI NESI ZE 100
SELECT DBMS_SQLTUNE. REPORT_TUNI NG_TASK( ' my_sql _t uni ng_t ask' ) FROM DUAL;

- - you can quer y:
DBA_ADVI SOR_TASKS
DBA_ADVI SOR_FI NDI NGS
DBA_ADVI SOR_RECOMMENDATI ONS
DBA_ADVI SOR_RATI ONALE
DBA_SQLTUNE_STATI STI CS
DBA_SQLTUNE_PLANS
Page 396 Oracle DBA Code Examples

Part 6 Oracle Automatic Storage
Management (ASM)
Page 397 Oracle DBA Code Examples

Managing Oracle ASM
Obtaining Information about ASM Instance
- - asm: al l di skgr oups mount ed db: di skgr oups mount ed i n asmand connect ed
t o by db
sel ect * f r omV$ASM_DI SKGROUP;

- - asm: dbs connect ed t o t he asm db: asms connect ed by db
sel ect * f r omV$ASM_CLI ENT;

- - asm: di scover ed di sks db: di sks used by db
sel ect * f r omV$ASM_DI SK;

- - asmf i l es
sel ect * f r omV$ASM_FI LE;

- - i nf o about asmt empl at es
sel ect * f r omV$ASM_TEMPLATE;
Creating an ASM Instance
The procedure below does not apply in 11g R2.
- - r equi r ed ser vi ces
<or ahome>\ bi n\ l ocal conf i g add

- - Cr eat i ng t he ASM I nst ance Manual l y ( on Wi ndows XP)
1. Bui l di ng t he ASM Candi dat e " di sks" : f or t est i ng or devel opment pur pose
mkdi r c: \ asmdi sks
ASMTOOL - cr eat e c: \ asmdi sks\ asmdi ska1 150

- - you can use DBCA and avoi d 2, 3, 4

2. Cr eat e a pf i l e wi t h t he name " i ni t +ASM. or a" i n t he f ol der
<ORACLE_HOME>\ dat abase.
I nser t t he f ol l owi ng par amet er s i n t he f i l e:
I NSTANCE_TYPE=ASM
_ASM_ALLOW_ONLY_RAW_DI SKS = FALSE
DB_UNI QUE_NAME = +ASM
ASM_DI SKSTRI NG =' C: \ asmdi sks\ *'
LARGE_POOL_SI ZE = 16M


3. Cr eat e t he ASM i nst ance ser vi ce:
ORADI M - NEW- ASMSI D +ASM - STARTMODE aut o

4. St ar t up t he i nst ance
SET ORACLE_SI D=+ASM
SQLPLUS / AS SYSDBA
SQL> STARTUP FORCE
SQL> SELECT PATH, MOUNT_STATUS FROM V$ASM_DI SK;

SELECT i nst ance_name FROM v$i nst ance;

Page 398 Oracle DBA Code Examples

LSNRCTL STATUS


- - st ar t i ng ASM i n r est r i ct ed mode: DB cannot access i t ( 11g)
- - i n t he ASM i nst ance l evel
SQL>STARTUP RESTRI CT;
- - i n t he di skgr oup l evel
SQL>ALTER DI SKGROUP DATA MOUNT RESTRI CTED;
- - check st at us of di skgr oups
SQL>SELECT NAME, STATE FROM V$ASM_DI SKGROUP;


- - cr eat i ng a t abl espace i n an ASM di skgr oup
CREATE TABLESPACE sampl e DATAFI LE ' +dgr oup1' ;
Managing Disk Groups and Disks in ASM
Fundementals of Managing Disk Groups and Disks
/ * Basi cs */
SELECT PATH, MOUNT_STATUS FROM V$ASM_DI SK;

SQL> STARTUP NOMOUNT
SQL>
CREATE DI SKGROUP dgr oup1 NORMAL REDUNDANCY
FAI LGROUP cont r ol l er 1 DI SK
' c: \ asmdi sks\ asmdi ska1' name f i r st a si ze 150M,
' c: \ asmdi sks\ asmdi ska2'
FAI LGROUP cont r ol l er 2 DI SK
' c: \ asmdi sks\ asmdi skb1' ,
' c: \ asmdi sks\ asmdi skb2'
/

i n t he pf i l e:
ASM_DI SKGROUPS=dgr oup1

SQL> sel ect NAME, SECTOR_SI ZE, BLOCK_SI ZE, ALLOCATI ON_UNI T_SI ZE,
STATE, TYPE, TOTAL_MB
f r omV$ASM_DI SKGROUP

r est ar t

- - r ebal anci ng speed
show par amet er ASM_POWER_LI MI T
ALTER DI SKGROUP dgr oup1 REBALANCE POWER 5;


- - addi ng ext r a di sks
ASMTOOL - cr eat e c: \ asmdi sks\ asmdi ska3 150
ASMTOOL - cr eat e c: \ asmdi sks\ asmdi skb3 150

SQL>
ALTER DI SKGROUP dgr oup1 ADD
FAI LGROUP cont r ol l er 1 DI SK ' c: \ asmdi sks\ asmdi ska3'
FAI LGROUP cont r ol l er 2 DI SK ' c: \ asmdi sks\ asmdi skb3'
/
Page 399 Oracle DBA Code Examples


ALTER DI SKGROUP dgr oup1 REBALANCE POWER 10
/



/ * Dr oppi ng a di sk */
ALTER DI SKGROUP gr oup1 DROP DI SK di sk5;
- - t o cancel a pendi ng dr op:
ALTER DI SKGROUP gr oup1 UNDROP DI SKS;

/ * Dr oppi ng a Di skgr oup */
i n Or acl e 10g:
# t he gr oup must be mount ed on exact l y one node
# non- empt y dgr oup
DROP DI SKGROUP DATA I NCLUDI NG CONTENTS;
# empt y dgr oup
DROP DI SKGROUP DATA;

# I f t he di skgr oup coul d not be mount ed and t he di sks
# wer e t o be r epur posed f or non- ASM uses
use dd command i n uni x

# I f t he di sks wer e t o be r epur posed as an ASM di sk f or a new di skgr oup,
# t hen use t he FORCE opt i on i n t he CREATE DI SKGROUP

i n Or acl e 11g:
# use FORCE i f t he gr oup i s not mount ed ( t r y mount i t f i r st )
DROP DI SKGROUP DATA FORCE I NCLUDI NG CONTENTS FORCE;


/ * Checki ng Di skgr oup */
- - 11g: you can val i dat e t he i nt er nal consi st ency of ASM di skgr oup met adat a.
Summar y of er r or s i s l ogged i n t he ASM al er t l og f i l e.
- - check speci f i c di skgr oup wi t h aut omat i c r epai r
SQL>ALTER DI SKGROUP dat a CHECK;
- - di sabl e aut omat i c r epai r
SQL>ALTER DI SKGROUP dat a CHECK NOREPAI R;
SQL>ALTER DI SKGROUP dat a CHECK REPAI R;
Managing Disk Groups Attributes
Oracle Database 11g introduces a new concept called ASM attributes at the diskgroup level. The
attributes for the diskgroup can be established at create diskgroup time or can be modified using the
ALTER DI SKGROUP command later.
Following are the attributes you can set:
Allocation unit (AU) sizes.
The compat i bl e. r dbms attribute.
The compat i bl e. asmattribute.
di sk_r epai r _t i me in units of minute (M) or hour (H) and is set by the ALTER DI SKGROUP command
The redundancy attribute for a specific template.
The stripping attribute for a specific template.
All of the diskgroup attributes can be queried from the V$ASM_ATTRI BUTE view.
Consider the following examples:
Page 400 Oracle DBA Code Examples

CREATE DI SKGROUP dat a
di sk ' / dev/ r aw/ r aw1' ,
. . .
at t r i but e ' au_si ze' = ' 16M' , ' compat i bl e. asm' = ' 11. 1' ;
ALTER DI SKGROUP dat a SET ATTRI BUTE ' compat i bl e. asm' = ' 11. 1. 0. 0. 0' ;
sel ect NAME, VALUE f r omV$ASM_ATTRI BUTE wher e GROUP_NUMBER=1;
Variable AU Sizes
The default size of Allocation Unit (AU) is 1 MB which is sufficient for most regular databases. However,
when you have databases with TB sizes, you will have enormous number of AUs. With Oracle 11g, AU
size can be specified at diskgroup creation time to 1, 2, 4, 8, 16, 32, or 64MB in size. You can check the
AU size through the following query:
sel ect NAME, ALLOCATI ON_UNI T_SI ZE f r omV$ASM_DI SKGROUP;
Compatibility Settings
Compatibility in ASM is controlled in three ways, as shown below:
COMPATI BLE
initialization
parameter

The compatible initialization parameter can be set for either ASM or the database
instance. It takes one of the following values: 10.1, 10.2, or 11.1.
Setting the initialization parameter to a lesser value than the software release will
exclude availability of the new features introduced in the new release.
RDBMS
Compatibility
This is a diskgroup-level compatibility and is specified by setting the
COMPATI BLE. RDBMS attribute. This attribute determines the minimum COMPATI BLE
database initialization parameter setting for any database instance that uses the disk
group. Its default value is 10.1.
ASM
Compatibility
This is a diskgroup-level compatibility and is specified by setting the COMPATI BLE. ASM
attribute. It determines the minimum software version for an ASM instance that uses
the disk group.
If you assign any of the compatibility setting to a higher value, you cannot later reverse it to a lower
value.
Following are some queries to obtain information about the compatibility settings:
- - di skgr oup compat i bi l i t y set t i ng
sel ect NAME, BLOCK_SI ZE, ALLOCATI ON_UNI T_SI ZE AU_SI ZE, STATE,
COMPATI BI LI TY ASM_COMP, DATABASE_COMPATI BI LI TY DB_COMP
f r omV$ASM_DI SKGROUP;
- - Compat i bi l i t y of t he dat abase cl i ent s t hat use t he ASM
sel ect DB_NAME, STATUS, SOFTWARE_VERSI ON, COMPATI BLE_VERSI ON f r omV$ASM_CLI ENT;
ASM Fast Mirror Resync
Any problems that make a failure group temporarily unavailable are considered transient failures that can
be recovered by the ASM fast mirror resync feature. Disk path malfunctions; such as cable failures, host
bus adapter failures, controller failures, or disk power supply interruptions; can cause transient failures.
ASM fast resync keeps track of pending changes to extents on an OFFLI NE disk during an outage. The
extents are resynced when the disk is brought back online.
Following are the steps to enable and handle this feature:
- - di skgr oup compat i bi l i t y must be set t o 11. 1
ALTER DI SKGROUP dg1 SET ATTRI BUTE ' compat i bl e. asm' = ' 11. 1' ;
ALTER DI SKGROUP dg1 SET ATTRI BUTE ' compat i bl e. r dbms' =' 11. 1' ;
- - speci f y t he dur at i on of t he di sk_r epai r _t i me ( def aul t i s 3. 6 hour )
ALTER DI SKGROUP dg1 SET ATTRI BUTE ' di sk_r epai r _t i me' = ' 5H' ; - - i n hour s
ALTER DI SKGROUP dg1 SET ATTRI BUTE ' di sk_r epai r _t i me' = ' 40M' ; - - mi nut es
- - ver i f y t he at t r i but e set t i ngs
Page 401 Oracle DBA Code Examples

sel ect NAME, VALUE f r omV$ASM_ATTRI BUTE;
- - i f you get an of f l i ne di sk because of a t r ansi ent f ai l ur e, you can see t he
- - r emai ni ng t i me l ef t i n SECONDS bef or e ASM dr ops an of f l i ne di sk
sel ect NAME, HEADER_STATUS, MOUNT_STATUS, MODE_STATUS, STATE, REPAI R_TI MER/ 60 f r om
V$ASM_DI SK WHERE GROUP_NUMBER=1;
- - whi l e t he f i x i s i n pr ogr ess, i f you want t o r eset t he el apsed t i me, j ust t ake
- - t he di sk( s) of f l i ne
ALTER DI SKGROUP dg1 OFFLI NE DI SK d3_0001;
ALTER DI SKGROUP dg1 OFFLI NE DI SKS I N FAI LGROUP f 2;
- - you can al so make a di sk of f l i ne wi t h a r epai r t i me di f f er ent f r omi t s
- - di sk_r epai r _t i me at t r i but e
ALTER DI SKGROUP dg1 OFFLI NE DI SK d3_0001 DROP AFTER 50m;
- - di sks i n a f ai l ur e gr oup ( f 2) can al so be t aken of f l i ne
ALTER DI SKGROUP dg1 OFFLI NE DI SKS I N FAI LGROUP f 2 DROP AFTER 5m;
- - i f t he di sk needs t o be dr opped i mmedi at el y and bef or e t he r epai r t i me has expi r ed
- - Not e: ALTER DI SKGROUP DROP DI SK wi l l not wor k
ALTER DI SKGROUP dg1 OFFLI NE DI SK D3_0001 DROP AFTER 0m;
- - af t er t he di sk( s) ar e f i xed, you can br i ng t hemonl i ne
ALTER DI SKGROUP dg1 ONLI NE ALL;
ALTER DI SKGROUP dg1 ONLI NE DI SK d3_0001;
Monitoring Long-Running Operations
The ALTER DI SKGROUP DROP, RESI ZE, and REBALANCE commands return before the operation is
complete. To monitor progress of these long-running operations, you can query the V$ASM_OPERATI ON
fixed view.
GROUP_NUMBER
Disk group
OPERATI ON
Type of operation: REBAL
STATE
State of operation: QUEUED or RUNNI NG
POWER
Power requested for this operation
ACTUAL
Power allocated to this operation
SOFAR
Number of allocation units moved so far
EST_WORK
Estimated number of remaining allocation units
EST_RATE
Estimated number of allocation units moved per minute
EST_MI NUTES
Estimated amount of time (in minutes) for operation termination
Page 402 Oracle DBA Code Examples

Migrating a Database to ASM
You can use OEM or RMAN as follows:
1. Shut down the database in a consistent mode by using the SHUTDOWN IMMEDIATE
command.
2. Add the DB_CREATE_FILE_DEST and DB_CREATE_ONLINE_LOG_DEST_n parameters, as
well as the new flash recovery area initialization parameters, DB_RECOVERY_FILE_DEST and
DB_ RECOVERY_FILE_DEST_SIZE, to your database parameter file so you can use an OMF-
based file system. Make sure that the two OMF parameters refer to the disk groups that you
want to use in your ASM system.
DB_CREATE_FILE_DEST = '+dgroup1'
DB_RECOVERY_FILE_DEST = '+dgroup2'
3. Delete the control file parameter from the SPFILE, since Oracle will create new control files
in the OMF file destinations by restoring them from the non-ASM database control files.
4. Start the database with the STARTUP NOMOUNT command:
RMAN> CONNECT TARGET;
RMAN> STARTUP NOMOUNT;
5. Restore the old control file in the new location, as shown here:
RMAN> RESTORE CONTROLFILE from '/u01/orcl/oradata/control1.ctl';
6. Mount the database:
RMAN> ALTER DATABASE MOUNT;
7. Use the following command to copy your database files into an ASM disk group:
RMAN> BACKUP AS COPY DATABASE FORMAT +dgroup1;
8. Use the SWITCH command to switch all datafiles into the ASM disk group:
RMAN> SWITCH DATABASE TO COPY;
At this point, all datafiles will be converted to the ASM type. You still have your original
datafile copies on disk, which you can use to restore your database if necessary.
9. Open the database with the following command:
RMAN> ALTER DATABASE OPEN;
10. For each redo log member, use the following command to move it to the ASM system:
RMAN> SQL "alter database rename '/u01/test/log1' to '+dgroup1' ";
11. Archive the current online redo logs, and delete the old non-ASM redo logs. Since RMAN
doesnt migrate temp files, you must manually create a temporary tablespace using the
CREATE TEMPORARY TABLESPACE statement or:
ALTER TABLESPACE TEMP ADD TEMPFILE
ALTER DATABASE TEMPFILE '/u1/temp1' DROP
Moving a Tablespace to ASM
SQL>sel ect name f r omv$dat af i l e wher e t s# = ( sel ect x. t s# f r omv$t abl espace x
wher e x. name=' HRSTBS' ) ;

set or acl e_si d=or a11g
Page 403 Oracle DBA Code Examples

r man t ar get /

sql ' al t er t abl espace hr st bs of f l i ne' ;

BACKUP AS COPY TABLESPACE hr st bs FORMAT ' +dgr oup1' ;

SWI TCH TABLESPACE hr st bs TO COPY;

sql ' al t er t abl espace hr st bs onl i ne' ;
Accessing an ASM instance from DB Console
/ * Met hod 1 */
dr op and r ecr eat e t he emr eposi t or y:
emca - deconf i g dbcont r ol db - r epos dr op
emca - conf i g dbcont r ol db - r epos cr eat e

/ * Met hod 2 */
- Edi t your l i st ener . or a and add an ent r y f or t he ASM i nst ance i n t he SI D_LI ST

( SI D_DESC =
( GLOBAL_DBNAME = My_DB_SI D)
( ORACLE_HOME=d: \ or acl e\ pr oduct \ 10. 2. 0\ db_2)
( SI D_NAME = +ASM)
)

- Rest ar t your l i st ener

- Access DBConsol e ( e. g. wi t h SYS as SYSDBA)

- I n t he " Admi ni st r at i on" or " Ser ver " t ab, cl i ck on t he l i nk cal l ed " Mi gr at e
t o ASM"

- Fi l l i n t he r equi r ed f i el ds and pr ess cont i nue ( i t wont do anyt hi ng yet .
I t s j ust t he f i r st st ep, t o get ASM l i st en as a new OEM t ar get ) .

- I f i t ever compl ai ns about ORA- 1017, you need t o r ecr eat e t he ASM i nst ance
paswor df i l e. Take a backup of i t f i r st i f you f eel bet t er so.

The synt ax f or r ecr eat i ng t he passwor df i l e can be, f or exampl e:

or apwd f i l e=D: \ or acl e\ pr oduct \ 10. 2. 0\ db_2\ dat abase\ PWD+ASM. or a
passwor d=my_passwor d f or ce=y

( of cour se, you must r epl ace t he passwor d and t he pat h wi t h t he one t hat
ser ves your needs)

The ASM t ar get shoul d have been cr eat ed.

Now, you onl y need t o: cl i ck on t he " Dat abase" l i nk on t he r i ght t op of t he DB
Consol e wi ndow, or access t he DB Consol e page agai n. You shoul d see t he ASM
t ar get l i nk bel ow t he l i st ener t ar get . You onl y need t o cl i ck t he l i nk and
youl l get t he ASM home admi ni st r at i on page, f r omDBConsol e.

I f ASM hyper l i nk i s not di r ect l y shown i n t he mai n DBconsol e page, you can
st i l l cl i ck on t he Host name l i nk i n t he l ef t of t he DBConsol e mai n page ( j ust
over t he l i st ener name l i nk) , and once t her e, agai n cl i ck i n t he " Tar get s"
Page 404 Oracle DBA Code Examples

l i nk, and l ast l y i n t he " +ASM_your _DB_host name" l i nk, whi ch t hen wi l l t ake you
t o t he ASM Admi ni st r at i on mai n page.

You al so have t he opt i on of di r ect l y t ypi ng t he f ol l owi ng URL, af t er t he ASM
t ar get i s cr eat ed:
ht t p: / / your _DB_host name: your _DBConsol e_por t / em/ consol e/ dat abase/ osm/ osmSi t emap
?t ype=osm_i nst ance&t ar get =%2BASM_your _DB_host name&event =doLoad
Managing ASM Files
Types of ASM Filenames
1. Fully Qualified ASM Filenames (System Alias)
You use this fully qualified name for referencing existing ASM files. Heres the syntax of an
ASM file using a fully qualified filename:
+gr oup/ dbname/ f i l e_t ype/ t ag. f i l e. i ncar nat i on
2. Numeric ASM Filenames
ASM derives numeric filenames from fully qualified ASM filenames and uses them to refer to
existing files.
+gr oup. f i l e. i ncar nat i on
3. Alias ASM Filenames
You can use ASM alias files both when creating new ASM files and when referring to existing
files. Alias ASM filenames mean that the files are not OMF-managed files. Thus, Oracle wont
automatically remove these files when it does not have any further need for them.
+dgr oup1/ myf i l es/ cont r ol _f i l e1
+dgr oup2/ mydi r / second. dbf
4. Incomplete ASM Filenames
You can use an incomplete ASM filename only when creating files.
+dgr oup1
+dgr oup1( dat af i l e)
Alias Filename Management
Creating Disk Group Directories for Alias Filenames
You must create a directory structure to support your alias filenaming conventions.
ALTER DI SKGROUP dgr oup1 ADD DI RECTORY ' +dgr oup1/ mydi r ' ;
Using Templates with Aliases
dgr oup( t empl at e_name) / al i as
+dgr oup1( spf i l e) / conf i g1
Adding Aliases
You can add a filename alias or rename an existing alias name, using the ADD ALI AS or
RENAME ALI AS clause of the ALTER DI SKGROUP statement.
ALTER DI SKGROUP dgr oup1 ADD ALI AS ' +dgr oup1/ mydi r / second. dbf ' FOR
' +dgr oupA/ sampl e/ dat af i l e/ myt abl e. 342. 3'
You can retrieve created aliases using v$ASM_ALI AS. The REFERENCE_I NDEX column is usable
only for entries that are directory entries in the alias directory. For non-directory entries, it
equals to zero.
Dropping Files and Aliases from a Disk Group
ALTER DI SKGROUP dgr oup1 DROP FI LE ' +dgr oup1/ payr ol l / compensat i on. dbf '
Page 405 Oracle DBA Code Examples

Using ASMCMD Utility
set or acl e_home=c: \ or acl e\ or adb11g
set or acl e_si d=+ASM
asmcmd
hel p
Oracle 11g introduces new commands in the asmcmd utility and it also provides backward compatibility
with Oracle Database 10g ASM instances. Following are summary of some of them:
Command Syntax Description and Examples
l sct [ - gH] [ gr oup]
Lists information about current ASM clients.
>l sct dgr oup1
l sdg [ - gcH] [ gr oup] lists all diskgroups and their attributes.
>l sdg dgr oup2
l sdsk [ - kspt agcHI ] [ - d
di skg_r oup_name] [ pat t er n]
lists the disks that are visible to ASM by scanning the disk
headers of the disks seen by the value of the ASM_DI SKSTRI NG
>l sdsk - k - d DATA *_001
>l sdsk - s - d DATA *_001
>l sdsk - t - d DATA *_001
>l sdsk - c - t - d DATA *_001
>l sdsk - g - t - d DATA *_001
cp [ - i f r ] [ connect _st r i ng: ] sr c_f name
[ connect _st r i ng: ] t gt _f name
cp [ - i f r ]
[ connect _st r i ng: ] sr c_f nameN,
sr c_f nameN+1 . . .
[ connect _st r i ng: ] t gt _di r ect or y

The connect _st r i ng is in the form of:
user _name@host _name[ . por t _number ] . SI D
-i interactive
-f force overwrite (aliases cannot be
overwritten)
-r recursive
Enables you to copy files between ASM disk groups on local
instances to and from remote instances.
>cp +dg1/ vdb. ct f 1 / backups/ vdb. ct f 1
>cp / home/ or acl e/ encr ypt ed. dmp +dg1
>cp vdb. ct f 1 / t mp
# t he t ar get ASM i nst ance must be r egi st er ed wi t h t he
LI STENER
>cp +DATA/ DBA11g/ DATAFI LE/ DOCS_D1. 289. 631914611
sys@r ac1. +ASM: +DATA/ DBA11g1/ dat af i l e/ xxx
r emap
Repairs a range of physical blocks on disk (only blocks exhibiting
read disk I/O errors are repaired) excluding those with corrupted
contents.
Internally, it reads the blocks from a good copy of an ASM mirror
and rewrites them to an alternate location on disk, if the blocks
on the original location cannot be properly read.
r emap <di sk gr oup name> <di sk name> <bl ock r ange>
> r emap DI SK_GRP1 DATA_0001 5000- 5999
Backing up and Restoring Diskgroup Metadata
The md_backup command captures information about ASM disks, diskgroup and failure group
configurations, and template and alias directory structures, and stores them in a user-designated backup
text file. Following is the basic syntax of the command:
md_backup [ - b <backup_f i l e_pat h> ] [ - g di skgr oup_name [ - g di skgr oup_name ] ]
Following is an example of using the command:
md_backup b /tmp/asm_backup.mdb -g dg1 g dg2
If the backup file already exists, you should remove it before issuing the command.
If you issue the md_backup command without any option, it creates a file named as
ambr _backup_i nt er medi at e_f i l e which contains the metadata information of all the mounted
diskgroups.
Page 406 Oracle DBA Code Examples

The md_r est or e command reads the backup file and restores a disk group. You can set its options to
build a script file that contains the SQL statements required to rebuild the ASM components from the
backup file. Following is the syntax of the command and description of its switches:
md_r est or e - b <backup_f i l e> [ - l i ]
[ - t ( f ul l ) | nodg| newdg] [ - f <sql _scr i pt _f i l e>]
[ - g ' <di skgr oup_name>, <di skgr oup_name>, . . . ' ]
[ - o ' <ol d_di skgr oup_name>: <new_di skgr oup_name>, . . . ' ]
- t
type of restore.
f ul l tag specifies that all the diskgroups should be re-created using the same configuration from
the MDB backup file.
nodg restore metadata only and skip the diskgroup creation.

newdg create disk group with a different name and restore metadata; - o is required. This tag is
used to allow the user to change diskgroup name.
- f
write SQL commands to <sql _scr i pt _f i l e>instead of executing them.
- o
override option is used only with the newdg option to remap the diskgroup name, disk name,
paths, and failure groups.
- i
ignore errors. By default, the command aborts when it encounters an error.
- l
log all messages to a log file.
Following are examples of using the command:
/ * Gener al Exampl es */
# To per f or ma r est or e of t he dg1 di skgr oup f r omt he MDB backup f i l e, use t hi s:
md_r est or e b / t mp/ backupf i l e t f ul l g dg1 - i
# To j ust r est or e t he met adat a f or t he dg1 di skgr oup ( t he di skgr oup al r eady
exi st s) .
md_r est or e b / t mp/ backupf i l e t nodg g dg1 i
# To cr eat e a di f f er ent di skgr oup name:
md_r est or e b / t mp/ backupf i l e t newdg - o " DGNAME=dg1: dg3" i
# To appl y t he over r i de opt i ons as speci f i ed i n t he dg_over . t xt f i l e and r est or e
# f r omt he backup f i l e:
md_r est or e b / t mp/ backupf i l e t newdg of / t mp/ dg_over r i de. t xt i

/ * Scenar i o Exampl e */
1. Back up a t abl espace exi si ng i n a di sk gr oup:
RMAN> BACKUP TABLESPACE user s;
2. Cr eat e a di r ect or y named t est i n t he di sk gr oup DGROUPA. Al so cr eat e an al i as
cal l ed
+DGROUPA/ t est / user s. f t hat poi nt s t o t he ASM dat af i l e t hat cont ai ns t he user s
t abl espace:
ASMCMD> mkdi r +DGROUPA/ t est
ASMCMD> mkal i as TBSSRA. 123. 123456789 +DGROUPA/ t est / user s. f
3. Back up t he met adat a f or t he di sk gr oup DGROUPA usi ng t he md_backup command:
ASMCMD> md_backup g dgr oupA
The md_backup command st or es t he backup met adat a i n t he t ext f i l e named
ambr _backup_
i nt er medi at e i n t he cur r ent di r ect or y.
4. Si mul at e a di sk f ai l ur e by dr oppi ng t he di sk gr oup DGROUPA:
SQL> ALTER DI SKGROUP dgr oup1 DI SMOUNT FORCE;
SQL> DROP DI KSGROUP dgr oup1 FORCE I NCLUDI NG CONTENTS;
Page 407 Oracle DBA Code Examples

The DI SMOUNT FORCE cl ause i n t he ALTER DI SKGROUP command di smount s t he di sk gr oup
and
f or ce dr ops i t .
5. Execut e t he md_r est or e command t o r est or e t he ASM met adat a f or t he dr opped di sk
gr oup:
ASMCMD> md_r est or e b ambr _backup_i nt er medi at e_f i l e
t f ul l g dat a
6. Usi ng t he backup of t he user s t abl espace f r omst ep 1, r est or e t he user s
t abl espace:
RMAN>RESTORE TABLESAPCE user s;
7. Exi t f r omRMAN once t he r est or e i s compl et ed.
Note that md_backup is a backup of the metadata of the ASM instance. The data is being backed up by
RMAN. After the diskgroup is created, along with all the directories, you can restore the RMAN backup to
the diskgroup.
Bad Block Recovery
If ASM cannot read a physical block from a disk, it considers that the block has IO error. In this case,
ASM will automatically read a mirrored block and write a relocated copy to produce successful copy.
However, you can manually repair blocks that have read disk I/O errors using the r emap command.
Following is the syntax of the command:
r emap <di skgr oup name> <di sk name> <bl ock r ange>
Using SYSASM Privilege and OSASM Group
This feature introduces a new SYSASM privilege that is specifically intended for performing ASM
administration tasks. Using the SYSASMprivilege instead of the SYSDBA privilege provides a clearer division
of responsibility between ASM administration and database administration.
Following are code examples illustrating how to use this privilege:
- - gr ant t he pr i vi l ege
GRANT SYSASM TO f i r as;

- - check t he gr ant ed pr i vi l ege
SELECT * FROM V$PWFI LE_USERS;

- - ASM management commands ar e avai l abl e t o Adam
CONNECT f i r as/ hi s_passwor d
ALTER DI SKGROUP dg1 DI SMOUNT;
ALTER DI SKGROUP dg2 MOUNT;
. . and so on.
Be aware that users with SYSOPER privilege have some ASM privileges. Following table shows available
and restricted ASM privilege for users with SYSOPER privilege:
Avaiable ASM Privilege Restricted ASM Privilege
STARTUP AND SHUTDOWN
ALTER DI SKGROUP MOUNT
ALTER DI SKGROUP DI SMOUNT
ALTER DI SKGROUP ONLI NE DI SK
ALTER DI SKGROUP OFFLI NE DI SK
ALTER DI SKGROUP REBALANCE
ALTER DI SKGROUP CHECK
CREATE DI SKGROUP / DI SK
DROP DI SKGROUPS / DI SKS
ALTER DI SKGROUP / DI SK RESI ZE

OSASM is a new operating system group that is used exclusively for ASM. Members of the OSASM group
can connect as SYSASMusing operating system authentication and have full access to ASM.
Page 408 Oracle DBA Code Examples

Manually Upgrading Oracle AS from 10g to 11g
Following are the steps you follow to upgrade an existing Oracle 10g ASM to 11g:
1. Install the Oracle Database 11g software to a new ORACLE_HOME directory.
2. Update the / et c/ or at ab or / var / opt / or acl e/ or at ab file with the new ASM ORACLE_HOME
location.
3. Copy the ASM initialization file from the old ORACLE_HOME to the new one.
4. Edit any directory-based parameters (such as di ag and dump) in the ASM initialization file as
required.
5. If you are upgrading a non-RAC ASM instance, you should reconfigure the Oracle CSS using the new
ORACLE_HOME. You can do this by executing the l ocal conf i g command from the new home. Once
the CSS configuration is complete, you need to change your ORACLE_HOME to the new Oracle
version 11.1 ORACLE_HOME and start the ASM instance.
cd $ORACLE_HOME/bin
# ./localconfig reset
6. If you are upgrading a ASM instance in a RAC environments, you can modify the new ASM home
within the OCR using the sr vct l utility as follows:
srvctl modify asm -n racnode1 -i +ASM1 -o /apps/oracle/product/11.1.0/asm -p
init+ASM1.ora
7. Grant the SYSASM role to the SYS
GRANT SYSASM to sys;
8. If you have obsolete initialization parameters, you can address them now. To get a listing of all the
obsolete initialization parameters, refer to the ASM alert log file.
Verifying Manually ASM Device
# To ver i f y asml i b st at us:
## Bot h shoul d be [ OK]
/ et c/ i ni t . d/ or acl easmst at us
Checki ng i f ASM i s l oaded: [ OK ]
Checki ng i f / dev/ or acl easmi s mount ed: [ OK ]


# To ver i f y user set t i ng i n asml i b:
ui d=1001( gr i d) gi d=1000( oi nst al l ) gr oups=1000( oi nst al l )

/ usr / sbi n/ or acl easmconf i gur e
ORACLEASM_ENABLED=t r ue
ORACLEASM_UI D=gr i d
ORACLEASM_GI D=oi nst al l
ORACLEASM_SCANBOOT=t r ue
ORACLEASM_SCANORDER=" "
ORACLEASM_SCANEXCLUDE=" "


# To ver i f y di sk
/ et c/ i ni t . d/ or acl easml i st di sks
DI SKCLU
l s - l / dev/ or acl easm/ di sks
. .
br w- r w- - - - 1 gr i d oi nst al l 8, 33 Sep 16 09: 41 DI SKCLU

Page 409 Oracle DBA Code Examples

# Di sk DI SKCLU i s avai l abl e and r eadabl e f r omabove out put .
dd i f =/ dev/ or acl easm/ di sks/ DI SKCLU of =/ dev/ nul l bs=1024k count =1
1+0 r ecor ds i n
1+0 r ecor ds out


Page 410 Oracle DBA Code Examples

Part 7 Oracle Real Application Cluster
Page 411 Oracle DBA Code Examples

Oracle RAC Possible Installation Configurations
For Oracle Software homes, Voting and OCR, db files:
NTFS_RAW_ASM
NTFS_RAW_RAW
NTFS_OCFS_OCFS
OCFS_OCFS_OCFS
Page 412 Oracle DBA Code Examples

Installing Oracle 10g R2 RAC on Enterprise Linux 4
Note: The metalink document RAC Starter Kit and Best Practices (Linux) [ID 811306.1] is a
good source reference for this task.
Installation Environment
Emulation software: VMWare Workstation ACE Edition 6.0.5 or VMWare Server 2.
RAC Nodes: 2 nodes with 2 GB RAM each , 2 ethernet cards.
OS: Oracle Linux Enterprise 4.5 for x86: kernel 2.6.9
Required Software
Oracle 10g R2 Clusterware for Linux x86 32-bit
Oracle Database 10g Release 2 for Linux x86 32-bit
Used Hardware
In the VMWare: create one virtual machine (rac1) with the following specs:
o 2 GB RAM
o Two ethernet cards: both can be configured as bridged or host-only in VMware.
o One local hardisk with 20 GB
o CPU Count: 2
o Create a folder in the same directory structure level as the parent folder containing the
created virtual machine. Give it a meaningful name like 'shared_disks'. Create in that
folder three disks of 10 GB and two of 512 MB. All of them are of LSI Logic type and
SCISI Persistent. Make sure they are on SCISI controller different from the SCSI
controller of the local hardisk. For example, if the SCSI controller of local hardisk is
SCISI0, make those disks on controller SCSI1.
Installation Plan
1. Preinstallation tasks:
o Hardware requirements
o Software requirements
o Environment configuration
2. Oracle Clusterware installation
3. Oracle Database 10g Software Installation
4. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software
5. Install EM Agent in cluster nodes (if required)
6. Configure Listeners
7. Perform ASM installation
Page 413 Oracle DBA Code Examples

8. Perform cluster database creation
9. Complete postinstallation tasks
10. Useful postinstallation tasks


1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Give the first ethernet card IP 192.168.4.11 and the second 192.168.0.11 and the
hostname r ac1. mydomai n. com. Define a gateway. If it does not exist, make it same as
the host IP address.
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Desktop
o X Window System
o Gnome
Page 414 Oracle DBA Code Examples

Applications
o Graphical Internet (optional)
Servers
o Do not select anything in this group.
Development
o Development Tools
System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
Miscellaneous
o Do not select anything in this group.
Complete the installation
Install further packages:
# t o know di st r i but i on and ver si on of Li nux
cat / et c/ i ssue
# t o know ker nel ver si on ( and i t s er r at a l evel )
uname - r

# f r omCD 3
r pm- Uvh l i bai o*
r pm- Uvh openmot i f 21- 2. 1. 30- 11. RHEL4. 6. i 386. r pm
r pm- Uvh openmot i f - 2. 2. 3- 10. 1. el 4. i 386. r pm

# t hose packages downl oaded f r omht t p: / / r pm. pbone. net
r pm- e compat - l i bst dc++- 296- 2. 96- 132. 7. 2
r pm- Uvh compat - l i bst dc++- 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - l i bst dc++- devel - 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - gcc- 7. 3- 2. 96. 128. i 386. r pm
r pm- Uvh compat - gcc- c++- 7. 3- 2. 96. 128. i 386. r pm

# conf i r mt he r equi r ed packages ar e i nst al l ed:
r pm- qa| gr ep gcc-
r pm- qa| gr ep gl i bc-
r pm- qa| gr ep compat - db-
r pm- qa| gr ep compat - gcc-
r pm- qa| gr ep compat - gcc- c++-
r pm- qa| gr ep compat - l i bst dc++-
r pm- qa| gr ep compat - l i bst dc++- devel -
r pm- qa| gr ep cont r ol - cent er - 2. 8. 0
r pm- qa| gr ep openmot i f 21-
r pm- qa| gr ep set ar ch-

# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Page 415 Oracle DBA Code Examples


# I nst al l ASMLi b 2. 0 packages
# i nst al l t he l i br ar y f or your ker nel and CPU t ype
# or acl easm- *- ver si on. cpu_t ype. r pm
# check i nst al l ed packages
r pm- qa| gr ep asm
# i nst al l t he packages f r omCD3
r pm- Uhv or acl easm- suppor t - 2. 0. 3- 2. i 386. r pm
r pm- Uhv or acl easm- 2. 6. 9- 55. 0. 0. 0. 2. EL- 2. 0. 3- 2. i 686. r pm
r pm- Uhv or acl easm- 2. 6. 9- 55. 0. 0. 0. 2. ELsmp- 2. 0. 3- 2. i 686. r pm

# downl oad t he package User space Li br ar y
# f r om
ht t p: / / ot n. or acl e. com/ sof t war e/ t ech/ l i nux/ asml i b/ f i l es/ RPMS/ r hel 4/ x86/ 2. 0. 4/ or
acl easml i b- 2. 0. 4- 1. el 4. i 386. r pm
r pm- Uvh or acl easml i b- 2. 0. 4- 1. el 4. i 386. r pm
Check the hardware requirements
# Har dwar e Requi r ement s ( i n cl ust er nodes)
# At l east 1 GB of physi cal memor y
gr ep MemTot al / pr oc/ memi nf o
# swap space: t wi ce t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o
# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 400 MB di sk space i n / t mp
df - k / t mp
# 4 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
# df - h / dev/ shm/
Create the required network configuration (rac2 will be created later):
# Net wor k names Resol ut i on
# conf i gur e / et c/ host s i f no domai n ser ver i s used ( bot h nodes)
vi / et c/ host s
127. 0. 0. 1 l ocal host . l ocal domai n l ocal host
#Publ i c
192. 168. 4. 11 r ac1. mydomai n. com r ac1
192. 168. 4. 12 r ac2. mydomai n. com r ac2
#VI P
192. 168. 4. 13 r ac1- vi p. mydomai n. com r ac1- vi p
192. 168. 4. 14 r ac2- vi p. mydomai n. com r ac2- vi p
#I nt er - connect
192. 168. 0. 11 r ac1- pr i v. mydomai n. com r ac1- pr i v
192. 168. 0. 12 r ac2- pr i v. mydomai n. com r ac2- pr i v
Page 416 Oracle DBA Code Examples

Note: To prevent network hangs with failovers from public to virtual IP addresses with
RAC databases using NAS devices or NFS mounts, enter the following command as root to
enable the Name Service Cache Daemon: / sbi n/ ser vi ce nscd st ar t
Create and configure the required OS users and groups
Note: userid and groupid must be the same in all nodes. You can check them by i d
or acl e command.
# al l gr oup and user i ds on al l t he nodes must have i dent i cal i d
# i nvent or y and OSDBA gr oups ( i f needed, use - g <number > t o speci f y t he i d)
# i nvent or y gr oup
gr oupadd - g 501 oi nst al l
gr oupadd - g 502 dba
# or acl e sof t war e owner user ( t ake not e of user i d)
/ usr / sbi n/ user add - u 200 - g oi nst al l - G dba or acl e
passwd or acl e
# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody

# The or acl e User Envi r onment
# i n / home/ or acl e/ . bash_pr of i l e
# expor t DI SPLAY i f r equi r ed
expor t ORACLE_BASE=/ u01/ app/ or acl e
i f [ $USER = " or acl e" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i
expor t EDI TOR=vi
expor t ORACLE_HOME=$ORACLE_BASE/ pr oduct / 10. 2. 0/ db_1
expor t ORA_CRS_HOME=/ u01/ cr s
expor t ORACLE_PATH=$ORACLE_BASE/ common/ or acl e/ sql : . : $ORACLE_HOME/ r dbms/ admi n
expor t ORACLE_SI D=r ac1
expor t NLS_LANG=AMERI CAN_AMERI CA. WE8I SO8859P1
expor t NLS_DATE_FORMAT=" mm/ dd/ yyyy hh24: mi : ss"
expor t PATH=. : ${PATH}: $HOME/ bi n: $ORACLE_HOME/ bi n: $ORA_CRS_HOME/ bi n
expor t PATH=${PATH}: / usr / bi n: / bi n: / usr / bi n/ X11: / usr / l ocal / bi n
expor t PATH=${PATH}: $ORACLE_BASE/ common/ or acl e/ bi n
expor t ORACLE_TERM=xt er m
expor t TNS_ADMI N=$ORACLE_HOME/ net wor k/ admi n
expor t ORA_NLS10=$ORACLE_HOME/ nl s/ dat a
expor t TNS_ADMI N=$ORACLE_HOME/ net wor k/ admi n
expor t ORA_NLS10=$ORACLE_HOME/ nl s/ dat a
expor t LD_LI BRARY_PATH=$ORACLE_HOME/ l i b
expor t LD_LI BRARY_PATH=${LD_LI BRARY_PATH}: $ORACLE_HOME/ or acm/ l i b
expor t LD_LI BRARY_PATH=${LD_LI BRARY_PATH}: / l i b: / usr / l i b: / usr / l ocal / l i b
expor t CLASSPATH=$ORACLE_HOME/ J RE
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ j l i b
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ r dbms/ j l i b
expor t CLASSPATH=${CLASSPATH}: $ORACLE_HOME/ net wor k/ j l i b
expor t THREADS_FLAG=nat i ve
# shoul d NOT be on a shar ed di sk
expor t TEMP=/ t mp
expor t TMPDI R=/ t mp
Page 417 Oracle DBA Code Examples

Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start, then
you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Conf i gur i ng ker nel par amet er s and shel l l i mi t s

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf
or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536
or acl e sof t meml ock 3145728
or acl e har d meml ock 3145728

vi / et c/ pam. d/ l ogi n
sessi on r equi r ed / l i b/ secur i t y/ pam_l i mi t s. so

# t hey can be t uned f or a pr oduct i on db
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf
ker nel . sem= 250 32000 100 128
# I t shoul d be equal t o or l ar ger t han t he l ar gest SGA ( max 4 GB)
ker nel . shmmax = 536870912
net . i pv4. i p_l ocal _por t _r ange = 1024 65000
net . cor e. r mem_def aul t = 4194304
net . cor e. r mem_max = 4194304
net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 262144
# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p
Configure hangcheck-timer kernel module:
# check hangcheck- t i mer Modul e Conf i gur at i on
# wi t h t hi s modul e, i f t he ker nel hangs, t he machi ne wi l l r eboot
# ver i f y t he modul e i s l oaded
/ sbi n/ l smod | gr ep - i hang

# i f not l oaded, l oad i t
vi / et c/ modpr obe. conf
opt i ons hangcheck- t i mer hangcheck_t i ck=30 hangcheck_mar gi n=180
# execut e and add i n t he f i l e
vi / et c/ r c. l ocal
/ sbi n/ modpr obe hangcheck- t i mer
Partition the disks and prepare the raw disks
# Par t i t i on t he devi ces
# f or t he di sks / dev/ sdb . . / dev/ sdf
f di sk / dev/ sdb
# answer s: " n" , " p" , " 1" , " Ret ur n" , " Ret ur n" , " p" and " w"
Not e: i f t he f ol l owi ng message appear s af t er t he " w" command:
WARNI NG: Re- r eadi ng t he par t i t i on t abl e f ai l ed wi t h er r or 16: Devi ce or
r esour ce busy.
t hen, you can avoi d r est ar t i ng t he machi ne by t he f ol l owi ng command:
par t pr obe
Page 418 Oracle DBA Code Examples


# t o make sur e par t i ons ar e cr eat ed
l s - l X / dev/ sd*
br w- r - - - - - 1 r oot di sk 8, 0 Dec 1 20: 35 / dev/ sda
br w- r - - - - - 1 r oot di sk 8, 1 Dec 1 20: 36 / dev/ sda1
br w- r - - - - - 1 r oot di sk 8, 2 Dec 1 20: 35 / dev/ sda2
br w- r - - - - - 1 r oot di sk 8, 16 Dec 1 21: 55 / dev/ sdb
br w- r - - - - - 1 r oot di sk 8, 17 Dec 1 21: 55 / dev/ sdb1
br w- r - - - - - 1 r oot di sk 8, 32 Dec 1 21: 57 / dev/ sdc
br w- r - - - - - 1 r oot di sk 8, 33 Dec 1 21: 57 / dev/ sdc1
br w- r - - - - - 1 r oot di sk 8, 48 Dec 1 21: 57 / dev/ sdd
br w- r - - - - - 1 r oot di sk 8, 49 Dec 1 21: 57 / dev/ sdd1
br w- r - - - - - 1 r oot di sk 8, 64 Dec 1 21: 58 / dev/ sde
br w- r - - - - - 1 r oot di sk 8, 65 Dec 1 21: 58 / dev/ sde1
br w- r - - - - - 1 r oot di sk 8, 80 Dec 1 21: 58 / dev/ sdf
br w- r - - - - - 1 r oot di sk 8, 81 Dec 1 21: 58 / dev/ sdf 1

# bi ndi ng sdi sks t o r aw devi ces
r aw / dev/ r aw/ r aw1 / dev/ sdb1
r aw / dev/ r aw/ r aw2 / dev/ sdc1
# l i st t he r aw devi ces
r aw - qa
# add t o t he f i l e
vi / et c/ sysconf i g/ r awdevi ces
/ dev/ r aw/ r aw1 / dev/ sdb1
/ dev/ r aw/ r aw2 / dev/ sdc1

# Adj ust t he r aw devi ces per mi ssi on set t i ngs:
# Run t he f ol l owi ng commands AND add t hemt he / et c/ r c. l ocal f i l e:
# wi l l be used by OCR
chown r oot : oi nst al l / dev/ r aw/ r aw1
chmod 660 / dev/ r aw/ r aw1
# wi l l be used by vot i ng di sk
chown or acl e: oi nst al l / dev/ r aw/ r aw2
chmod 644 / dev/ r aw/ r aw2
# wi l l be used by ASM, i f i t i s usi ng r aw devi ce ( NOT I N THI S CONFI GURATI ON)
# chown or acl e: oi nst al l / dev/ r aw/ r aw3
# chmod 660 / dev/ r aw/ r aw3

# st ar t t he ser vi ce
ser vi ce r awdevi ces r est ar t
Create the required directories for the Oracle clusterware and database software
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

# i n t he exampl e above, / u01 shoul d be owned by t he r oot user
# and wr i t abl e by gr oup oi nst al l
# di r ect or i es must be same i n al l nodes:
mkdi r - p / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
mkdi r / u01/ st age10g
# cl ust er war e must NOT be subdi r ect or y of t he ORACLE_BASE
mkdi r / u01/ cr s
chown - R or acl e: oi nst al l / u01/ app/ or acl e
Page 419 Oracle DBA Code Examples

chmod - R 775 / u01/ app/ or acl e
chown or acl e: oi nst al l / u01/ st age10g
chown - R or acl e: oi nst al l / u01/ cr s
chmod - R 775 / u01/ cr s
Disable screensavers on host & guest machines.
o In Oracle Linux: Applications-> Preferences-> Screen Saver-> Mode: Disable Screen
Saver
o Do the same after logging off and logging on again as oracle user.
Shutdown rac1
Edit the VMware file (with vmx extensions) and add the following entry to allow sharing
the disks (make sure the scsi controller number is the one you used):
di sk. l ocki ng = " FALSE"
di skLi b. dat aCacheMaxSi ze = " 0"
di skLi b. dat aCacheMaxReadAheadSi ze = " 0"
di skLi b. dat aCacheMi nReadAheadSi ze = " 0"
di skLi b. dat aCachePageSi ze = " 4096"

scsi 1. shar edBus = " vi r t ual "
scsi 1: 0. devi ceType = " di sk"
scsi 1: 1. devi ceType = " di sk"
scsi 1: 2. devi ceType = " di sk"
scsi 1: 3. devi ceType = " di sk"
scsi 1: 4. devi ceType = " di sk"
scsi 1: 5. devi ceType = " di sk"
Copy the folder containing rac1 into a new folder in the same directory structure level.
Let's name it "rac2". This will be the second node in the cluster.
Edit the VMware file of rac1 and edit the following: displayName = "rac2"
Open rac2 then probe its network cards, change it's IP addresses: IP 192.168.4.12 and
192.168.0.12. It's hostname to rac2.mydomain.com. You can use system-config-network-
gui. Activate the network and reboot the vm.
In rac2, perform:
# change t he var i abl e i n t he f i l e
vi / home/ or acl e/ . bash_pr of i l e
expor t ORACLE_SI D=r ac2
Start rac1
Configure ASM drivers:
# as r oot ( on ALL NODES )
ser vi ce or acl easmconf i gur e

Def aul t user t o own t he dr i ver i nt er f ace [ ] : oracle
Def aul t gr oup t o own t he dr i ver i nt er f ace [ ] : dba
St ar t Or acl e ASM l i br ar y dr i ver on boot ( y/ n) [ n] : y
Fi x per mi ssi ons of Or acl e ASM di sks on boot ( y/ n) [ y] : y
Wr i t i ng Or acl e ASM l i br ar y dr i ver conf i gur at i on: [ OK ]
Cr eat i ng / dev/ or acl easmmount poi nt : [ OK ]
Loadi ng modul e " or acl easm" : [ OK ]
Mount i ng ASMl i b dr i ver f i l esyst em: [ OK ]
Scanni ng syst emf or ASM di sks: [ OK ]

# As t he r oot user on node node1 ( ONLY ONE NODE)
ser vi ce or acl easmcr eat edi sk DI SK1 / dev/ sdd1
Page 420 Oracle DBA Code Examples

ser vi ce or acl easmcr eat edi sk DI SK2 / dev/ sde1
ser vi ce or acl easmcr eat edi sk DI SK3 / dev/ sdf 1
# i f any of t he commands above f ai l s, you can del et e t he di sk
ser vi ce or acl easmdel et edi sk DI SK1
# i n ALL NODES
ser vi ce or acl easmscandi sks
ser vi ce or acl easml i st di sks
Configure SSH in all the nodes:
Note: scp and ssh must be located in the path /usr/local/bin. If not, then create a symbolic
link in /usr/local/bin to the location where scp and ssh are found.
# Conf i gur i ng SSH f or Remot e I nst al l at i on
# make sur e t he ssh i s r unni ng
# t he f ol l owi ng command shoudl r et ur n ssh pr ocess i d
pgr ep sshd

vi / et c/ host s. equi v
# add node names t o / et c/ host s. equi v ( al l nodes)
r ac1
r ac2
# as oracle i n node1
# whenever pr ompt ed f or a passphr ase l eave i t empt y and pr ess r et ur n
mkdi r ~/ . ssh
chmod 700 ~/ . ssh
/ usr / bi n/ ssh- keygen - t r sa
# as or acl e i n node2
mkdi r ~/ . ssh
chmod 700 ~/ . ssh
/ usr / bi n/ ssh- keygen - t r sa
# as or acl e on node1
cat ~/ . ssh/ i d_r sa. pub >> ~/ . ssh/ aut hor i zed_keys
ssh r ac2 cat ~/ . ssh/ i d_r sa. pub >> ~/ . ssh/ aut hor i zed_keys
scp ~/ . ssh/ aut hor i zed_keys r ac2: / home/ or acl e/ . ssh/

# Per f or mt he f ol l owi ng as t he or acl e user on node1 and t hen node2
# copy past e t he f ol l owi ng command i n bot h nodes t wi ce:
ssh r ac1 dat e; ssh r ac2 dat e; ssh r ac1. mydomai n. comdat e; ssh r ac2. mydomai n. com
dat e; ssh r ac1- pr i v dat e; ssh r ac2- pr i v dat e; ssh r ac1- pr i v. mydomai n. comdat e; ssh
r ac2- pr i v. mydomai n. comdat e; ssh l ocal host . l ocal domai n dat e; ssh l ocal host dat e
# Not e: t he keys ar e sessi on dependent . i t ' s gone f r ommemor y on l og of f
# Execut e ( t o l oad t he keys i n t he memor y) :
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add
2. Oracle Clusterware installation
# make sur e syst emt i me of r ac2 shoul d be behi nd t he syst emt i me of r ac1
dat e; ssh r ac2 dat e

# I dent i f y t he shar ed di sks t o use
# / dev/ sdb & / dev/ sdc wi l l be used f or OCR & Vot i ng by t he Cl ust er sof t war e
/ sbi n/ f di sk l

# unzi p t he Or acl e 10g R2 Cl ust er war e f or Li nux i n t he st age f ol der ( r ac1)

# I f you pl an t o use Or acl e Cl ust er war e on x86 ( 64- bi t ) ( but not on
# Li nux I t ani um64- bi t ) , t hen you must r un t he r oot pr e. sh on al l nodes
Page 421 Oracle DBA Code Examples

su -
cd / u01/ st age10g/ cl ust er war e/ r oot pr e
. / r oot pr e. sh

# i nst al l cl uvf y ( i n al l nodes)
# i n node1
su -
cd / u01/ st age10g/ cl ust er war e/ r pm
r pm- q cvuqdi sk- 1. 0. 1
expor t CVUQDI SK_GRP=dba
r pm- i vh cvuqdi sk- 1. 0. 1- 1. r pm
# i n node2
su -
expor t CVUQDI SK_GRP=dba
r pm- i vh cvuqdi sk- 1. 0. 1- 1. r pm

# Ver i f y Cl ust er Set up wi t h cl uvf y
# as oracle
# i f t he user equi val ency i s not l oaded
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add
# t hen pr oceed:
cd / u01/ st age10g/ cl ust er war e/ cl uvf y
expor t CV_NODE_ALL=r ac1, r ac2
. / r uncl uvf y. sh st age - pr e cr si nst - n r ac1, r ac2 - ver bose
# I f onl y t he VI P was t he pr obl em, t hen you' r e goi ng i n t he r i ght way!


# l unch OUI f r omt he cl ust er war e ( as oracle f r omnode1)
# i f l ogged i n i n Genome usi ng anot her user , l og out and l og i n as or acl e
# t o r el oad t he user equi val ency, i f l ogged of f : ( as or acl e)
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add
# i f not t ur ned of f , t ur n of f t he scr eensaver I N ALL NODES
# t hen pr ocess:
cd / u01/ st age10g/ cl ust er war e
. / r unI nst al l er


>I nvent or y Di r ect or y ( di spl ayed onl y i n f i r st t i me)
/ u01/ app/ or acl e/ or aI nvent or y
oi nst al l

>Home Det ai l s
/ u01/ cr s

>Pr oduct - Speci f i c Pr er equi si t e Checks
They al l shoul d succeed

>Speci f y Cl ust er Conf i gur at i on
Sel ect ' Add' and add t he det ai l s f or node r ac2. Ent er al l det ai l s. ' OK' t o
cont i nue.
r ac2. mydomai n. com
r ac2- pr i v. mydomai n. com
r ac2- vi p. mydomai n. com
Cl i ck ' Next '

Page 422 Oracle DBA Code Examples

>Speci f y Net wor k I nt er f ace Usage
Change t he et h0 I nt er f ace Type t o Publ i c.
' Ok' t o cont i nue

>Speci f y Or acl e Cl ust er Regi st r y ( OCR) Locat i on
Sel ect Ext er nal Redundancy and
speci f y t he f i r st r aw devi ce / dev/ r aw/ r aw1 as t he OCR l ocat i on
' Next ' t o cont i nue.

>Speci f y Vot i ng Di sk Locat i on
Sel ect Ext er nal Redundancy and
speci f y t he f i r st r aw devi ce / dev/ r aw/ r aw2 as t he vot i ng di sk l ocat i on
' Next ' t o cont i nue.

>Summar y
Revi ew t he summar y and sel ect ' I nst al l ' t o st ar t t he i nst al l at i on

>Conf i gur at i on Scr i pt s
as t he r oot user on each node, r un t he scr i pt s. Do not r un t he scr i pt s
si mul t aneousl y on bot h nodes.
i f t her e i s an er r or i n scr i pt s execut i on, i t ' s r epor t ed i n / u01/
/ cr s/ l og/ <host name>

output of running the script in node1:
Checki ng t o see i f Or acl e CRS st ack i s al r eady conf i gur ed
/ et c/ or acl e does not exi st . Cr eat i ng i t now.

Set t i ng t he per mi ssi ons on OCR backup di r ect or y
Set t i ng up NS di r ect or i es
Or acl e Cl ust er Regi st r y conf i gur at i on upgr aded successf ul l y
assi gni ng def aul t host name r ac1 f or node 1.
assi gni ng def aul t host name r ac2 f or node 2.
Successf ul l y accumul at ed necessar y OCR keys.
Usi ng por t s: CSS=49895 CRS=49896 EVMC=49898 and EVMR=49897.
node <nodenumber >: <nodename> <pr i vat e i nt er connect name> <host name>
node 1: r ac1 r ac1- pr i v r ac1
node 2: r ac2 r ac2- pr i v r ac2
Cr eat i ng OCR keys f or user ' r oot ' , pr i vgr p ' r oot ' . .
Oper at i on successf ul .
Now f or mat t i ng vot i ng devi ce: / dev/ r aw/ r aw2
For mat of 1 vot i ng devi ces compl et e.
St ar t up wi l l be queued t o i ni t wi t hi n 90 seconds.
Addi ng daemons t o i ni t t ab
Expect i ng t he CRS daemons t o be up wi t hi n 600 seconds.
CSS i s act i ve on t hese nodes.
r ac1
CSS i s i nact i ve on t hese nodes.
r ac2
Local node checki ng compl et e.
Run r oot . sh on r emai ni ng nodes t o st ar t CRS daemons.

output of running the script in node2:
Checki ng t o see i f Or acl e CRS st ack i s al r eady conf i gur ed
/ et c/ or acl e does not exi st . Cr eat i ng i t now.

Set t i ng t he per mi ssi ons on OCR backup di r ect or y
Set t i ng up NS di r ect or i es
Page 423 Oracle DBA Code Examples

Or acl e Cl ust er Regi st r y conf i gur at i on upgr aded successf ul l y
cl scf g: EXI STI NG conf i gur at i on ver si on 3 det ect ed.
cl scf g: ver si on 3 i s 10G Rel ease 2.
assi gni ng def aul t host name r ac1 f or node 1.
assi gni ng def aul t host name r ac2 f or node 2.
Successf ul l y accumul at ed necessar y OCR keys.
Usi ng por t s: CSS=49895 CRS=49896 EVMC=49898 and EVMR=49897.
node <nodenumber >: <nodename> <pr i vat e i nt er connect name> <host name>
node 1: r ac1 r ac1- pr i v r ac1
node 2: r ac2 r ac2- pr i v r ac2
cl scf g: Ar gument s check out successf ul l y.

NO KEYS WERE WRI TTEN. Suppl y - f or ce par amet er t o over r i de.
- f or ce i s dest r uct i ve and wi l l dest r oy any pr evi ous cl ust er
conf i gur at i on.
Or acl e Cl ust er Regi st r y f or cl ust er has al r eady been i ni t i al i zed
St ar t up wi l l be queued t o i ni t wi t hi n 90 seconds.
Addi ng daemons t o i ni t t ab
Expect i ng t he CRS daemons t o be up wi t hi n 600 seconds.
CSS i s act i ve on t hese nodes.
r ac1
r ac2
CSS i s act i ve on al l nodes.
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Wai t i ng f or t he Or acl e CRSD and EVMD t o st ar t
Or acl e CRS st ack i nst al l ed and r unni ng under i ni t ( 1M)
Runni ng vi pca( si l ent ) f or conf i gur i ng nodeapps
The gi ven i nt er f ace( s) , " et h0" i s not publ i c. Publ i c i nt er f aces shoul d be used
t o conf i gur e vi r t ual I Ps.


# you MUST run vipca in the LAST NODE ( NODE2) bef or e cl i cki ng OK i n OUI
# f r om$ORA_CRS_HOME/ bi n
cd / u01/ cr s/ bi n
./vipca
# i n vi pca, cl i ck on vi p addr ess t o aut o f i l l
r ac1 r ac1- vi p. mydomai n. com 192. 168. 4. 13
r ac2 r ac2- vi p. mydomai n. com 192. 168. 4. 14

When t he conf i gur at i on i s compl et e, t he f i nal r esul t r epor t wi l l be:
Conf i gur at i on Resul t sThe VI P Conf i gur at i on Assi st ant has successf ul l y cr eat ed
r esour ce apl i cat i ons f or each cl ust er node
Cl i ck ' Exi t '

Cl i ck ' OK' i n t he OUI .
Al l t he checks shoul d succeed.
Cl i ck ' Exi t '

# To ver i f y t he i nst al l at i on:
- - 1
cd / u01/ st age10g/ cl ust er war e/ cl uvf y
. / r uncl uvf y. sh st age - post cr si nst - n r ac1, r ac2 - ver bose
Page 424 Oracle DBA Code Examples

- - 2
pi ng r ac1- vi p
pi ng r ac2- vi p
- - 3
/ u01/ cr s/ bi n/ cr sct l check cr s

# To Avoid Node Eviction
# I n ALL NODES as r oot : ( I MPORTANT)
vi / u01/ cr s/ i nst al l / r oot conf i g
At l i ne 356, change
CLSCFG_MI SCNT=" - mi sscount 60"
t o
CLSCFG_MI SCNT=" - mi sscount 300"
# and t hen by t he command
cr sct l set css mi sscount 300

# check st at us of cr s daemon pr ocesses ( ALL NODES)
. / cr s_st at - t
Name Type Tar get St at e Host
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
or a. r ac1. gsd appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac1. ons appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac1. vi p appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac2. gsd appl i cat i on ONLI NE ONLI NE r ac2
or a. r ac2. ons appl i cat i on ONLI NE ONLI NE r ac2
or a. r ac2. vi p appl i cat i on ONLI NE ONLI NE r ac2
# i f St at e of any of t hemi s UNKNOWN, t r y r est ar t i ng t he deamons
. / cr sct l st op cr s
# t hen st ar t agai n
. / cr sct l st ar t cr s
# t o check t hei r st at us ( keep checki ng t i l l al l damons ar e up)
. / cr sct l check cr s
# when t hey ar e al l up, t he out put shoul d be:
CSS appear s heal t hy
CRS appear s heal t hy
EVM appear s heal t hy
3. Oracle Database 10g Software Installation
# make sur e al l cl ust er war e pr ocesses ar e r unni ng
/ u01/ cr s/ bi n/ cr s_st at - t
# you can r est ar t t hem
/ u01/ cr s/ bi n/ cr sct l st op cr s
/ u01/ cr s/ bi n/ cr sct l st ar t cr s

# I f not l oaded, t o l oad t he keys i n t he memor y:
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add

- - ext r act DB sof t war e i n / u01/ st age10g/ dat abase i n node1
- - as or acl e
mkdi r / u01/ st age10g/ dat abase

- - st ar t OUI
cd / u01/ st age10g/ dat abase
. / r unI nst al l er

Wel come ' Next ' t o ski p t he Wel come scr een
Page 425 Oracle DBA Code Examples


Sel ect I nst al l at i on Type
' Next ' t o cont i nue.

I nst al l Locat i on
Keep t he def aul t Or acl e Base l ocat i on / u01/ app/ or acl e and
def aul t Or acl e Home l ocat i on / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
' Next ' t o cont i nue.

Speci f y Har dwar e Cl ust er I nst al l at i on Mode
Keep t he def aul t ' Cl ust er I nst al l at i on' sel ect i on
and sel ect bot h nodes.
' Next ' t o cont i nue.

Pr oduct - Speci f i c Pr er equi si t e Checks
The OUI wi l l now ver i f y t hat t he envi r onment meet s al l t he r equi r ement s. Al l
pr e- r equi si t e st eps shoul d compl et e successf ul l y.
Sel ect ' Next ' t o cont i nue.

Sel ect Conf i gur at i on Opt i on
Sel ect ' I nst al l Sof t war e Onl y' .
' Next ' t o cont i nue.

Pr i vi l eged Oper at i ng Syst emGr oups
Keep t he def aul t opt i ons dba, oi nst al l .
' Next ' t o cont i nue

Summar y
Revi ew t he summar y and sel ect ' I nst al l ' t o st ar t t he i nst al l at i on.

Conf i gur at i on Scr i pt
Once t he i nst al l at i on i s compl et e you wi l l be pr ompt ed t o r un a scr i pt as t he
r oot user . Open a
t er mi nal wi ndow and execut e t he scr i pt as t he r oot user on each node.
Sel ect ' Ok' t o cont i nue af t er t he scr i pt has been r un successf ul l y on bot h
nodes.

End of I nst al l at i on
Once t he i nst al l at i on i s compl et e sel ect ' Exi t ' t o compl et e t he i nst al l at i on
and exi t t he OUI .
4. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software
Note: This is the patchset applied for this environment. Generally speaking, if there is a newer
version, use it instead of this version.
Note: This patch includes the Oracle Clusterware Process Monitor Daemon (oprocd) which
when it detects a system hang, it restarts the hung node. This may restart a node under
heavy workload. Check Oracle Clusteware Installation documenation for more information.
# ext r act 10g Rel ease 2 ( 10. 2. 0. 4) Pat ch Set 3 f or Li nux x86 t o
/ u01/ st age10g/ pat ch10. 2. 0. 4/ Di sk1
mkdi r / u01/ st age10g/ pat ch10. 2. 0. 4

# I f not l oaded, t o l oad t he keys i n t he memor y:
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add

# you appl y t he pat ch on ( 1) cl ust er war e t hen on ( 2) dat abase sof t war e
Page 426 Oracle DBA Code Examples


# ( 1) Appl y t he pat ch on cl ust er war e
# as oracle i n r ac1
cd / u01/ st age10g/ Pat ch10. 2. 0. 4
. / r unI nst al l er
Sel ect CRS Home t hen - >Next
Cl ust er I nf o di spl ayed - > Next
Checks - > Next
- >I nst al l
Af t er I nst al l at i on i s compl et e i t wi l l ask t o appl y a scr i pt on t he nodes one-
by- one.
Fol l owi ng i s a sampl e of t he message t hat appear s:
To compl et e t he i nst al l at i on of t hi s pat chset , you must per f or mt he f ol l owi ng
t asks on each node:
1. Log i n as t he r oot user .
2. As t he r oot user , per f or mt he f ol l owi ng t asks:
a. Shut down t he CRS daemons by i ssui ng t he f ol l owi ng command:
/ u01/ cr s/ bi n/ cr sct l st op cr s
b. Run t he shel l scr i pt l ocat ed at :
/ u01/ cr s/ i nst al l / r oot 102. sh
Thi s scr i pt wi l l aut omat i cal l y st ar t t he CRS daemons on t he pat ched node
upon compl et i on.
3. Af t er compl et i ng t hi s pr ocedur e, pr oceed t o t he next node and r epeat .

# f ol l owi ng i s t he i mpl ement at i on of t he above
su -
cd / u01/ cr s/ bi n
. / cr sct l st op cr s
cd / u01/ cr s/ i nst al l
. / r oot 102. sh
cd / u01/ cr s/ bi n
. / cr sct l quer y cr s sof t war ever si on
# REPEAT I N NODE2
# t hen check st at us of deamons
. / cr s_st at - t

# ( 2) Appl y t he pat ch on DB sof t war e
# as or acl e i n node1
cd / u01/ st age10g/ pat ch10. 2. 0. 4/ Di sk1
. / r unI nst al l er
Sel ect pat h of ORACLE_HOME - >Next
Af t er I nst al l at i on i s compl et e i t wi l l ask t o appl y a scr i pt on bot h t he nodes
one- by- one.
5. Install EM Agent in cluster nodes (if required)

6. Configure Listeners
# Run net ca ( not net manager whi ch i s not cl ust er awar e) f r omany node.
# as or acl e
cd $ORACLE_HOME/ bi n
. / net ca &
Sel ect Cl ust er conf i gur at i on and sel ect bot h nodes.
Conf i gur e Li st ener
Then Conf i gur e Nami ng Met hods: Local and Easy Connect

Page 427 Oracle DBA Code Examples

Af t er i nst al l i ng l i st ener check wi t h bel ow commands whet her l i st ener wor ki ng
pr oper l y.
# as r oot
/ u01/ cr s/ bi n/ cr s_st at - t
7. Perform ASM installation
# as oracle ( i n node1)
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
dbca &

Wel come
Keep t he def aul t sel ect i on Or acl e RAC dat abase. ' Next ' t o cont i nue.

Oper at i ons Sel ect
Conf i gur e ASM. ' Next ' t o cont i nue.

Node Sel ect i on
Sel ect ALL t he nodes and ' Next ' t o cont i nue.

Cr eat e ASM I nst ance
Sel ect a SYS passwor d f or t he ASM i nst ance.
Sel ect I FI LE par amet er f i l e t o cr eat e. ' Next ' t o cont i nue.

Sel ect OK t o conf i r mcr eat i on of t he ASM i nst ances.

ASM Di sk Gr oups
Sel ect Cr eat e New t o cr eat e new ASM di sk gr oups.

Ent er dg1 as t he f i r st di sk gr oup name.
Keep t he def aul t r edundancy set t i ngs ( Nor mal ) and sel ect t he 2 dat a di sks
DI SK1 and DI SK2.
' Ok' t o cont i nue
Sel ect Cr eat e New agai n t o add anot her di sk gr oup.
Ent er dg2 as t he di sk gr oup name.
Thi s t i me sel ect Ext er nal f or r edundancy and sel ect t he r emai ni ng di sk DI SK3.
Thi s gr oup wi l l be used as t he r ecover y ar ae
' OK' t o cont i nue.
Al l t he di sk gr oups ar e now cr eat ed. Fi ni sh t o compl et e.

# An ASM i nst ance wi l l be cr eat ed i n ever y node named as ASMn
expor t ORACLE_SI D=ASM1
sql pl us / nol og
SQL>conn / as sysdba
sel ect name f r omv$asm_di skgr oup ;
. . .
# af t er checki ng, r et ur n ORACLE_SI D t o i t s or i gi nal val ue
expor t ORACLE_SI D=r ac1
8. Perform cluster database creation
# I f not l oaded, t o l oad t he keys i n t he memor y:
exec / usr / bi n/ ssh- agent $SHELL
/ usr / bi n/ ssh- add

# as or acl e ( i n node1)
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ bi n
dbca &
Page 428 Oracle DBA Code Examples


Cr eat e Or acl e RAC Dat abase
' Next ' t o cont i nue

Oper at i ons
Sel ect Cr eat e a Dat abase.
' Next ' t o cont i nue.

Node
Sel ect al l t he nodes
' Next ' t o cont i nue.

Dat abase Templ at es
Sel ect t he r equi r ed t empl at e
' Next ' t o cont i nue.

Dat abase I dent i f i cat i on
Ent er r ac as t he gl obal dat abase name.
' Next ' t o cont i nue.

Management Opt i ons
Keep t he def aul t set t i ngs Conf i gur e Ent er pr i se Manager and Conf i gur e Dat abase
Cont r ol f or l ocal management sel ect ed,
but Enabl e Al er t Not i f i cat i ons and Enabl e Dai l y Di sk Backup t o Recover y Ar ea
desel ect ed.
' Next ' t o cont i nue.

Dat abase Cr edent i al s
Sel ect Use t he same Admi ni st r at i ve Passwor d f or Al l Account s and ent er a
passwor d.
' Next ' t o cont i nue.

St or age Opt i ons
Sel ect ASM f or st or age.
' Next ' t o cont i nue.


ASM Di sk Gr oups
Sel ect bot h di sk gr oups dg1 and dg2.
' Next ' t o cont i nue.

Dat abase Fi l e Locat i ons
Keep t he def aul t Use Or acl e- Managed Fi l es.
Make sur e +DG1 i s ent er ed as t he Dat abase Ar ea.
' Next ' t o cont i nue

Recover y Conf i gur at i on:
Sel ect Speci f y Fl ash Recover y Ar ea and ent er +DG2 as t he Fl ash Recover y Ar ea.
Set i t s si ze.
Sel ect Enabl e ar chi vi ng and cl i ck on t he Edi t Ar chi ve Mode Par amet er s but t on
and make sur e t he Fl ash Recover y ar ea i s poi nt i ng t o +DG2.
' OK' and t hen
' Next ' t o cont i nue.

Dat abase Cont ent
Sel ect Sampl e Schemas i f you want t o i nst al l t hem.
Cl i ck ' Next '

Page 429 Oracle DBA Code Examples

Dat abase Ser vi ces:
Cl i ck Add but t on and ent er Ser vi ce Name such as: hr ser v t hen cl i ck ' OK'
Make sur e i t ' s set t o ' Pr ef er r ed' i n bot h nodes and sel ect Basi c f or TAF.
Cl i ck ' Next '

I ni t i al i zat i on Par amet er s:
Memor y Si ze t o 70%. You can l eave al l ot her set t i ngs as i s.
' Next ' t o cont i nue

Cr eat i on Opt i ons
Sel ect Gener at e dat abase cr eat i on scr i pt s i f you want t o r evi ew t hese at a
l at er st age.
' Fi ni sh' t o r evi ew t he i nst al l at i on.

Summar y
Sel ect Ok t o cl ose t he r evi ew page and
' Fi ni sh' t o st ar t t he i nst al l at i on.

Once dat abase cr eat i on i s done a summar y scr een wi l l be di spl ayed.
' Exi t ' t o exi t t he OUI .

# check Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep
9. Postinstallation tasks
As t he or acl e user edi t t he / et c/ or at ab f i l e on bot h nodes.
Repl ace t he dat abase name wi t h t he i nst ance name f or t he r ac dat abase
i . e. r epl ace t he rac keywor d wi t h rac1 or rac2 dependi ng on t he node.
Fur t her mor e add det ai l s f or your cl ust er war e home t o t hi s f i l e.
Thi s wi l l enabl e you t o set t he Cl ust er war e home usi ng t he or aenv scr i pt .
Once edi t ed t he / et c/ or at ab f i l e shoul d cont ai n t he f ol l owi ng:
vi / et c/ or at ab
On node RAC1:
+ASM1: / u01/ app/ or acl e/ pr oduct s/ 10. 2. 0/ db_1: N
r ac1: / u01/ app/ or acl e/ pr oduct s/ 10. 2. 0/ db_1: N
cr s: / u01/ cr s: N

On node RAC2
+ASM2: / u01/ app/ or acl e/ pr oduct s/ 10. 2. 0/ db_1: N
r ac2: / u01/ app/ or acl e/ pr oduct s/ 10. 2. 0/ db_1: N
cr s: / u01/ cr s: N


# ver i f y t he Cl ust er Regi st r y conf i gur at i on
sr vct l conf i g dat abase - d r ac

# backup t he r oot . sh scr i pt
cp / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ r oot . sh ~/ r oot . sh. bak

# Back up t he vot i ng di sk
dd i f =/ dev/ r aw/ r aw2 of =~/ vdi sk. bak

# ver i f y t hat OEM i s wor ki ng
ht t ps: / / r ac1. mydomai n. com: 1158/ em
# r est ar t t he dbconsol e i f r equi r ed
emct l st at us dbconsol e
emct l st op dbconsol e
Page 430 Oracle DBA Code Examples

emct l st ar t dbconsol e
10. Useful Postinstallation Tasks
Following are tips to consider after the successful installation to make managing RAC
easier.
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems
/ * Make cr s_st at - t mor e r eadabl e */
/ * copy t he f ol l owi ng scr i pt i nt o ~/ scr i pt s/ cr st at . sh */
#! / usr / bi n/ ksh
#
# Sampl e 10g CRS r esour ce st at us quer y scr i pt
#
# Descr i pt i on:
# - Ret ur ns f or mat t ed ver si on of cr s_st at - t , i n t abul ar
# f or mat , wi t h t he compl et e r sc names and f i l t er i ng keywor ds
# - The ar gument , $RSC_KEY, i s opt i onal and i f passed t o t he scr i pt , wi l l
# l i mi t t he out put t o HA r esour ces whose names mat ch $RSC_KEY.
# Requi r ement s:
# - $ORA_CRS_HOME shoul d be set i n your envi r onment
# suggest ed scr i p name: cr st at . sh

RSC_KEY=$1
QSTAT=- u
AWK=/ usr / bi n/ awk # i f not avai l abl e use / usr / bi n/ awk

# Tabl e header : echo " "
$AWK \
' BEGI N {pr i nt f " %- 45s %- 10s %- 18s\ n" , " HA Resour ce" , " Tar get " , " St at e" ;
pr i nt f " %- 45s %- 10s %- 18s\ n" , " - - - - - - - - - - - " , " - - - - - - " , " - - - - - " ; }'

# Tabl e body:
$ORA_CRS_HOME/ bi n/ cr s_st at $QSTAT | $AWK \
' BEGI N { FS=" =" ; st at e = 0; }
$1~/ NAME/ && $2~/ ' $RSC_KEY' / {appname = $2; st at e=1};
st at e == 0 {next ; }
$1~/ TARGET/ && st at e == 1 {appt ar get = $2; st at e=2; }
$1~/ STATE/ && st at e == 2 {appst at e = $2; st at e=3; }
st at e == 3 {pr i nt f " %- 45s %- 10s %- 18s\ n" , appname, appt ar get , appst at e;
st at e=0; }'


# t hen add t he f ol l owi ng i n t he . bashr c of or acl e user
# i f t he f i l e was saved i n ~/ scr i pt s/ cr st at . sh
al i as cr st at =' ~/ scr i pt s/ cr st at . sh'

/ * Easy Acces t o cr s and db homes */
# i t i s common t o access bi n di r ect or i es i n cl ust er war e and db homes

# add t he f ol l owi ng t o . bashr c of or acl e user
al i as db=' cd $ORACLE_HOME/ bi n'
al i as cr s=' cd $ORA_CRS_HOME/ bi n'
Page 431 Oracle DBA Code Examples

Installing Oracle 11g R2 RAC on Enterprise Linux 5
Note: The metalink document RAC Starter Kit and Best Practices (Linux) [ID 811306.1] is a
good source reference for this task.
Main Changes in Oracle 11g Release 2 RAC
SCAN: single client access name (SCAN) is a domain name used by all clients connecting
to the cluster. It is registered to three IP addresses, either in the domain name service
(DNS) or the Grid Naming Service (GNS).
GNS: enables using DHCP, which must be configured in the subdomain in which the cluster
resides.
OCR and Voting can now be configured on an ASM diskgroup.
Passwordless automatic SSH connectivity: the installer can configure SSH for you.
Intelligent Platform Management interface (IPMI): provides a set of common interfaces to
computer hardware and firmware that administrators can use to monitor system health
and manage the system.
Time sync: The new Oracle Cluster Time Synchronization Service is designed for
organizations whose Oracle RAC databases are unable to access NTP services.
Grid Infrastructure home: Clusterware and ASM share the same Oracle Home.
Hangchecktimer replaced by the cluster synchronization service daemon Agent and
Monitor to provide more accurate recognition of hangs and to avoid false termination.
Installation Environment
Emulation software: VMWare Workstation 7
RAC Nodes: 2 nodes with 2.5 GB RAM each , 2 ethernet cards.
OS: Oracle Linux Enterprise 5 for x86 32-bit
Required Software
Oracle Database 11g Release 2 for Linux x86 32-bit
Oracle Database 11g Release 2 Grid Infrastructure (11.2.0.1.0) for Linux x86 32-bit
Used Hardware
In the VMWare: create one virtual machine (rac1) with the following specs:
o 2.5 GB RAM
o Two ethernet cards: both can be configured as bridged or host-only in VMware.
o One local hardisk with 24 GB on SCSI 0:0.
o CPU Count: 2
Page 432 Oracle DBA Code Examples

o Create a folder in the same directory structure level as the parent folder containing the
created virtual machine. Give it a meaningful name like 'shared_disks'. Create in that
folder the following disks:
Disk1: of 3 GB. Allocate its disk space. It will be used for OCR and
Voting disk. Set it on controller SCSI 1:1.
Disk2: of 4 GB. Allocate its disk space. It will be used for +Data. Set it
on controller SCSI 1:2.
Disk3: of 2 GB. Allocate its disk space. It will be used for +Flash. Set it
on controller SCSI 1:3.


Installation Plan
11. Preinstallation tasks
Hardware requirements
Software requirements
Environment configuration
12. Oracle Grid Infrastructure installation
13. Oracle Grid Infrastructure Patching
14. Oracle Database 11g R2 Software Installation
15. Oracle Database 11g R2 Software Patching
16. Install EM Agent in cluster nodes (if required)
Page 433 Oracle DBA Code Examples

17. ASM Diskgroups Creation
18. RAC Database Creation
19. Complete postinstallation tasks
20. Useful postinstallation tasks
Note: The installation is explained without GNS and IPMI
Note: For this installation we will be using ASM for Clusterware and Database storage
1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Configure the swap area in the local hardisk to have 3 GB disk space.
o Give the first ethernet card IP 192.0.2.100 and the second 172.0.2.100 and the
hostname r ac1. mydomai n. com. Define a gateway. If it does not exist, make it same as
the host IP address.
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Applications
o Graphical Internet (optional)
o Editors (optional)
Development
o Development Libraries
o Development Tools
Servers
o Do not select anything in this group.
Base System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
X Window System
Complete the installation.
After the Installation compelets, RHEL 5.2 and below will hang on booting when it reaches
to "starting udev" line. To solve this problem, shutdown the Vmware machine and change
the CPU count and Core Count to only one. Implement the changes below, then shutdown
the machine, set CPU count back to 2 and startup the machine.
put the kernel command line parameters at the end of the "kernel" line:
vi / boot / gr ub/ gr ub. conf
add di vi der =10 cl ocksour ce=acpi _pm
Page 434 Oracle DBA Code Examples

For example: ker nel / vml i nuz- 2. 6. 18 . . cl ock=acpi _pmdi vi der =10
For Vmware machines, install VMWare tools and set it to synchronize its time with the
guest: vmwar et ool box. Alternatvily, you can use Oracle Cluster Time Synchronization
Service (ctssd) (metalink document 551704.1)
Install further packages:
# t o know di st r i but i on and ver si on of Li nux ( Red Hat Ent . 5. 2 used)
cat / et c/ i ssue
# t o know ker nel ver si on ( and i t s er r at a l evel ) ( 2. 6. 18- 92 or newer )
uname - r

# t o l i st mi ssed packages:
r pm- q - - qf ' %{NAME}- %{VERSI ON}- %{RELEASE} ( %{ARCH}) \ n' bi nut i l s \
compat - l i bst dc++- 33 \
el f ut i l s- l i bel f \
el f ut i l s- l i bel f - devel \
gcc \
gcc- c++ \
gl i bc \
gl i bc- common \
gl i bc- devel \
gl i bc- header s \
ksh \
l i bai o \
l i bai o- devel \
l i bgcc \
l i bst dc++ \
l i bst dc++- devel \
make \
sysst at \
uni xODBC \
uni xODBC- devel

# f or mi ssed packages, i nst al l t hem:
r pm- Uvh l i bai o- devel - 0. 3. 106- 3. 2. i 386. r pm
r pm- Uvh uni xODBC*

# Downl oad t he appr opr i at e ASMLi b RPMs f r omOTN.
# t o know t he ker nel ver i on: uname - r m
# I n t hi s case we need:
or acl easm- 2. 6. 18- 92. el 5- 2. 0. 5- 1. el 5. i 686. r pm
or acl easml i b- 2. 0. 4- 1. el 5. i 386. r pm
or acl easm- suppor t - 2. 1. 3- 1. el 5. i 386. r pm

r pm- Uvh or acl easm*. r pm

# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Check the hardware requirements
# Har dwar e Requi r ement s ( i n cl ust er nodes)
# At l east 1. 5 GB of physi cal memor y but pr act i cal l y 1. 5 i s not f i ne
gr ep MemTot al / pr oc/ memi nf o
Page 435 Oracle DBA Code Examples


# swap space: same as t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o

# t o di spl ay swap and memor y i n one command:
f r ee

# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 1 GB di sk space i n / t mp
df - h / t mp
# 8 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
# df - h / dev/ shm/
Create the required network configuration (rac2 will be created later):
o Public and Private interface names must be the same for all nodes.
o This private hostname does not need to be resolvable through DNS and should be
entered in the /etc/hosts file.
o SCAN VIPs must NOT be in the /etc/hosts file, it must be resolved by DNS. But here
I've defined it as a single IP address in the "/etc/hosts" file, which is wrong and will
cause the cluster verification to fail, but it allows me to complete the install without the
presence of a DNS.
o If you are using a DNS, Oracle recommends that you add lines to the /etc/hosts file on
each node, specifying the public IP, VIP and private addresses.
o If you configured the IP addresses in a DNS server, then, as the root user, change the
hosts search order in /etc/nsswitch.conf on all nodes as shown:
Old: host s: f i l es ni s dns
New: host s: dns f i l es ni s
o Then restart nscd daemon on each node: / sbi n/ ser vi ce nscd r est ar t
# Net wor k names Resol ut i on
# conf i gur e / et c/ host s i f no domai n ser ver i s used ( bot h nodes)
vi / et c/ host s
127. 0. 0. 1 l ocal host . l ocal domai n l ocal host
#et h0 - PUBLI C
192. 0. 2. 100 r ac1. mydomai n. comr ac1
192. 0. 2. 101 r ac2. mydomai n. comr ac2
#VI P
192. 0. 2. 102 r ac1- vi p. mydomai n. comr ac1- vi p
192. 0. 2. 103 r ac2- vi p. mydomai n. comr ac2- vi p
#et h1 - PRI VATE
Page 436 Oracle DBA Code Examples

172. 0. 2. 100 r ac1- pr i v
172. 0. 2. 101 r ac2- pr i v

# i n r eal pr oduct i on: t he f ol l wi ng shoul d not be t her e at al l
# SCAN: cl ust er _name- scan. GNS_subdomai n_name
192. 0. 2. 104 r ac- scan. mydomai n. comr ac- scan
Create and configure the required OS users and groups
Note: userid and groupid must be the same in all nodes. You can check them by i d
or acl e command.
# al l gr oup and user i ds on al l t he nodes must have i dent i cal i d
# Gr i d I nf r ast r uct ur e ( GI ) and t he Or acl e RDBMS home wi l l
# be i nst al l ed usi ng di f f er ent user s:
/ usr / sbi n/ gr oupadd - g 501 oi nst al l
/ usr / sbi n/ gr oupadd - g 502 dba
/ usr / sbi n/ gr oupadd - g 504 asmadmi n
/ usr / sbi n/ gr oupadd - g 506 asmdba
/ usr / sbi n/ gr oupadd - g 507 asmoper
/ usr / sbi n/ user add - u 501 - g oi nst al l - G asmadmi n, asmdba, asmoper gr i d
/ usr / sbi n/ user add - u 502 - g oi nst al l - G dba, asmdba or acl e

# set passwor ds
passwd or acl e
passwd gr i d

# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody

# define the env variables for oracle user
vi /home/oracle/.bash_profile
# Oracle Settings
export EDITOR=vi
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR
ORACLE_HOSTNAME=rac1.mydomain.com; export ORACLE_HOSTNAME
ORACLE_UNQNAME=RAC; export ORACLE_UNQNAME
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1; export ORACLE_HOME
ORACLE_SID=RAC1; export ORACLE_SID
ORACLE_TERM=xterm; export ORACLE_TERM
PATH=/usr/sbin:$PATH; export PATH
PATH=$ORACLE_HOME/bin:$PATH; export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export
CLASSPATH

# shel l st ar t up f i l e
vi / et c/ pr of i l e
i f [ $USER = " or acl e" ] | | [ $USER = " gr i d" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i

Page 437 Oracle DBA Code Examples

# f or C shel l
vi / et c/ csh. l ogi n
i f ( $USER = " or acl e" | | $USER = " gr i d" ) t hen
l i mi t maxpr oc 16384
l i mi t descr i pt or s 65536
endi f
Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start,
then you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Ker nel Par amet er s
# t o t une t hme, r ef er t o met al i nk document 169706. 1
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf

# ker nel . shmmax not st at ed i n 11g R2 ( max: 4G) ( 169706. 1)
ker nel . shmmni = 4096
ker nel . sem= 250 32000 100 128
f s. ai o- max- nr = 1048576
f s. f i l e- max = 6815744
net . i pv4. i p_l ocal _por t _r ange = 9000 65500
net . cor e. r mem_def aul t = 262144
net . cor e. r mem_max = 4194304
net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 1048576

# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf
gr i d sof t npr oc 2047
gr i d har d npr oc 16384
gr i d sof t nof i l e 1024
gr i d har d nof i l e 65536
or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536

vi / et c/ pam. d/ l ogi n
sessi on r equi r ed pam_l i mi t s. so
Create the required directories for the Oracle software:
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

# Or acl e I nvent or y Di r ect or y
# as a r oot
mkdi r - p / u01/ app/ or aI nvent or y
chown - R gr i d: oi nst al l / u01/ app/ or aI nvent or y
chmod - R 775 / u01/ app/ or aI nvent or y
Page 438 Oracle DBA Code Examples


# Gr i d I nf r ast r uct ur e Home Di r ect or y
mkdi r - p / u01/ 11. 2. 0/ gr i d
chown - R gr i d: oi nst al l / u01/ 11. 2. 0/ gr i d
chmod - R 775 / u01/ 11. 2. 0/ gr i d

# Or acl e Base Di r ect or y
mkdi r - p / u01/ app/ or acl e
#needed t o ensur e t hat dbca i s abl e t o r un af t er t he r dbms i nst al l at i on
mkdi r / u01/ app/ or acl e/ cf gt ool l ogs
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ app/ or acl e

# Or acl e RDBMS Home Di r ect or y
mkdi r - p / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chown - R or acl e: oi nst al l / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chmod - R 775 / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
Shutdown the Vmware machine then edit the VMware file (with vmx extensions) and add
the following entry to allow sharing the disks (make sure the scsi controller number is the
one you used):
di sk. l ocki ng = " FALSE"
di skLi b. dat aCacheMaxSi ze = " 0"
di skLi b. dat aCacheMaxReadAheadSi ze = " 0"
di skLi b. dat aCacheMi nReadAheadSi ze = " 0"
di skLi b. dat aCachePageSi ze = " 4096"

scsi 1. shar edBus = " vi r t ual "

scsi 1: 1. devi ceType = " di sk"
scsi 1: 2. devi ceType = " di sk"
scsi 1: 3. devi ceType = " di sk"
Startup the machine then partition the disks:
Note: On a real life storage, you would create a single whole-disk partition with exactly 1 MB
offset on each LUN to be used as ASM Disk. In fdisk: u (to change units from cylinder to
sectors), n, p, 1, 2048, w.
# as a r oot , f or t he di sks / dev/ sdb . . / dev/ sdd
# conf i r mt hey ar e seen:
l s / dev/ sd*
#par t i t i on t he di sks:
f di sk / dev/ sdb
# answer s: " n" , " p" , " 1" , " Ret ur n" , " Ret ur n" , " p" and " w"
Not e: i f t he f ol l owi ng message appear s af t er t he " w" command:
WARNI NG: Re- r eadi ng t he par t i t i on t abl e f ai l ed wi t h er r or 16: Devi ce or
r esour ce busy, t hen you can avoi d r est ar t i ng t he machi ne by t he f ol l owi ng
command: par t pr obe

# t o make sur e par t i ons ar e cr eat ed
l s - l X / dev/ sd*
Configure ASM drivers:
Note: If you see that the shared disks are not synced between rac1 and rac2, one of the
things you can examine is to see if there is any "debug" command in any of the nodes'
vmx files. If you find one, shutdown the node, remove the command from the vmx file and
restart.
# as r oot ( t o be done i n al l nodes)
Page 439 Oracle DBA Code Examples

or acl easmconf i gur e - i

Def aul t user t o own t he dr i ver i nt er f ace [ ] : grid
Def aul t gr oup t o own t he dr i ver i nt er f ace [ ] : asmdba
St ar t Or acl e ASM l i br ar y dr i ver on boot ( y/ n) [ n] : y
Fi x per mi ssi ons of Or acl e ASM di sks on boot ( y/ n) [ y] : y
Wr i t i ng Or acl e ASM l i br ar y dr i ver conf i gur at i on: [ OK ]
Cr eat i ng / dev/ or acl easmmount poi nt : [ OK ]
Loadi ng modul e " or acl easm" : [ OK ]
Mount i ng ASMl i b dr i ver f i l esyst em: [ OK ]
Scanni ng syst emf or ASM di sks: [ OK ]

# Load t he ker nel modul e usi ng t he f ol l owi ng command:
/ usr / sbi n/ or acl easmi ni t
# I f you have any pr obl ems, make sur e you have t he cor r ect
# ver si on of t he dr i ver :
/ usr / sbi n/ or acl easmupdat e- dr i ver

# mar k t he shar ed di sks: ( one node)
/ usr / sbi n/ or acl easmcr eat edi sk DI SK1 / dev/ sdb1
/ usr / sbi n/ or acl easmcr eat edi sk DI SK2 / dev/ sdc1
/ usr / sbi n/ or acl easmcr eat edi sk DI SK3 / dev/ sdd1

# check t he di sks ar e mar ked and seen:
/ usr / sbi n/ or acl easml i st di sks

# i n ot her nodes:
/ usr / sbi n/ or acl easmscandi sks
/ usr / sbi n/ or acl easml i st di sks

#I f you need t o unmar k a di sk t hat was used i n a cr eat edi sk command:
/ usr / sbi n/ or acl easmdel et edi sk DI SK1
/ usr / sbi n/ or acl easmdel et edi sk DI SK2
/ usr / sbi n/ or acl easmdel et edi sk DI SK3
Disable screensavers on host & guest machines.
o In Oracle Linux: Applications-> Preferences-> Screen Saver
o Do the same after logging off and logging on again as or acl e and gr i d user.
Shutdown rac1
Copy the folder containing rac1 into a new folder in the same directory structure level.
Let's name it "rac2". This will be the second node in the cluster.
Edit the VMware file of rac1 and edit the following: displayName = "rac2"
Open rac2, then perform:
o in a terminal issue: system-config-network-gui.
o Remove the devices with the "%.bak" nicknames. To do this, highlight a device,
deactivate, then delete it.
o Highlight the "eth0" interface and click the "Edit" button. Change its IP addresses and
gate way: IP 192.0.2.101. Click on the "Hardware Device" tab and click the "Probe"
button.
o For eth1 set its ip address to 172.0.2.101. Do not define a gateway.
o In DNS tab, change hostname to rac2.mydomain.com.
o Activate the network cards.
Page 440 Oracle DBA Code Examples

In rac2, perform:
# change t he var i abl e i n t he f i l e
vi / home/ or acl e/ . bash_pr of i l e
ORACLE_SI D=RAC2; expor t ORACLE_SI D
ORACLE_HOSTNAME=r ac2. l ocal domai n; expor t ORACLE_HOSTNAME
Start rac1. Make sure the machines can see each other:
pi ng - c 3 r ac1
pi ng - c 3 r ac1- pr i v
pi ng - c 3 r ac2
pi ng - c 3 r ac2- pr i v
2. Oracle Grid Infrastructure installation
# i n r ac1: copy t he sof t war e i n a st agi ng f ol der
mkdi r - p / u01/ app/ st age/ or a11gr 2gr i di nf r a
chown - R gr i d: oi nst al l / u01/ app/ st age/ or a11gr 2gr i di nf r a
chmod - R 775 / u01/ app/ st age/ or a11gr 2gr i di nf r a

mkdi r - p / u01/ app/ st age/ or a11gr 2db
chown - R or acl e: oi nst al l / u01/ app/ st age/ or a11gr 2db
chmod - R 775 / u01/ app/ st age/ or a11gr 2db

# i n al l nodes, make sur e t he asmdi sks ar e accessi bl e:
/ usr / sbi n/ or acl easmscandi sks
/ usr / sbi n/ or acl easml i st di sks

# do not use cl uvf y because SSH was not conf i gur ed.

# l unch OUI f r omt he cl ust er war e ( as grid f r omr ac1)
# i f l ogged i n i n Genome usi ng anot her user , l og out and l og i n as gr i d
cd / u01/ app/ st age/ or a11gr 2gr i di nf r a
. / r unI nst al l er

I nst al l at i on Opt i on
>Sel ect r adi o but t on ' I nst al l and Conf i gur e Gr i d I nf r ast r uct ur e f or a Cl ust er '
>Next

I nst al l at i on Type
>Sel ect ' Advanced I nst al l at i on'
>Next

Pr oduct Language
>Accept ' Engl i sh' as l anguage'
>Next

Gr i d Pl ug and Pl ay
>cl ust er name: r ac
>SCAN name: r ac- scan. mydomai n. com
>Make sur e ' Conf i gur e GNS' i s NOT sel ect ed
>Next

Cl ust er Node I nf or mat i on
>Add but t on
>Host name: r ac2. mydomai n. com
>Vi r t ual I P Name: r ac2- vi p. mydomai n. com
>OK
Page 441 Oracle DBA Code Examples


>" SSH Connect i vi t y" but t on
>Ent er t he passwor d
>Set up but t on
>Test but t on

Net wor k I nt er f ace Usage
>check t he publ i c and pr i vat e net wor ks ar e speci f i ed cor r ect l y
>Next

St or age Opt i on
>Sel ect ' Aut omat i c St or age Management ( ASM) '
>Next

Cr eat ASM Di sk Gr oup
>Di sk Gr oup Name: DGOCRVOTE ( 3GB di sk: Di sk1)
>Redundancy: ext er nal
>Next
NOTE: I f you see an empt y scr een f or you candi dat e di sks i t i s l i kel y t hat
ASMLi b has not been pr oper l y conf i gur ed. Tr y r econf i gur e t hem.
I f you ar e sur e t hat ASMLi b has been pr oper l y conf i gur ed cl i ck on ' Change
Di scover y Pat h' and pr ovi de t he cor r ect dest i nat i on.

ASM Passwor d
>Speci f y and conf or mt he passwor d you want t o use
>Next

Fai l ur e I sol at i on Suppor t
>Sel ect NOT t o use I PMI
>Next

Pr i vi l eged OS Gr oups
>Assi gn t he cor r ect OS gr oups f or OS aut hent i cat i on ( most l y def aul t i s OK)
>Next

I nst al l at i on Locat i on
>ORACLE_BASE: / u01/ app/ or acl e
Sof t war e l ocat i on: / u01/ 11. 2. 0/ gr i d
>Next

Cr eat e I nvent or y
>Speci f y t he l ocat i ons: / u01/ app/ or aI nvent or y
>Next

Per f or mPr er equi si t e Checks
>OUI per f or ms cer t ai n checks
>Check t hat st at us of al l checks i s Succeeded
Not e: i n t hi s exampl e, NPS er r or can be i gnor ed
>Next

Summar y
>Fi ni sh

Execut e Conf i gur at i on Scr i pt s
>Run t he scr i pt s as i nst r uct ed i n t he scr een
Not e: The scr i pt s must be r un on one node at a t i me.
>OK
Page 442 Oracle DBA Code Examples


We expect t he ver i f i cat i on phase t o f ai l wi t h an er r or r el at i ng t o t he SCAN,
assumi ng you ar e not usi ng DNS.
I NFO: Checki ng Si ngl e Cl i ent Access Name ( SCAN) . . .
I NFO: Checki ng name r esol ut i on set up f or " r ac- scan. l ocal domai n" . . .
I NFO: ERROR:
I NFO: PRVF- 4664 : Found i nconsi st ent name r esol ut i on ent r i es f or SCAN name
" r ac- scan. l ocal domai n"
I NFO: ERROR:
I NFO: PRVF- 4657 : Name r esol ut i on set up check f or " r ac- scan. l ocal domai n"
( I P addr ess: 192. 168. 2. 201) f ai l ed
I NFO: ERROR:
I NFO: PRVF- 4664 : Found i nconsi st ent name r esol ut i on ent r i es f or SCAN name
" r ac- scan. l ocal domai n"
I NFO: Ver i f i cat i on of SCAN VI P and Li st ener set up f ai l ed
Pr ovi ded t hi s i s t he onl y er r or , i t i s saf e t o i gnor e t hi s
>Next

Message: The i nst al l at i on of t he Gr i d I nf r ast r uct ur e was successf ul l .
>Cl ose

Not e: I f your OS i s SUSE Li nux, shut t i ng down on node wi l l r esul t i n shut t i ng
t he ot her nodes. To wor kar ound:
#cd / et c/ r c3. d
#l n - s / et c/ i ni t . d/ ohasd K07ohasd
3. Oracle Grid Infrastructure Patching
Appl y pat ch set , i f t her e i s any.
4. Oracle Database 11g R2 Software Installation
# make sur e al l cl ust er war e pr ocesses ar e r unni ng
/ u01/ cr s/ bi n/ cr s_st at - t

# as oracle
. / r unI nst al l er

Conf i gur e Secur i t y Updat es
>Pr ovi de your e- mai l addr ess, i f you want
>Next

I nst al l at i on Opt i ons
>Sel ect ' I nst al l Dat abase sof t war e onl y'
>Next >

I nst al l Type
>Sel ect ' Real Appl i cat i on Cl ust er s dat abase i nst al l at i on' , and sel ect al l
nodes.
>Use t he ' SSH Connect i vi t y' but t on t o conf i gur e/ t est t he passwor dl ess SSH
connect i vi t y.
>Next

Pr oduct Languages
>Conf i r m' Engl i sh'
>Next

Dat abase Edi t i on
Page 443 Oracle DBA Code Examples

>' Ent er pr i se Edi t i on' i s t i cked
>Next

I nst al l at i on Locat i on
>Or acl e Base: / u01/ app/ or acl e
Sof t war e Locat i on: / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
>Next

Pr i vi l eged OS Gr oups
>OSDBA: dba
>OSOPER: oi nst al l
>Next

Pr er equi si t e Checks
. . OUI per f or ms pr er equi si t e checks
>Check t hat st at us of al l checks i s Succeeded
>I f you ar e sur e t he unsuccessf ul l checks can be i gnor ed t i ck t he box ' I gnor e
Al l '
>Next

Summar y
>Check summar y i nf o
>Fi ni sh

I nst al l Pr oduct
. . OUI i nst al l s t he db sof t war e
>as a r oot , r un t he r oot . sh scr i pt on t he f i r st node t hen t he ot her nodes ( One
at a t i me)
>OK

Fi ni sh
>Cl ose
5. Oracle Database 11g R2 Software Patching

6. Install EM Agent in cluster nodes (if required)

7. ASM Diskgroups Creation
Note: It is Oracle's Best Practise to have an OCR mirror stored in a second disk group. To
follow this recommendation add an OCR mirror. Mind that you can only have one OCR in a
diskgroup. To add OCR mirror to an Oracle ASM disk group, ensure that the Oracle
Clusterware stack is running and
ocr conf i g - add +ORADATA
ocr check
# as gr i d user : st ar t t he ASM Conf i gur at i on Assi st ant ( ASMCA)
#su - grid
cd / u01/ 11. 2. 0/ gr i d/ bi n
. / asmca

>Di sk Gr oups t ab
>Cr eat e but t on
>Di sk Gr oup Name: DGDATA
Page 444 Oracle DBA Code Examples

>Redundancy: Ext er nal
>Di sk2
>OK

>Cr eat e but t on
>Di sk Gr oup Name: DGFLASH
>Redundancy: Ext er nal
>Di sk3
>OK

>Exi t
>Yes
8. RAC Database Creation
# as or acl e
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n
. / dbca

Wel come
Sel ect ' Or acl e Real Appl i cat i on Cl ust er s dat abase'
>Next

Oper at i ons
> choose opt i on ' Cr eat e a Dat abase'
>Next

Dat abase Templ at e
>Sel ect Gener al Pur pose or any t empl at e
>Next

Dat abase I dent i f i cat i on
>Conf i gur at i on Type: Admi n
>Gl obal e Dat abase Name: r ac
>SI D: r ac
>Sel ect Al l but t on
>Next

Management Opt i ons
>Sel ect t he opt i on you want
>Next

Dat abase Cr edent i al s
>Set t he passwor d( s)
>Next

Dat abase Fi l e Locat i ons
>Dat abase Ar ea: +DGDATA
>Pr act i cal l y ( but not i n t hi s case) , you shoul d def i ne ' Mul t i pl ex Redo Logs
and Cont r ol Fi l es' .
>Next

/ * Not e: I f you cannot see t he di skgr oups, per f or mt he f ol l owi ng ( I D:
1177483. 1) :
su -
cd <Gr i d_Home>/ bi n
chmod 6751 or acl e
l s - l or acl e
Page 445 Oracle DBA Code Examples

- r wsr - s- - x 1 gr i d oi nst al l
*/

ASM Cr edent i al s
. . I f you chose t o set up EM, you wi l l be asked about ASMSNMP passwor d
>Ent er t he passwor d
>Ok but t on

Recover y Conf i gur at i on
>Fl ash r ecover y ar ea: +DGFLASH
>def i ne t he si ze: 2000 MB
I f t he si ze i s smal l er t han r ecommended a war ni ng wi l l popup.
>Enabl e Ar chi vi ng
>Next

Dat abase Cont ent
>Sel ect i f you want t o have sampl e schemas cr eat ed i n your dat abase
>Next

I ni t i al i zat i on Par amet er s
>Revi ew and change t he set t i ngs f or memor y al l ocat i on, char act er set et c.
>Next

Dat abase St or age
>Revi ew t he dat abase st or age set t i ngs and change as r equi r ed
>Next

Cr eat i on Opt i ons
>Make sur e t he t i ckbox ' Cr eat e Dat abase' i s t i cked
>Fi ni sh

Summar y
>OK
. . Dat abase cr eat i on pr oceedi ng
>af t er compl et i on Exi t

# Conf i r mat i on

# t o show t he cur r ent conf i gur at i on and st at us of t he RAC dat abase
sr vct l conf i g dat abase - d r ac

# check OEM ( i f conf i gur ed) :
ht t ps: / / r ac1. mydomai n. com: 1158/ em/
# i f not st ar t ed, you can st ar t i t :
su - or acl e
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n
expor t ORACLE_UNQNAME=r ac
. / emct l st at us dbconsol e

# check Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep
9. Postinstallation tasks
# backup t he r oot . sh scr i pt ( on al l nodes)
cp / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ r oot . sh ~/ r oot . sh. bak
Page 446 Oracle DBA Code Examples

10. General Useful Postinstallation Tasks in Linux
Following are tips to consider after the successful installation to make managing RAC
easier.
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems
/ * Make cr s_st at - t mor e r eadabl e */
/ * copy t he f ol l owi ng scr i pt i nt o ~/ scr i pt s/ cr st at . sh */
#! / usr / bi n/ ksh
#
# Sampl e 10g CRS r esour ce st at us quer y scr i pt
#
# Descr i pt i on:
# - Ret ur ns f or mat t ed ver si on of cr s_st at - t , i n t abul ar
# f or mat , wi t h t he compl et e r sc names and f i l t er i ng keywor ds
# - The ar gument , $RSC_KEY, i s opt i onal and i f passed t o t he scr i pt , wi l l
# l i mi t t he out put t o HA r esour ces whose names mat ch $RSC_KEY.
# Requi r ement s:
# - $ORA_CRS_HOME shoul d be set i n your envi r onment
# suggest ed scr i p name: cr st at . sh

RSC_KEY=$1
QSTAT=- u
AWK=/ usr / bi n/ awk # i f not avai l abl e use / usr / bi n/ awk

# Tabl e header : echo " "
$AWK \
' BEGI N {pr i nt f " %- 45s %- 10s %- 18s\ n" , " HA Resour ce" , " Tar get " , " St at e" ;
pr i nt f " %- 45s %- 10s %- 18s\ n" , " - - - - - - - - - - - " , " - - - - - - " , " - - - - - " ; }'

# Tabl e body:
$ORA_CRS_HOME/ bi n/ cr s_st at $QSTAT | $AWK \
' BEGI N { FS=" =" ; st at e = 0; }
$1~/ NAME/ && $2~/ ' $RSC_KEY' / {appname = $2; st at e=1};
st at e == 0 {next ; }
$1~/ TARGET/ && st at e == 1 {appt ar get = $2; st at e=2; }
$1~/ STATE/ && st at e == 2 {appst at e = $2; st at e=3; }
st at e == 3 {pr i nt f " %- 45s %- 10s %- 18s\ n" , appname, appt ar get , appst at e;
st at e=0; }'


# t hen add t he f ol l owi ng i n t he . bashr c of or acl e user
# i f t he f i l e was saved i n ~/ scr i pt s/ cr st at . sh
al i as cr st at =' ~/ scr i pt s/ cr st at . sh'

/ * Easy Acces t o cr s and db homes */
# i t i s common t o access bi n di r ect or i es i n cl ust er war e and db homes

# add t he f ol l owi ng t o . bashr c of or acl e user
al i as db=' cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n'

# add t he f ol l owi ng t o . bashr c of gr i d user
al i as cr s=' cd / u01/ app/ or acl e/ cr s/ bi n'
Page 447 Oracle DBA Code Examples

Installing Oracle 10g R2 RAC on Windows
Note: The metalink document RAC Starter Kit and Best Practices (Windows) [ID 811271.1] is
a good source reference for this task.
Installation Methods
NTFS_RAW_ASM (shown in this document)
NTFS_RAW_RAM
NTFS_OCFS_OCFS
Installation Environment
Emulation software: VMWare Server 2 for Windows.
RAC Nodes: 2 nodes
OS: Windows 2003 Server Standard Edition 32-bit SP2
Required Software
Oracle 10g R2 Clusterware for Windows 32-bit
Oracle Database 10g Release 2 for Windows 32-bit
Used Virtual Hardware
In the VMWare: create one virtual machine (rac1) with the following specs:
o 2 GB RAM
o two ethernet cards: both can be configured as bridged or host-only in VMware.
o one local hardisk with 20 GB on controller SCISI 0:0.
o CPU Count: 2
o create a folder in the same directory structure level as the parent folder containing the
created virtual machine. Give it a meaningful name like 'shared_disks'. Create in that
folder two disks of 10 GB and two of 512 MB each. All of them are of LSI Logic type and
SCISI Persistent. Make sure they are on SCISI controller different from the SCSI0. For
example, set them on SCSI1.

Page 448 Oracle DBA Code Examples


Installation Plan
1. Preinstallation tasks
2. Oracle Clusterware installation
3. Apply Patch Set 3 (10.2.0.4) on Clusterware software
4. Oracle ASM 10g Software Installation
5. Apply Patchset 3 (10.2.0.4) on ASM software
6. Install EM Agent in cluster nodes (if required)
7. Configure Listeners
8. Create ASM Instance
9. Install Oracle RAC Database Home Software
10. Apply Patchset 3 (10.2.0.4) on Oracle RAC Software Home
11. Perform cluster database creation
12. Useful postinstallation steps
1. Preinstallation tasks
The local admin username and password must be the same on both nodes.
Give the first ethernet card IP 192.168.4.11 and the second 192.168.0.11. Define a
gateway. If it does not exist, make it same as the host IP address.
Note: Gateway must be defined and its IP must be alive.
Set the hostname to r ac1. mydomai n. com(Desktop-> right click My Computer->
Properties-> Computer Name-> Change-> type computer name: rac1 -> More-> type
Primary DNS Suffix: mydomain.com
Page 449 Oracle DBA Code Examples

/ * Pr epar e t he r aw di sks */
# enabl e r aw di sk aut o mount i ng
di skpar t
AUTOMOUNT ENABLE
exi t
# t hen r eboot

# st ar t di sk management
st ar t - > r un- > t ype: di skmgmt . msc- > Di sk I ni t i al i zat i on Wi zar d pops up- >
Next - >
mar k al l di sks ( 1- 4) t o i ni t i al i ze- >
make sur e al l di sks ar e unmar ked Next - > Fi ni sh

# al l di sks must be i n Basi c mode ( not dynami c)

r i ght cl i ck Di sk1- > New Par t i t i on- > Next - >
sel ect t he Ext ended par t i t i on r adi o but t on- > Next - >
sel ect t he par t i t i on si ze t o f i l l t he di sk- > Next - > Fi ni sh

r i ght cl i ck on t he par t i t i on and sel ect t he " New Logi cal Dr i ve" - > Next - >
Accept t he def aul t par t i t i on si ze Next - >
sel ect t he " Do not assi gn a dr i ve l et t er or dr i ve pat h" opt i on- >
Next - >
sel ect t he " Do not f or mat t hi s par t i t i on" opt i on- > Next - > Fi ni sh

Repeat t he pr evi ous par t i t i oni ng st eps f or t he r emai ni ng di sks.


/ * Ti me Sync */
- - make sur e t he t i me i s synched i n Vmwar et ool s
- - i n Wi ndows, i n Dat e and Ti me Set t i ngs, t her e i s an opt i on " Aut omat i cal l y
syn wi t h I nt er net Ser ver " whi ch can be conf i gur ed, i f connect ed t o Web
Create the required network configuration (rac2 will be created later):
# Net wor k names Resol ut i on
# i f no domai n ser ver i s used ( bot h nodes)
not epad C: \ WI NDOWS\ syst em32\ dr i ver s\ et c\ host s
127. 0. 0. 1 l ocal host
#Publ i c
192. 168. 4. 11 r ac1. mydomai n. com r ac1
192. 168. 4. 12 r ac2. mydomai n. com r ac2
#VI P
192. 168. 4. 13 r ac1- vi p. mydomai n. com r ac1- vi p
192. 168. 4. 14 r ac2- vi p. mydomai n. com r ac2- vi p
#I nt er - connect
192. 168. 0. 11 r ac1- pr i v. mydomai n. com r ac1- pr i v
192. 168. 0. 12 r ac2- pr i v. mydomai n. com r ac2- pr i v
Disable Windows Media Sensing, which allows Windows to uncouple an IP address from a
card when the link to the local switch is lost:
i n t he r egi st r y:
HKEY_LOCAL_MACHI NE\ Syst em\ Cur r ent Cont r ol Set \ Ser vi ces\ Tcpi p\ Par amet er s
Add t he f ol l owi ng r egi st r y ent r y t o t he Par amet er s subkey:
Name: Di sabl eDHCPMedi aSense
Dat a t ype: REG_DWORD ( Bool ean)
Val ue: 1
Open the "Network Connections" screen (Start > All Programs > Accessories >
Communications > Network Connections). Rename the two connections to "public" and
"private" respectively, making sure you apply the names to the appropriate connections.
Page 450 Oracle DBA Code Examples

Ensure the public interface is first in the bind order:
o Open the "Network Connections" dialog by right-clicking on the "My Network Places"
icon and selecting the "Properties" menu option.
o Select the "Advanced > Advanced Settings..." menu option.
o On the "Adapters and Bindings" tab, make sure the public interface is the first
interface listed. Otherwise, promote it.
Disable screensavers
Shutdown rac1
Edit the VMware file (with vmx extensions) and add the following entry to allow sharing
the disks:
di sk. l ocki ng = " FALSE"
di skLi b. dat aCacheMaxSi ze = " 0"
di skLi b. dat aCacheMaxReadAheadSi ze = " 0"
di skLi b. dat aCacheMi nReadAheadSi ze = " 0"
di skLi b. dat aCachePageSi ze = " 4096"
di skLi b. maxUnsyncedWr i t es = " 0"

scsi 1. shar edBus = " vi r t ual "
scsi 1: 1. devi ceType = " di sk"
scsi 1: 2. devi ceType = " di sk"
scsi 1: 3. devi ceType = " di sk"
scsi 1: 4. devi ceType = " di sk"
scsi 1: 5. devi ceType = " di sk"
Copy the folder containing rac1 into a new folder in the same directory structure level.
Let's name it "rac2". This will be the second node in the cluster.
Edit the VMware file of rac1 and edit the following: displayName = "rac2"
Start rac2 then change it's IP addresses: IP 192.168.4.12 and 192.168.0.12. It's
hostname to rac2.mydomain.com. Modify their default gateway accordingly.
Change hostname to rac2 and restart the virtual machine.
Start rac1 and make sure it can ping rac2.
Perform Net Use test, to make sure files can be transfered:
# on r ac1
net use \ \ r ac2\ c$
# on r ac2
net use \ \ r ac1\ c$
Note: The environment variables TMP & TEMP must point to the same directory in all RAC
nodes, which is the case here.
Stage Oracle software (Clusterware, DB and patch set) in rac1.
Run the CVU to check the state of the cluster prior to the install of the Oracle Software.
The messages 'The system cannot find the file specified' and 'Could not find a suitable set
of interfaces for VIPs' can be ignored.
C: \ t emp\ Or acl eCl ust er war e\ cl uvf y>r uncl uvf y st age - post hwos - n r ac1, r ac2
C: \ . . \ cl uvf y>r uncl uvf y st age - pr e cr si nst - n r ac1, r ac2 - ver bose
2. Oracle Clusterware installation
if you are using terminal services to perform the installation, be sure to invoke the
terminal services in 'console' mode:
mst sc - v: ser ver name / F / consol e
Page 451 Oracle DBA Code Examples

OR, for some (newer) versions of Windows:
mst sc - v: ser ver name / F / admi n
/ * St op I nt er r upt i ng Ser vi ces on bot h nodes */
# t he MSDTC ser vi ce may i nt er r upt i nst al l at i on pr ocess
# i t can be st ar t ed af t er i nst al l at i on
st op t he ser vi ce: Di st r i but ed Tr ansact i on Coor di nat or

# l unch OUI f r omt he cl ust er war e sof t war e ( on r ac1)
cd C: \ t emp\ Or acl eCl ust er war e\
. / set up. exe


>Wel come messge
>Next

>ent er Home Det ai l s
Or aCr 10g
C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s

>Pr oduct - Speci f i c Pr er equi si t e Checks
They al l shoul d succeed

>Speci f y Cl ust er Conf i gur at i on
Sel ect ' Add' and add t he det ai l s f or node r ac2. Ent er al l det ai l s
>OK
r ac2. mydomai n. com
r ac2- pr i v. mydomai n. com
r ac2- vi p. mydomai n. com
>Next

>Speci f y Net wor k I nt er f ace Usage
set t he Publ i c i nt er f ace ( subet net 192. 168. 4. *)
>Ok

>Speci f y Or acl e Cl ust er Regi st r y ( OCR) Locat i on
>Hi ghl i ght di sk 1 and cl i ck t he " Edi t "
>sel ect t he " Pl ace OCR( Pr i mar y) on t hi s Par t i t i on" opt i on >OK
>Hi ghl i ght di sk 2 and cl i ck t he " Edi t "
>Sel ect t he " Pl ace Vot i ng Di sk on t hi s Par t i t i on" opt i on >OK
>Next and i gnor e t he r edundancy war ni ngs
>OK

>Summar y
>I nst al l

>Wai t whi l e t he conf i gur at i on assi st ant s r un

I f t he Conf i gur at i on Assi st ant f ai l s, t her e i s a pr obl emt hat must be f i xed
bef or e pr oceedi ng. Met al i nk document s mi ght hel p: 356535. 1, 310791. 1

VI PCA shoul d f ai l s, j ust cl i ck t he " OK" but t on on t he r esul t i ng er r or scr een
>Next but t on and accept t he subsequent war ni ng
>Exi t

On t he RAC1 vi r t ual machi ne, r un t he VI PCA manual l y:
cd c: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ bi n
vi pca. bat
Page 452 Oracle DBA Code Examples


>Wel come
>Next

>Hi ghl i ght t he " publ i c" i nt er f ace
>Next

>Ent er t he vi r t ual I P al i as and addr ess f or each node: r ac1- vi p. mydomai n. com
Once you ent er t he f i r st al i as, t he r emai ni ng val ues shoul d def aul t
aut omat i cal l y
>Next

>Summar y
>Fi ni sh


# To ver i f y t he i nst al l at i on:
cd C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ BI N
- - 1
cl uvf y st age - post cr si nst - n r ac1, r ac2
- - 2
pi ng r ac1- vi p
pi ng r ac2- vi p
- - 3
cr sct l check cr s

- - 4
# check st at us of cr s daemon pr ocesses ( ALL NODES)
cr s_st at - t
Name Type Tar get St at e Host
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
or a. r ac1. gsd appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac1. ons appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac1. vi p appl i cat i on ONLI NE ONLI NE r ac1
or a. r ac2. gsd appl i cat i on ONLI NE ONLI NE r ac2
or a. r ac2. ons appl i cat i on ONLI NE ONLI NE r ac2
or a. r ac2. vi p appl i cat i on ONLI NE ONLI NE r ac2

# i f St at e of any of t hemi s UNKNOWN, t r y r est ar t i ng t he deamons
cr sct l st op cr s
# t hen st ar t agai n
cr sct l st ar t cr s
3. Apply Patch Set 3 (10.2.0.4) on Clusterware software
There is a bug in Oracle Clusterware 10.2.0.1 in which sometime CRSS service is unable to
access OCR disk. This issue is addressed by Patch Set 3. Therefore, to avoid any possible
problem by this issue, you should apply the Patch Set at this stage.
# ( 1) Appl y t he pat ch on cl ust er war e
# i n ALL NODES
# St op t he f ol l owi ng ser vi ces and make t hei r st ar t up t ype Manual ( i f
r unni ng) :
Or acl e Obj ect Ser vi ce
Or acl eCl ust er Vol umeSer vi ce
Or acl eCRSer vi ce
Or acl eCSSer vi ce
Or acl eEVMSer vi ce
Page 453 Oracle DBA Code Examples


Open t ask manager and ki l l ons pr ocesses, i f t her e i s any.

# i f any of t he ser vi ces i s hang, you can change t he st ar t up t ype f r omr egedi t
t hen r eboot ( don' t f or get t o st op t he Di st r i but ed Tr ansact i on ser vi ce af t er
r eboot ) :
HKEY_LOCAL_MACHI NE - > SYSTEM - > Cur r ent Cont r ol Set - > Ser vi ces - >
Or acl eCSSer vi ce - > Sel ect ( St ar t ) - > Edi t - > Speci f y 3 i n Val ue


# i n RAC1: st ar t oui
cd C: \ t emp\ Pat chset _10204\ Di sk1>
set up. exe
Wel come
>Next

>sel ect Or acl e Cl ust er war e home
>Next
>Conf i r mnodes >Next
>Checki ng shoul d pass >Next
>Summar y
>I nst al l
>Exi t

# updat e t he nodes
# make sur e al l r el at ed Or acl e ser vi ces ar e st opped, ot her wi se st op t hem
# appl y t he bat ch i n node1 t hen node2:
C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ i nst al l \ pat ch102. bat
# i t shoul d end wi t h t he f ol l owi ng message:
Successf ul upgr ade of t hi s node t o Or acl e Cl ust er Ready Ser vi ces

# Or acl e Pr ocess Manager ser vi ce wi l l aut omat i cal l y be i nst al l ed

# check t he updat ed ver i on
cr sct l quer y cr s act i vever si on

# t hen check st at us of deamons
cr s_st at - t

# change t he st ar t up mode of t he ser i ves t o AUTOMATI C
# st ar t up Di st r i but ed Ser vi ce, i f i t was st opped.
4. Oracle ASM 10g Software Installation
# make sur e al l cl ust er war e pr ocesses ar e up and r unni ng
cd C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ BI N
cr s_st at - t

- - i n r ac1: st ar t OUI
cd C: \ t emp\ Or acl eDB10gR2
set up. exe

Wel come
>Next

Sel ect I nst al l at i on Type
>Next

Page 454 Oracle DBA Code Examples

I nst al l Locat i on
>Or acl e Home name: Or aDb10g
>Or acl e Home l ocat i on: C: \ or acl e\ pr oduct \ 10. 2. 0\ db_1
>Next

Speci f y Har dwar e Cl ust er I nst al l at i on Mode
>sel ect bot h nodes
>Next

Pr oduct - Speci f i c Pr er equi si t e Checks
Al l pr e- r equi si t e st eps shoul d compl et e successf ul l y.
>Next

Sel ect Conf i gur at i on Opt i on
>Install Software Only
>Next

Summar y
>Fi ni sh

End of I nst al l at i on
>Exi t

Opt i onal l y, check and modi f y, i f you wi sh, NLS_LANG i n r egedi t .
5. Apply Patchset 3 (10.2.0.4) on ASM Software
Note: This is the patchset applied for this environment. Generally speaking, if there is a newer
version, use it instead of this version. In all cases, same patch set applied to Oracle software
must also be applied to Clusterware first.
#Appl y t he pat ch on DB sof t war e
# i n RAC1: st ar t oui
cd C: \ t emp\ Pat chset _10204\ Di sk1>
set up. exe
Wel come
>Next

>sel ect Or acl e Dat abase home
>Next
>Conf i r mnodes >Next
>Checki ng shoul d pass >Next
>Summar y
>I nst al l

>Exi t

# not r equi r ed, but r ecommended:
r est ar t t he nodes
6. Install EM Agent in cluster nodes (if required)

7. Configure Listeners
# Run net ca ( not net manager whi ch i s not cl ust er awar e) f r omany node
cd C: \ or acl e\ pr oduct \ 10. 2. 0\ db_1\ bi n
net ca. bat
Page 455 Oracle DBA Code Examples


>Sel ect Cl ust er conf i gur at i on and sel ect bot h nodes.
>Conf i gur e Li st ener
>Conf i gur e Nami ng Met hods: Local and Easy Connect

Af t er i nst al l i ng l i st ener check wi t h bel ow commands whet her l i st ener wor ki ng
pr oper l y
C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ bi n\ cr s_st at - t
8. Create ASM Instance
# i n r ac1
cd C: \ or acl e\ pr oduct \ 10. 2. 0\ db_1\ bi n
dbca. bat

Wel come
Keep t he def aul t sel ect i on Or acl e RAC dat abase
>Next

Oper at i ons Sel ect
>Conf i gur e ASM >Next

Node Sel ect i on
>Sel ect ALL t he nodes >Next

Cr eat e ASM I nst ance
Sel ect a SYS passwor d f or t he ASM i nst ance.
Sel ect I FI LE par amet er f i l e t o cr eat e
>Next
>OK ( asmi nst ances wi l l be cr eat ed)

# her e' s an i ssue f aced i n a case af t er cr eat i ng t he ASM i nst ances:
# check t hat t he Admi ni st r at or ( or t he OS you' r e usi ng) bel ong t o or a_dba
# gr oup i n ALL t he Nodes. I f not t her e, add t he user t o t he gr oup.


# St amp t he di sks f or ASM
>Cr eat e New
>St amp Di sks
>Sel ect t he " Add or change l abel " opt i on
>Next
>sel ect t he f i r st Di sk of si ze 10G
>t ype DATA i n t he pr ef i x t ext f i el d ( don' t t ype ASM)
>Next >Next >Fi ni sh

>st amp t he second 10g di sk: r epeat above f or t he second di sk

r ac2 shoul d see t he changes:
asmt ool - l i st

Not e: i f you want t o cl ean t he di sk t o r edo t he pr ocedur e above, you can:
( 1) i n r ac1: DI SKPART, sel ect <DI SK NAMe>, cl ean al l , cr eat e par t ext , cr eat e
par t l og
( 2) i n r ac2: r emove l et t er dr i ve assi gned t o t he par t i t i on

# cr eat e ASM Di sk Gr oups
>Ent er dgdat a1 as t he f i r st di sk gr oup name.
>Set r edundancy set t i ngs t o Ext er nal
Page 456 Oracle DBA Code Examples

>sel ect t he di sk ORCLDI SKDATA0
>Ok

Sel ect Cr eat e New agai n t o add anot her di sk gr oup named as dgf r a. Thi s gr oup
wi l l be used as t he r ecover y ar ae
>OK
>Fi ni sh t o compl et e.

Not e: i n an envi r onment , I kept r ecei vi ng ORA- 15063 er r or . Af t er maki ng sur e
t hat al l t he pr e- r equi si t s wer e appl i ed, t he i ssue was r esol ved by al l ocat i ng
al l t he di sk space at di sk cr eat i on t i me.

# An ASM i nst ance wi l l be cr eat ed i n ever y node named as ASMn
set ORACLE_SI D=ASM1
sql pl us / nol og
SQL>conn / as sysdba
sel ect name f r omv$asm_di skgr oup ;
. . .
9. Install Oracle RAC Database Home Software
# make sur e al l cl ust er war e pr ocesses ar e up and r unni ng
cd C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ BI N
cr s_st at - t


- - i n r ac1: st ar t OUI
cd C: \ t emp\ Or acl eDB10gR2
set up. exe

Wel come
>Next

Sel ect I nst al l at i on Type:
Ent er pr i se Edi t i on
>Next

I nst al l Locat i on
>Or acl e Home name: Or aDb10g2
>Or acl e Home l ocat i on: C: \ or acl e\ pr oduct \ 10. 2. 0\ db_2
>Next

Speci f y Har dwar e Cl ust er I nst al l at i on Mode
>sel ect bot h nodes
>Next

Pr oduct - Speci f i c Pr er equi si t e Checks
Al l pr e- r equi si t e st eps shoul d compl et e successf ul l y
>Next

Upgr ade an Exi st i ng Dat abase
>sel ect No
>Next

Sel ect Conf i gur at i on Opt i on
>I nst al l Sof t war e Onl y
>Next

Page 457 Oracle DBA Code Examples

Summar y
>Fi ni sh

End of I nst al l at i on
>Exi t

Opt i onal l y, check and modi f y, i f you wi sh, NLS_LANG i n r egedi t .
10. Apply Patchset 3 (10.2.0.4) on Oracle RAC Software Home
#Appl y t he pat ch on DB sof t war e
# i n RAC1: st ar t oui
cd C: \ t emp\ Pat chset _10204\ Di sk1>
set up. exe
Wel come
>Next

>sel ect Or acl e RAC Dat abase home
>Next
>Conf i r mnodes >Next
Or acl e Conf i gur at i on Manager
you can set up t he Or acl e Conf i gur at i on Manager
>Checki ng shoul d pass >Next
>Summar y
>I nst al l

>Exi t
11. Perform cluster database creation
# i n r ac1: f r omOr acl e Dat abase home ( not ASM)
c: \ or acl e/ pr oduct / 10. 2. 0/ db_2/ bi n\ dbca

Cr eat e Or acl e RAC Dat abase
' Next ' t o cont i nue

Oper at i ons
Sel ect Cr eat e a Dat abase.
' Next ' t o cont i nue.

Node
Sel ect al l t he nodes
' Next ' t o cont i nue.

Dat abase Templ at es
Sel ect t he r equi r ed t empl at e: l i ke " Gener al Pur pose"
' Next ' t o cont i nue.

Dat abase I dent i f i cat i on
Ent er r ac as t he gl obal dat abase name.
' Next ' t o cont i nue.

Management Opt i ons
Keep t he def aul t set t i ngs " Conf i gur e Dat abase Cont r ol f or Conf i gur e Ent er pr i se
Manager " sel ect ed,
Keep " Enabl e Al er t Not i f i cat i ons" and " Enabl e Dai l y Di sk Backup t o Recover y
Ar ea" desel ect ed.
' Next ' t o cont i nue
Page 458 Oracle DBA Code Examples


Dat abase Cr edent i al s
Sel ect Use t he same Admi ni st r at i ve Passwor d f or Al l Account s and ent er a
passwor d.
' Next ' t o cont i nue

St or age Opt i ons
Sel ect ASM f or st or age
' Next ' t o cont i nue

ASM Di sk Gr oups
Sel ect t he di sk gr oups dgdat a1
' Next ' t o cont i nue

Dat abase Fi l e Locat i ons
Keep t he def aul t Use Or acl e- Managed Fi l es.
Make sur e +DGDATA1 i s ent er ed as t he Dat abase Ar ea.
' Next ' t o cont i nue

Recover y Conf i gur at i on:
Sel ect Speci f y Fl ash Recover y Ar ea and ent er +DGFRA as t he Fl ash Recover y
Ar ea. Set i t s si ze.
Sel ect Enabl e ar chi vi ng and cl i ck on t he Edi t Ar chi ve Mode Par amet er s but t on
and make sur e t he Fl ash Recover y ar ea i s poi nt i ng t o +DGFRA
' OK' and t hen
' Next ' t o cont i nue.

Dat abase Cont ent
Sel ect Sampl e Schemas i f you want t o i nst al l t hem.
Cl i ck ' Next '

Dat abase Ser vi ces:
Cl i ck Add but t on and ent er Ser vi ce Name such as: hr ser v t hen cl i ck ' OK'
Make sur e i t ' s set t o ' Pr ef er r ed' i n bot h nodes and sel ect Basi c f or TAF.
Cl i ck ' Next '

I ni t i al i zat i on Par amet er s:
Memor y Si ze t o 70%. You can l eave al l ot her set t i ngs as i s.
' Next ' t o cont i nue

Dat abase St or age
Her e you can r evi ew t he pl acement of var i ous dat abase f i l es
' Next ' t o cont i nue

Cr eat i on Opt i ons
Sel ect Gener at e dat abase cr eat i on scr i pt s i f you want t o r evi ew t hese at a
l at er st age.
' Fi ni sh' t o r evi ew t he i nst al l at i on.

Summar y
Sel ect Ok t o cl ose t he r evi ew page and
' OK' t o st ar t t he i nst al l at i on.

Once dat abase cr eat i on i s done a summar y scr een wi l l be di spl ayed.
Copy t he OEM URL i nt o cl i pboar d. Save i t i n a f i l e or t he I nt er net Br owser
' Exi t ' t o exi t t he OUI .

Page 459 Oracle DBA Code Examples

12. Useful Postinstallation Steps
Following are tips to consider after the successful installation to make managing RAC
easier.
# Cr eat e l i nks t o Or acl e cr s and dat abase homes.
not epad C: \ WI NDOWS\ syst em32\ cr s. bat
cd / d C: \ or acl e\ pr oduct \ 10. 2. 0\ cr s\ BI N

not epad C: \ WI NDOWS\ syst em32\ db. bat
cd / d C: \ or acl e\ pr oduct \ 10. 2. 0\ db_2\ BI N

not epad C: \ WI NDOWS\ syst em32\ asm. bat
cd / d C: \ or acl e\ pr oduct \ 10. 2. 0\ db_1\ BI N

Page 460 Oracle DBA Code Examples

Cleaning Up Clusterware Installation on Windows
If clusterware installation fails, sometimes you need to clean up the installation and redo
the installation again. Following procedure just does that. The procedure applies on Oracle
10g R1, R2 and Oracle 11g R1.
1. St op t he f ol l owi ng ser vi ces on each node and set t hemt o Manual :
Or acl eCSSer vi ce
Or acl eCRSer vi ce
Or acl eEVMSer vi ce


2. To see t he l i nk names t hat have been assi gned t o, i nvoke t he Or acl e t ool
<CRS_HOME>\ bi n\ Gui Or acl eObj Manager . exe
I f you al r eady r emove t he CRS_Home, you can downl oad t he t ool s f r om:
- met al i nk I D: 341214. 1
- ht t p: / / www. ahmedbar aka. com/ or acl e/ cl eanup. zi p


3. I f you' r e usi ng RAWdi sks, i nvoke t he Or acl e t ool l ogpat f or mat . exe t o
r ei ni t i al i ze t he header s of t he di sks:
r un l ogpar t f or mat / q <l i nk name as shown i n gui or acl eobj manager t ool >
For exampl e: l ogpar t f or mat / q \ \ . \ ocr cf g
Repeat t hi s st ep f or al l l i nk names l i st ed i n gui or acl eobj manager )

4. I f you' r e usi ng OCFS:
navi gat e t o CRS_HOME\ bi n\
r un l ogpar t f or mat / q <DRI VELETTER>:
For exampl e: l ogpar t f or mat / q P:


5. Remove al l t he assi gned l i nk names usi ng t he GUI Or acl eobj manager . exe t ool
by cl i cki ng:
Pl aci ng a check mar k i n t he check box f or t he gi ven par t i t i on, t hen
choosi ng ' Commi t ' f r omt he ' Opt i ons' menu.


6. Remove and r ecr eat e your l ogi cal dr i ves on t op of ext ended par t i t i ons f r om
Wi ndows Di sk Management .


7. Use t he OUI t o r emove t he sof t war e f r omt he CRS home


8. Remove Or acl e bi nar i es usi ng Wi ndows expl or er , bot h t he CRS home and t he
f i l es l ocat ed i n: c: \ pr ogr amf i l es\ or acl e


9. Check t he r egi st r y on each node and ensur e t hat t he f ol l owi ng ser vi ces have
been r emoved f r om( r emove t hem, i f not ) :
HKEY_LOCAL_MACHI NE\ SYSTEM\ Cur r ent Cont r ol Set \ Ser vi ces
and
HKEY_LOCAL_MACHI NE\ SYSTEM\ Cont r ol Set XXX\ Ser vi ces

Ser vi ces t o be r emoved i ncl ude:
ocf s
Or acl eCSSer vi ce
Page 461 Oracle DBA Code Examples

Or acl eEVMSer vi ce
Or acl eCRSer vi ce
Or acl eObj ect Ser vi ce
Or acl eCl ust er Vol umeSer vi ce
Or aFenceSer vi ce


10. Usi ng Wi ndows expl or er , r emove t he f ol l owi ng dr i ver f i l es f r om:
%syst emr oot %\ wi ndows\ syst em32\ dr i ver s:
ocf s. sys
or af encedr v. sys
or af enceser vi ce. sys


11. Reboot al l ser ver s i n your RAC conf i gur at i on
Page 462 Oracle DBA Code Examples

Single Instance to RAC Conversion
The Tools to Convert a Single Instance DB to RAC
DBCA: enables moving from host that will not be part of the RAC
rconfig utility: the single instance db host will be part of the RAC
Enterprise Manager
Conversion Prerequisites for Oracle 10g R2
Oracle Clusterware 10g Release 2 (10.2) is installed, configured, and running.
Oracle Real Application Clusters 10g Release 2 (10.2) software is installed.
The Oracle binary is enabled for RAC.
Shared storage is available and accessible from all nodes.
User equivalence exists for the oracle user.
Using rconfig Utitlity
The example below applies on Oracle 10g R2.
Test r conf i g bef or e conver t i ng t o RAC
#make copy of $ORACLE_HOME/ assi st ant s/ r conf i g/ sampl eXMLs/ Conver t ToRAC. xml

su - or acl e
cd $ORACLE_HOME/ assi st ant s/ r conf i g/ sampl eXMLs/
cp Conver t ToRAC. xml Or a10gToRac. xml

#edi t t he f i l e: make changes as i nst r uct ed i n t he comment s
# make sur e t o set Conver t ver i f y = " ONLY"
# bel ow i s an exampl e f i l e:

xsi : schemaLocat i on=" ht t p: / / www. or acl e. com/ r conf i g" >
<n: Conver t ToRAC>
<! - - Ver i f y does a pr echeck t o ensur e al l pr e- r equi si t es ar e met , bef or e t he
conver si on i s at t empt ed. Al l owabl e val ues ar e: YES| NO| ONLY - - >
<n: Conver t ver i f y=" ONLY" >
<! - - Speci f y cur r ent Or acl eHome of non- r ac dat abase f or Sour ceDBHome - - >

<n: Sour ceDBHome>/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1</ n: Sour ceDBHome>
<! - - Speci f y Or acl eHome wher e t he r ac dat abase shoul d be conf i gur ed. I t can be
same as Sour ceDBHome - - >

<n: Tar get DBHome>/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1</ n: Tar get DBHome>
<! - - Speci f y SI D of non- r ac dat abase and cr edent i al . User wi t h sysdba r ol e i s
r equi r ed t o per f or mconver si on - - >
<n: Sour ceDBI nf o SI D=" or a10g" >
<n: Cr edent i al s>
<n: User >sys</ n: User >
<n: Passwor d>or a10g</ n: Passwor d>
<n: Rol e>sysdba</ n: Rol e>
</ n: Cr edent i al s>
Page 463 Oracle DBA Code Examples

</ n: Sour ceDBI nf o>
<! - - ASMI nf o el ement i s r equi r ed onl y i f t he cur r ent non- r ac dat abase uses ASM
St or age - - >
<n: ASMI nf o SI D=" +ASM1" >
<n: Cr edent i al s>
<n: User >sys</ n: User >
<n: Passwor d>wel come</ n: Passwor d>
<n: Rol e>sysdba</ n: Rol e>
</ n: Cr edent i al s>
</ n: ASMI nf o>
<! - - Speci f y t he l i st of nodes t hat shoul d have r ac i nst ances r unni ng.
Local Node shoul d be t he f i r st node i n t hi s nodel i st . - - >
<n: NodeLi st >
<n: Node name=" r ac1" / >
<n: Node name=" r ac2" / >
</ n: NodeLi st >
<! - - Speci f y pr ef i x f or r ac i nst ances. I t can be same as t he i nst ance name f or
non- r ac dat abase or di f f er ent . The i nst ance number wi l l be at t ached t o t hi s
pr ef i x. - - >
<n: I nst ancePr ef i x>r ac</ n: I nst ancePr ef i x>
<! - - Speci f y por t f or t he l i st ener t o be conf i gur ed f or r ac dat abase. I f
por t =" " , al i st ener exi st i ng on l ocal host wi l l be used f or r ac dat abase. The
l i st ener wi l l be ext ended t o al l nodes i n t he nodel i st - - >
<n: Li st ener por t =" " / >
<! - - Speci f y t he t ype of st or age t o be used by r ac dat abase. Al l owabl e val ues
ar e CFS| ASM. The non- r ac dat abase shoul d have same st or age t ype. - - >
<n: Shar edSt or age t ype=" ASM" >
<! - - Speci f y Dat abase Ar ea Locat i on t o be conf i gur ed f or r ac dat abase. I f t hi s
f i el d i s l ef t empt y, cur r ent st or age wi l l be used f or r ac dat abase. For CFS,
t hi s f i el d wi l l have di r ect or y pat h. - - >
<n: Tar get Dat abaseAr ea>+DG1</ n: Tar get Dat abaseAr ea>
<! - - Speci f y Fl ash Recover y Ar ea t o be conf i gur ed f or r ac dat abase. I f t hi s
f i el d i s l ef t empt y, cur r ent r ecover y ar ea of non- r ac dat abase wi l l be
conf i gur ed f or r ac dat abase. I f cur r ent dat abase i s not usi ng r ecover y Ar ea,
t he r esul t i ng r ac dat abase wi l l not have a r ecover y ar ea. - - >
<n: Tar get Fl ashRecover yAr ea>+DG2</ n: Tar get Fl ashRecover yAr ea>
</ n: Shar edSt or age>
</ n: Conver t >
</ n: Conver t ToRAC>
</ n: RConf i g>


# r un t he t ool f or t est i ng
r conf i g Or a10gToRac. xml
Using DBCA
The example below tested on an Oracle 10g R2 for Enterprise Linux x86 (version 4.5).
The DBCA:
o Automates the configuration of the control file attributes
o Creates the undo tablespaces and the redo logs
o Makes the initialization parameter file entries for cluster-enabled environments
o Configures Oracle Net Services, Oracle Clusterware resources, and the configuration for
RAC database management for use by Oracle Enterprise Manager or the SRVCTL utility.
Page 464 Oracle DBA Code Examples

# ( 1) Cr eat e a pr econf i gur ed i mage of your si ngl e- i nst ance dat abase
$ORACLE_HOME\ bi n\ DBCA

Wel come scr een
>Next

Oper at i ons scr een
>Manage Templ at es
>Next

Templ at e Management scr een
>sel ect " Cr eat e a dat abase" t empl at e
>" Fr oman exi st i ng dat abase ( st r uct ur e as wel l as dat a) , "
>Next

Sour ce Dat abase scr een,
>Sel ect t he dat abase name
>Next

On t he Templ at e Pr oper t i es scr een
>ent er a t empl at e name i n t he Name f i el d.
>ent er a descr i pt i on of t he f i l e i n t he Descr i pt i on f i el d
>change t he t empl at e f i l e l ocat i on i n t he Templ at e dat a f i l e f i el d i f you want
>Next

Locat i on of Dat abase Rel at ed Fi l es scr een
>" Mai nt ai n t he f i l e l ocat i ons, " so t hat you can r est or e t he dat abase t o t he
cur r ent di r ect or y st r uct ur e
>Fi ni sh
The DBCA gener at es t wo f i l es: a dat abase st r uct ur e f i l e ( t empl at e_name. dbc)
and a dat abase pr econf i gur ed i mage f i l e ( t empl at e_name. df b) .


#( 2) Copy t he pr econf i gur ed dat abase i mage t o node1
on r ac1 as or acl e
scp
or acl e@192. 168. 4. 21: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ assi st ant s/ dbca/ t empl a
t es/ Or a10gDB. * / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ assi st ant s/ dbca/ t empl at es


#( 3) Cr eat e t he RAC DB f r omt he suppl i ed t empl at e
I n r ac1, r un DBCA t o cr eat e a new dat abase.
On t he DBCA Templ at e Sel ect i on scr een, use t he t empl at e t hat you copi ed.
Compl et e t he i nst al l at i on.

Note: When I t est ed t hi s pr ocedur e, DBCA r et ur ns uncl ear TNS er r or . I l et t he
DBCA gener at e t he scr i t p but unf or t unat el y I t hen r eal i zed t hat t he gener at ed
scr i pt wi l l cr eat e a si ngl e i nst ance dat abase!

Page 465 Oracle DBA Code Examples

Administering RAC Database

Page 466 Oracle DBA Code Examples

Administering Oracle Clusterware Components
Managing Cluserware Daemons and Processes
Displaying Clusterware Processes
ps - ef | gr ep d. bi n
ps - ef | gr ep - E " opr o| r acgi mon| evmd| cr sd| ocssd" | gr ep - v gr ep
Starting, Stopping, Enabling and Disabling crs Stack
# as r oot

# pr event CRS f r omst ar t i ng on a r eboot
cr sct l di sabl e cr s

# st ar t cr s
cr sct l st ar t cr s

# enabl e CRS on r eboot :
cr sct l enabl e cr s

# di sabl e CRS on r eboot ( not st oppi ng cur r ent st ack) :
cr sct l di sabl e cr s

# st ar t cr s
cr sct l st op cr s
CSS Parameters
MISSCOUNT: Represents network heartbeat timeouts (600 s)
DISKTIMEOUT: Represents disk I/O timeouts outside reconfiguration (200 s). Should
always be less than I/O latency otherwise crs may trigger node eviction.
# t o set di skt i meout :
1. Shut down Or acl e Cl ust er war e on al l nodes but one.
2. As r oot on avai l abl e node, use ( wher e M i s t he I / O l at ency) :
cr sct l get css di skt i meout
cr sct l set css di skt i meout M+1
3. Reboot avai l abl e node.
4. Rest ar t al l ot her nodes.

# t o set mi sscount
# same as above except :
cr sct l set css mi sscount 300
Administering Voting Disks in RAC
Multiplexing Voting Disks
Use one voting disk if it is stored on a reliable disk.
Multiplexed copies should be stored on independent devices.
Page 467 Oracle DBA Code Examples

Use at least three multiplexed copies.
A typical voting disk configuration comprises between three and five disks.
Dynamically Adding and Removing Voting Disks after Installing RAC
Recommendation is to use symbolic links
# i f you have mul t i pl e vot i ng di sks, you can add and r emove vot i ng di sks
su -
cr sct l del et e css vot edi sk / dev/ r aw/ r aw2
cr sct l add css vot edi sk / dev/ r aw/ r aw3

# i f t he command doesn' t wor k onl i ne:
su -
# i n al l nodes
cr sct l st op cr s
cr sct l add css vot edi sk / dev/ r aw/ r aw3 - f or ce
# i n al l nodes
cr sct l st ar t cr s
Backing up Voting Disks
Do it when you add or remove a node.
Perform it on every voting disk.
# Back up t he vot i ng di sk ( can be onl i ne)
# usual l y 4K bl ock si ze i s OK
su -
# t o l i st vot i ng di sks cur r ent l y used
cr sct l quer y css vot edi sk
# backup
dd i f =/ dev/ r aw/ r aw2 of =~/ vdi sk. bak bs=4k

# on Wi ndows use ocopy
Recovering Voting Disks
# r ecover yi ng vot i ng di sk
dd i f =~/ vdi sk. bak of =/ dev/ r aw/ r aw2

# i f you have mul t i pl e vot i ng di sks,
# you can add ( mul t i pl ex) and r emove vot i ng di sks
su -
cr sct l del et e css vot edi sk / dev/ r aw/ r aw2
cr sct l add css vot edi sk / dev/ r aw/ r aw2
Administering the Oracle Cluster Registry (OCR)
RAC environments do not support more than two OCRs (OCR and its mirror)
Using mirrored OCR is optional but recommended when not stored on RAID storage.
Note: The ocrconfig command cannot modify OCR configuration information for nodes that
are shut down or for nodes on which the Oracle Clusterware is not running.
Page 468 Oracle DBA Code Examples

Replacing the OCR
If you receive from ocrcheck the message: "Devi ce/ Fi l e needs t o be synchr oni zed
wi t h t he ot her devi ce", it means OCR mirror is out of sync with the primary OCR. In
this case, replace or relocate your failing OCR with a copy of the other healthy OCR.
If it is the primary OCR file that is failing, and if your OCR mirror is still in good health, you
can use the ocrconfig replace ocr <ocrfilename>
Executing ocrconfig replace ocr|ocrmirror filename adds the primary or mirror OCR file to
your environment if it does not already exist.
Executing ocrconfig replace ocr|ocrmirror removes the primary or the mirror OCR.
If you remove a primary OCR file, the mirror OCR file becomes primary.
# 1) ver i f y t he ot her OCR i s onl i ne
# 2) ver i f y cr s i s r unni ng i n t he node you ar e usi ng t o r epl ace OCR
cr sct l check cr s
cr s_st at - t
# 3) r un one of t he f ol l owi ng
ocr conf i g - r epl ace ocr / dev/ r aw/ r aw5
ocr conf i g - r epl ace ocr mi r r or / dev/ r aw/ r aw6
# 4) I n any node t hat i s st opped i n your RAC
ocr conf i g - r epai r ocr mi r r or / dev/ r aw/ r aw2
Adding and Removing the OCR
# Addi ng an Or acl e Cl ust er Regi st r y
ocr conf i g - r epl ace ocr / dev/ r aw/ r aw5
ocr conf i g - r epl ace ocr mi r r or / dev/ r aw/ r aw6

# Removi ng an Or acl e Cl ust er Regi st r y
# I f you r emove a pr i mar y OCR, t hen t he mi r r or ed OCR becomes t he pr i mar y OCR
# t o r emove t he ocr
ocrconfig -replace ocr
# t o r emove t he mi r r or ed
ocrconfig -replace ocrmirror
Repairing the OCR
You may need to repair an OCR configuration on a particular node if your OCR
configuration changes while that node is stopped.
The OCR configuration information is stored in:
/etc/oracle/ocr.loc on Linux and AIX
/var/opt/oracle/ocr.loc on Solaris and HP-UX
Registry key HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ocr on Windows
# Repar i ng an OCR ( r epai r s onl y t he ocr conf i gur at i on i nf o, not i t s i t egr i t y)
# 1. t he cr s must be st opped
su -
cr sct l st op cr s
# 2. r epai r
ocr conf i g - r epai r ocr mi r r or / dev/ r aw/ r aw2
# 3. st ar t cr s
cr sct l st ar t cr s
Making Physical Backups of the OCR
Create manually copies of the automatically generated physical backups on daily basis.
Export the OCR contents before and after making significant configuration changes such as
adding or deleting nodes from your environment, modifying Oracle Clusterware resources,
or creating a database.
Page 469 Oracle DBA Code Examples

Do not perform an OCR restore as a correction to revert to previous configurations if some
of these configuration changes fail.
# backup OCR
# backup t he backups t hat ar e aut omat i cal l y gener at ed i n ( ever y 4 hr s )
$CRS_HOME/ cdat a/ CLUSTER_NAME
# t he def aul t di r ect or y can be obt ai ned:
ocr conf i g - showbackup

# i t i s a good i dea t o set t he aut o- backup di r ect or y t o a shar ed st or age:
ocr conf i g backupl oc / shar ed/ bak
Recovering the OCR using the Physical Backups
# make r ecover y onl y when you ar e sur e t her e i s an er r or i n t he
# ocr . use ocr check t o check t he ocr
# i n unix:
# 1. I dent i f y t he OCR backups t hen r evi ew t he cont ent s of t he backup
# backups done t i mi ngs
ocr conf i g - showbackup
l s - l t / u01/ cr s/ cdat a/ cr s/
. / ocr dump - backupf i l e / u01/ cr s/ cdat a/ cr s/ backup00. ocr
l ess OCRDUMPFI LE
# 2. St op t he Or acl e Cl ust er war e sof t war e on ALL Nodes
su -
cr sct l st op cr s
# 3. Make sur e t hat t he OCR devi ces t hat you speci f y i n t he OCR conf i gur at i on
f i l e ( / et c/ or acl e/ ocr . l oc) exi st . Rest or e f r oman OCR backup f i l e f r omSt ep 1:
ocr conf i g - r est or e / u01/ cr s/ cdat a/ cr s/ backup00. ocr
# 4. Rest ar t t he Or acl e Cl ust er war e on al l of t he nodes
su -
cr sct l st ar t cr s
# 5. Ver i f y t he OCR i nt egr i t y
cl uvf y comp ocr - n al l [ - ver bose]

# in Windows
# 1. I dent i f y t he OCR backups usi ng t he
ocr conf i g - showbackup
ocr dump - backupf i l e <f i l e_name>
# 2. On al l of t he r emai ni ng nodes, di sabl e t he f ol l owi ng OCR cl i ent s:
Or acl eCl ust er Vol umeSer vi ce, Or acl eCSSer vi ce, Or acl eCRSer vi ce, and t he
Or acl eEVMSer vi ce
# 3. Appl y t he OCR backup f i l e f r omSt ep 1
ocr conf i g - r est or e c: \ or acl e\ cr s\ cdat a\ cr s\ backup00. ocr
# 4. St ar t al l of t he ser vi ces t hat wer e st opped i n st ep 2. Rest ar t al l of t he
nodes and r esume oper at i ons i n cl ust er mode.
# 5. Ver i f y t he OCR i nt egr i t y wher e t he - n al l
cl uvf y comp ocr - n al l [ - ver bose]
Making Logical Backups of the OCR (Exporting)
Export the OCR contents before and after making significant configuration changes, such
as adding or deleting nodes from your environment, modifying OracleClusterware
resources, or creating a database.
# t o expor t OCR cont ent s ( out put f i l e i s a bi nar y not - t o- edi t f i l e)
ocr conf i g expor t / u01/ ocr backup/ ocr . bak
Making Logical Backups of the OCR (Importing)
# i n Uni x
# 1. I dent i f y t he OCR expor t f i l e t hat you want t o i mpor t
# 2. St op Or acl e Cl ust er war e on al l t he nodes i n your RAC dat abase
Page 470 Oracle DBA Code Examples

su -
cr sct l st op cr s
# 3. I mpor t t he f i l e
ocr conf i g - i mpor t f i l e_name
# 4. Rest ar t Or acl e Cl ust er war e on al l t he nodes
su -
cr sct l st ar t cr s
# 5. ver i f y OCR i nt egr i t y
cl uvf y comp ocr - n al l

# I mpor t i n Wi ndows
1. I dent i f y t he OCR expor t f i l e
2. St op t he f ol l owi ng OCR cl i ent s on each node:
Or acl eCl ust er Vol umeSer vi ce, Or acl eCMSer vi ce, Or acl eEVMSer vi ce,
Or acl eCSSer vi ce, and t he Or acl eCRSer vi ce.
3. I mpor t t he OCR expor t f i l e
ocr conf i g - i mpor t ocr expor t . dat
4. Rest ar t al l of t he af f ect ed ser vi ces on al l nodes.
5. Ver i f y t he OCR i nt egr i t y wher e node_l i st i s a l i st of al l of t he nodes:
cl uvf y comp ocr - n al l [ - ver bose]
Diagnosing OCR Problems with the OCRDUMP and OCRCHECK Utilities
OCRDUMP view OCR contents in a readable format.
l s - l t / u01/ cr s/ cdat a/ cr s/
. / ocr dump - backupf i l e / u01/ cr s/ cdat a/ cr s/ backup00. ocr
l ess OCRDUMPFI LE

. / ocr dump dumpout put - backupf i l e / u01/ cr s/ cdat a/ cr s/ backup00. ocr
. / ocr dump - st dout - backupf i l e / u01/ cr s/ cdat a/ cr s/ backup00. ocr - xml

# checks l ogs ar e r epor t ed i n CRS_Home/ l og/ host name/ cl i ent
. / ocr check
Page 471 Oracle DBA Code Examples

Administering Storage
Datafile Access in Real Application Clusters
Redo Log File Storage in Real Application Clusters
Each instance has its own online redo log groups which are referred to as an instance's
thread of online redo.
/ * i nst ance Thr ead */
- - t hr ead i s uni que t o ever y node
sel ect val ue f r omv$par amet er wher e name=' t hr ead' ;

- - I f you change t he t hr ead of an i nst ance, i t won' t
- - t ake ef f ect t i l l you enabl e i t ( ot her wi se db r est ar t wi l l f ai l ) :
ALTER DATABASE ENABLE THREAD 3;

- - f ol l owi ng commands r emove t hr ead 3 and r epl ace i t wi t h t hr ead 2
ALTER SYSTEM SET t hr ead = 2 SCOPE=SPFI LE SI D=' r ac2' ;
/ u01/ cr s11g/ bi n/ sr vct l st op i nst ance - d r ac - i r ac2
/ u01/ cr s11g/ bi n/ sr vct l st ar t i nst ance - d r ac - i r ac2
connect / as sysdba
al t er dat abase di sabl e t hr ead 3;

- - ever y t hr ead has at l east t wo gr oups
sel ect t hr ead#, gr oup#, member s, byt es/ 1024/ 1024 MB, st at us f r omv$l og or der
by t hr ead#, gr oup#;
sel ect gr oup#, member , st at us f r omv$l ogf i l e or der by gr oup#;


/ * t o add a r edo l og gr oup */
- - i f OMF or ASM i s used
ALTER DATABASE ADD LOGFI LE THREAD 1 GROUP 5 SI ZE 50M;
ALTER DATABASE ADD LOGFI LE THREAD 2 GROUP 6 SI ZE 50M;
- - or
al t er dat abase add l ogf i l e t hr ead 2
gr oup 5 ( ' / . . / _g5_m1. dbf ' , ' / . . / _g5_m2. dbf ' ) SI ZE 128M REUSE,
gr oup 6 ( ' / . . / _g6_m1. dbf ' , ' / . . / _g6_m2. dbf ' ) SI ZE 128M REUSE,
gr oup 7 ( ' / . . / _g7_m1. dbf ' , ' / . . / _g7_m2. dbf ' ) SI ZE 128M REUSE,
gr oup 8 ( ' / . . / _g8_m1. dbf ' , ' / . . / _g8_m2. dbf ' ) SI ZE 128M REUSE;

/ * t o dr op a gr oup */
- - make sur e i t s i nact i ve
sel ect t hr ead#, gr oup#, member s, byt es/ 1024/ 1024 MB, st at us f r omv$l og or der
by t hr ead#, gr oup#;
- - swi t ch l og i f r equi r ed
al t er syst emswi t ch l ogl i f e;
- - st ar t ar chi vi ng, i f r equi r ed: speci f i c i nst ance
al t er syst emar chi ve l og i nst ance ' r ac1' next ;
- - dr op t he gr oup
ALTER DATABASE DROP LOGFI LE GROUP 5;
ALTER DATABASE DROP LOGFI LE GROUP 6;
Automatic Undo Management in Real Application Clusters
# di spl ay undo t abl espace used by t he SI D
SELECT VALUE FROM V$PARAMETER WHERE UPPER( NAME) i n
Page 472 Oracle DBA Code Examples

( ' UNDO_TABLESPACE' , ' I NSTANCE_NAME' ) ;

# change undo t abl espace f or an i nst ance
ALTER SYSTEM SET UNDO_TABLESPACE =' UNDORAC2' SI D=' r ac2' ;
Administering ASM Instances with SRVCTL in RAC
# t o st ar t , st op, and obt ai n t he st at us of an ASM i nst ance
sr vct l st ar t asm- n node_name [ - i asm_i nst nace_name] [ - o st ar t _opt i ons] [ - c
<connect _st r > | - q]
sr vct l st op asm- n node_name [ - i asm_i nst ance_name] [ - o st op_opt i ons] [ - c
<connect _st r > | - q]
sr vct l conf i g asm- n node_name
sr vct l st at us asm- n node_name

# t o add conf i gur at i on i nf or mat i on about an exi st i ng ASM i nst ance:
sr vct l add asm- n node_name - i asm_i nst ance_name - o or acl e_home

# t o r emove an ASM i nst ance:
sr vct l r emove asm- n node_name [ - i asm_i nst ance_name]

# t o enabl e an ASM i nst ance:
sr vct l enabl e asm- n node_name [ - i ] asm_i nst ance_name

# t o di sabl e an ASM i nst ance:
sr vct l di sabl e asm- n node_name [ - i asm_i nst ance_name]

Page 473 Oracle DBA Code Examples

Administering Cluster Databases
Displaying Current Instance in SQL*Plus Prompt
# i n l ogi n. sql f i l e ( usual l y i n $ORACLE_HOME/ bi n) add:
SET SQLPROMPT ' _USER@_CONNECT_I DENTI FI ER> '
Starting and Stopping Instances and RAC Databases
Starting Up and Shutting Down with SQL*Plus
- - on an i nst ance on your l ocal node
echo $ORACLE_SI D
CONNECT / AS SYSDBA
SELECT VALUE FROM V$PARAMETER WHERE UPPER( NAME) =' I NSTANCE_NAME' ;
- - t he f ol l owi ng command wi l l wai t f or al l t r ans i n t he db
SHUTDOWN TRANSACTI ONAL
- - t he f ol l owi ng command wi l l wai t f or t he t r ans i n t he connect ed node onl y
SHUTDOWN TRANSACTI ONAL LOCAL
- - connect ed i nst ance wi l l shut down
STARTUP MOUNT

- - or
CONNECT / @db1 AS SYSDBA
. .
Intermittent Windows Shutdown Issue in RAC Environments
Normal Windows shutdown may hange, if the instance was shutdown using SQL*Plus. To
avoid it, shutdown the following using SRVCTL:
All services on the node.
All database instances on the node.
All ASM instances on the node.
All node applications on the node.
Starting Up and Shutting Down with SRVCTL
Shutting down a database means shutting down all its instances.
# speci f i c i nst ance( s)
# pr ef er r ed and avai l abl e ser vi ces wi l l al so be st ar t ed al ongsi de
sr vct l st ar t i nst ance - d db_name - i " i nst _name_l i st " [ - o st ar t _opt i ons]
sr vct l st op i nst ance - d name - i " i nst _name_l i st " [ - o st op_opt i ons]
sr vct l st op i nst ance - d r ac - i " r ac1, r ac2" - o i mmedi at e

# ent i r e cl ust er dat abase
# when you st ar t , onl y non- r unni ng i nst ances wi l l be st ar t ed
sr vct l st ar t dat abase - d name [ - o st ar t _opt i ons]
sr vct l st ar t dat abase - d r ac - o mount
sr vct l st op dat abase - d name [ - o st op_opt i ons]
Page 474 Oracle DBA Code Examples

Customizing How Oracle Clusterware Manages RAC Databases
You may want to:
prevent the Oracle Clusterware from restarting your RAC database when you restart the
system
avoid restarting failed instances more than once
# when you make a ser vi ce unavai l abl e, i t won' t r un under t he Or acl e cr s
# f or aut omat i c st ar t up, f ai l over , or r est ar t
sr vct l di sabl e dat abase - d r ac
sr vct l di sabl e i nst ance - d r ac - i " r ac1, r ac2"
sr vct l di sabl e ser vi ce - d r ac - s hr ser v, mar ket i ng
# - n node name
sr vct l di sabl e asm- n cr mnode1 - i asm1
Switching Between the Database Automatic and Manual Policies
When AUTO_START attribute is set to 2 (MANUAL) for a resource, crs will not automatically
start it on reboot.
# t o di spl ay t he cur r ent pol i cy
sr vct l conf i g dat abase - d r ac - a
. .
POLI CY: AUTOMATI C

# change t he cur r ent pol i cy t o anot her one
sr vct l modi f y dat abase d dat abase_name - y AUTOMATI C| MANUAL
Customizing Resource Parameters (like AUTO_START)
You can customize the following resource parameters for database or ASM instances,
databases, services, and service members:
# when 1 (0), it atuo-restarts on system reboot
AUTO_START as
# restart attempts before relocate (1)
RESTART_ATTEMPTS ra
# application up-time to be considered stable by crs
UPTIME_THRESHOLD ut
# 1. r et r ei ve r esour ce name
cr s_st at t

# 2. updat e t he OCR wi t h t he r i ght at t r i but e val ues f or your r esour ces
cr s_r egi st er or a. . i nst - updat e - o as=2, r a=1, ut =7d
cr s_r egi st er or a. . asm- updat e - o as=2, r a=1, ut =7d
cr s_r egi st er or a. . db - updat e - o as=2, r a=1, ut =7d
cr s_r egi st er or a. . cs - updat e - o as=2, r a=0
cr s_r egi st er or a. . svr - updat e - o as=2, r a=0
Page 475 Oracle DBA Code Examples

Handling Initialization Parameter Files in RAC
Setting Server Parameter File Parameter Values for Real Application Clusters
Practically, each instance uses its own PFILE file that contains only one parameter called
SPFILE. The SPFILE parameter points to the shared SPFILE on your shared storage.
/ * about t he par amet er s i n spf i l e i n RAC */
# t o know wheat her spf i l e or pf i l e was used when st ar t up
SELECT DECODE( val ue, NULL, ' PFI LE' , ' SPFI LE: ' | | val ue) " I ni t Fi l e Type"
FROM sys. v_$par amet er WHERE name = ' spf i l e' ;

- - spf i l e i s shar ed by al l i nst ances
cat $ORACLE_HOME/ dbs/ i ni t r ac1. or a
SPFI LE=' +DG1/ r ac/ spf i l er ac. or a'

- - exampl e
ALTER SYSTEM SET OPEN_CURSORS=500
COMMENT=' Changed by Ahmed f or t est i ng on 16- dec- 09'
SCOPE=BOTH
SI D=' *' ;
ALTER SYSTEM SET OPEN_CURSORS=1000 SPFI LE=BOTH SI D=' r ac1' ;

- - t o r emove a par amt er f r omspi f l e
ALTER SYSTEM RESET t i med_st at i st i cs SCOPE=SPFI LE SI D=' *' ;
ALTER SYSTEM SET t i med_st at i st i cs = ' ' SCOPE=SPFI LE;
Parameters Used in RAC Databases
CLUSTER_DATABASE must be TRUE
CLUSTER_DATABASE_I NSTANCES
CLUSTER_I NTERCONNECTS
DB_NAME
DI SPATCHERS
I NSTANCE_NAME
SERVI CE_NAMES
SESSI ONS_PER_USER If SESSIONS_PER_USER is set to 1 for a user, the user can log on to the
database more than once as long as each connection is from a different instance.
THREAD
SPFI LE
MAX_COMMI T_PROPAGATI ON_DELAY deprecated in 10g R2
Parameters that Must Have Identical Settings on All Instances
ACTI VE_I NSTANCE_COUNT
ARCHI VE_LAG_TARGET
CLUSTER_DATABASE
CLUSTER_DATABASE_I NSTANCES number of instances in the RAC
CONTROL_FI LES
DB_BLOCK_SI ZE
DB_DOMAI N
DB_FI LES
DB_NAME
DB_RECOVERY_FI LE_DEST
DB_RECOVERY_FI LE_DEST_SI ZE
Page 476 Oracle DBA Code Examples

DB_UNI QUE_NAME
UNDO_MANAGEMENT
Parameters That Must Have Unique Settings on All Instances
THREAD
ROLLBACK_SEGMENTS
UNDO_TABLESPACE if automatic is used
Parameters that Should Have Identical Settings on All Instances
It is highly recommended to set same value for parameters in the following list in all the
instances:
ARCHI VE_LAG_TARGET
LI CENSE_MAX_USERS
LOG_ARCHI VE_FORMAT
SPFI LE
TRACE_ENABLED
UNDO_RETENTI ON
ASM Instance Initialization Parameters and RAC
CLUSTER_DATABASE must be TRUE
ASM_DI SKSTRI NG Multiple instances can have different values (not recommended)
ASM_POWER_LIMIT Multiple instances can have different values
expor t ORACLE_SI D=+ASM1

sql pl us / nol og
conn / as sysdba

sel ect name, val ue
f r omv$par amet er
wher e upper ( name) i n ( ' CLUSTER_DATABASE' , ' ASM_DI SKSTRI NG' , ' ASM_POWER_LI MI T' ) ;
Dropping a RAC Database
Option 1: After making sure the crs and the database are up and running, issue dbca and
delete the database.
Option 2: issue the commands below:
st ar t up mount excl usi ve r est r i ct ;
dr op dat abase;
# t o del et e ar chi ved l og and t he backups as wel l
dr op dat abase i ncl udi ng backups;

sr vct l r emove i nst ance - d r ac - i r ac1
sr vct l r emove dat abase - d r ac

Page 477 Oracle DBA Code Examples

Workload Management in RAC
Types of Workload Distribution
Connection load balancing:
o Client-side connect-time load balancing
o Client-side connect-time failover
o Server-side connect-time load balancing
Run-time connection load balancing can be implemented by using connection pools in
middle tier.
Connection Load Balancing
Client-Side Load Balancing and Failover
If you use connect-time failover, do not set GLOBAL_DBNAME in the listener.ora
# t o enabl e Cl i ent - Si de Load Bal anci ng ONLY ( i . e. , no f ai l over ) : send r equest
# r andoml y t o one l i st ener f r omt he l i st .
CSLB_ONLY =
( DESCRI PTI ON =
(LOAD_BALANCE = ON)
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac1- vi p) ( PORT = 1521) )
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac2- vi p) ( PORT = 1521) )
( CONNECT_DATA =
( SERVER = DEDI CATED)
( SERVI CE_NAME = r acdb)
)
)

# use t hi s set t i ngs f or RAC dat abase
# t o enabl e f ai l over ( usi ng TCP/ I P t i me- out , t he cl i ent make sur e t he host i s
# al i ve bef or e sendi ng connect i on r equr est ) ( i n RAC, you use vi p addr esses)
CSLB_ONLY =
( DESCRI PTI ON =
(LOAD_BALANCE = ON)
(FAILOVER = ON)
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac1- vi p) ( PORT = 1521) )
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac2- vi p) ( PORT = 1521) )
( CONNECT_DATA =
( SERVER = DEDI CATED)
( SERVI CE_NAME = r acdb)
)
)

Server-Side Load Balancing
Target: which listener should take the connection.
- - Conf i gur i ng Ser ver - si de connect i on l oad bal anci ng
- - 1) def i ne t he ser vi ce whi ch wi l l be used f or t he connect i on l oad bal anci ng
- - 2) Add ent r i es i n ever y cl i ent ' s TNSNAMES. ORA f i l e f or t he new al i as
Page 478 Oracle DBA Code Examples

HRSERV =
( DESCRI PTI ON =
( ADDRESS_LI ST =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac1- vi p. mydomai n. com) ( PORT = 1521) )
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac2- vi p. mydomai n. com) ( PORT = 1521) )
)
( LOAD_BALANCE = ON) - - not r el at ed t o ser ver - si de l oad bal anci ng
( FAI LOVER = ON) - - not r el at ed t o ser ver - si de l oad bal anci ng
( CONNECT_DATA =
( SERVI CE_NAME = hrserv)
)
)
- - 3) Add ent r i es i n t he TNSNAMES. ORA f i l e of ever y node t o
- - i ncl ude t he REMOTE_LI STENER set t i ng
LISTENERS_RAC =
( ADDRESS_LI ST =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac1- vi p. mydomai n. com) ( PORT =
1521) )
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac2- vi p. mydomai n. com) ( PORT =
1521) )
)
- - 4) set t he par amet er t o make PMON aut omat i cal l y r egi st er t he dat abase
- - wi t h al l t he l i st ener s i n t he nodes
ALTER SYSTEM SET REMOTE_LISTENER =LI STENERS_RAC SI D=' *' SCOPE=BOTH;


- - set t i ng t he def aul t connect i on l oad bal anci ng goal f or t he ser vi ce hr ser v
- - t o LONG ( l ong- l i ved apps l i ke f or ms) ( def aul t ) , SHORT ( shor t - l i ved apps)
execut e dbms_ser vi ce. modi f y_ser vi ce ( ser vi ce_name => ' hr ser v' , cl b_goal =>
dbms_ser vi ce. cl b_goal _l ong) ;
execut e dbms_ser vi ce. modi f y_ser vi ce ( ser vi ce_name => ' hr ser v' , cl b_goal =>
dbms_ser vi ce. cl b_goal _shor t ) ;

- - vi ew i t ( name i s case sensi t i ve)
SELECT CLB_GOAL FROM DBA_SERVI CES WHERE NAME=' hr ser v' ;
Fast Application Notification (FAN)
FAN publishing load balancing advisory events and UP and DOWN info about services,
instances and nodes to client applicaitons.
You can take advantage of FAN events in the following three ways:
1. Application can take advantage of FAN without any programmatic changes by utilizing
an integrated Oracle Client like: Oracle Database 10g JDBC, ODP.NET, and OCI.
2. Applications can take advantage of FAN programmatically by using the Oracle
Notification Service (ONS) Application Programming Interface (API) to subscribe to
FAN events and execute event handling actions upon the receipt of an event.
3. You can implement FAN with server side callouts on your database tier.
Using Fast Application Notification Callouts
FAN callouts are server side executables that RAC executes immediately when high
availability events occur.
Page 479 Oracle DBA Code Examples

# pl ace an execut abl e i n t he di r ect or y CRS_home/ r acg/ usr co i n al l nodes
vi / u01/ cr s/ r acg/ usr co/ cal l out . sh
#! / bi n/ ksh
FAN_LOGFI LE=/ home/ or acl e/ l og/ r ac_`host name`. l og
echo $* " r epor t ed=" `dat e` >> $FAN_LOGFI LE &

# pl ace an execut abl e i n t he di r ect or y CRS_home/ r acg/ usr co i n al l nodes
# exampl e sour ce i s Or acl e Document at i on 10g R1
vi / u01/ cr s/ r acg/ usr co/ cal l out . sh
#! / usr / bi n/ sh#

# Descr i pt i on: wr apper scr i pt t o enabl e RAC event l oggi ng and not i f i cat i on
# t o gener i c t hi r d- par t y syst ems. The scr i pt showcases t wo possi bl e
# met hods t o enabl e l ocal or r emot e l oggi ng/ not i f i cat i on of RAC-
# det ect ed event s. #

AWK=/ usr / bi n/ awk
MY_CRS_HOME=/ pr i vat e/ or acl e/ cr s

# Scan and par se ar gl i st : #
f or ARGS i n $*; do
PROPERTY=`echo $ARGS | $AWK - F" =" ' {pr i nt $1}' `
VALUE=`echo $ARGS | $AWK - F" =" ' {pr i nt $2}' `

#> map EVTTYPE t o EVENT_TYP, NODE t o HOST:
case $PROPERTY i n
#> EVENT_TYP i s one of : NODE, DATABASE, I NSTANCE, SERVI CE, SERVI CEMEMBER
EVENT_TYP | event _t yp) NOTI FY_EVENT_TYP=$VALUE ; ;
VERSI ON | ver si on) NOTI FY_VERSI ON=$VALUE ; ;
SERVI CE | ser vi ce) NOTI FY_SERVI CE=$VALUE ; ;
DATABASE | dat abase) NOTI FY_DBNAME=$VALUE ; ;
I NSTANCE | i nst ance) NOTI FY_I NSTANCE=$VALUE ; ;
HOST | host ) NOTI FY_HOST=$VALUE ; ;
STATUS | st at us) NOTI FY_STATUS=$VALUE ; ;
TI MESTAMP | t i mest amp) NOTI FY_SVRLOGDATE=$VALUE ; ;
esac
done


# ###################################################
# [ 1] Not i f i cat i on Met hod 1: On- cl ust er f i l e l oggi ng
# ###################################################
# Thi s sect i on si mpl y wr i t es one- l i ne ent r i es f or each event publ i shed by RAC,
# and t he l og i s wr i t t en t o st andar d RAC l og di r ect or y. I t wi l l bl i ndl y
# r ecor d al l RAC event s, r egar dl ess of st at e ( UP, DOWN or NOT_RESTARTI NG) :

RACEVT_LOGFI LE=$MY_CRS_HOME/ r acg/ l og/ r ac_${NOTI FY_SERVI CE}_upt i me. l og

echo RAC\ ( v$NOTI FY_VERSI ON\ ) : $NOTI FY_STATUS event , t ype " $NOTI FY_EVENT_TYP" ,
\
`i f [ - n " $NOTI FY_SERVI CE" ] ; t hen \
echo " f or ser vi ce $NOTI FY_SERVI CE"
f i ` \
\ [ `i f [ - n " $NOTI FY_I NSTANCE" ] ; t hen \
echo " i nst : $NOTI FY_I NSTANCE"
f i ` \
`i f [ - n " $NOTI FY_DATABASE" ] ; t hen \
echo " db: $NOTI FY_DATABASE"
f i ` \
`i f [ - n " $NOTI FY_HOST" ] ; t hen \
echo " db: $NOTI FY_HOST"
f i ` \
Page 480 Oracle DBA Code Examples

\ ] r ecei ved on $NOTI FY_SVRLOGDATE >> $RACEVT_LOGFI LE



# ########################################################
# [ 2] Not i f i cat i on Met hod 2: On- cl ust er pr ogr amexecut i on
# ########################################################
# Let ' s assume you have a cust omcl i ent pr ogr ami n / t mp ( say l ogTi cket )
# t o whi ch you can pass cer t ai n ar gument s. Thi s pr ogr amconnect s t o a
# cust omer - ser vi ce appl i cat i on t hat pr ocesses i nci dent t i cket s f or your
# I T depar t ment :
# %/ t mp/ l ogTi cket {ser ver si de_t i mest amp} \
# {dat abasename} {ser vi cename} \
# {i nst ancename} {host name}#

# Let us al so assume t hat a t i cket woul d be l ogged onl y f or NOT_RESTARTI NG
# event s, as t hey ar e t he ones t hat exceeded RAC- moni t or ed t i meout s and
# ser i ousl y need human i nt er vent i on f or f ul l r esol ut i on. #

# - - - - - - - - - - - - - - - - - - -
# ONE SOLUTI ON TO [ 2] :
# - - - - - - - - - - - - - - - - - - -
i f [ $NOTI FY_STATUS = " NOT_RESTARTI NG" - o $NOTI FY_STATUS = " not _r est ar t i ng"
] ; t hen
/ t mp/ l ogTi cket $NOTI FY_SVRLOGDATE $NOTI FY_DBNAME \
$NOTI FY_SERVI CE \
$NOTI FY_I NSTANCE $NOTI FY_HOST >> $RACEVT_LOGFI LE
f i
Configuring the Server-Side ONS
When useocr=on in ons.config, racgons add_config command store this data in OCR.
# t ar get : t o add r ac3 node i n t he RAC ONS
# ( 1) obt ai n t he r emot e nodes f r omr ac1, r ac2
# and set useocr =on
cat $CRS_HOME/ opmn/ conf / ons. conf i g

# ( 2) i n r ac3:
r acgons add_conf i g r ac1: 6200 r ac2: 6200
r acgons add_conf i g r ac3: 6200

# ( 3) i n r ac1, r ac2:
onsct l r econf i g
Administering Load Balancing Advisory
The load balancing advisory has the task of advising the direction of incoming work to the
RAC instances that provide optimal quality of service for that work.
To test the load balancing, you can use the scripts in the appendix to apply load and the
following section for monitoring.
- - vi ew l oad bal anci ng gaol of a cur r ent ser vi ce
- - NONE means l oad bal anci ng advi sor y i s di sabl ed
SELECT NAME, GOAL, CLB_GOAL FROM DBA_SERVI CES;

- - SERVI CE TI ME: r esponse- t i me based, l i ke onl i ne shoppi ng
Page 481 Oracle DBA Code Examples

execut e dbms_ser vi ce. modi f y_ser vi ce ( ser vi ce_name => ' hr ser v' -
, goal => dbms_ser vi ce. goal_service_time -
, cl b_goal => dbms_ser vi ce. cl b_goal _shor t ) ;
- - THROUGHPUT: r at at whi ch j obs ar e compl et ed, l i ke bat ch pr ocessi ng
execut e dbms_ser vi ce. modi f y_ser vi ce ( ser vi ce_name => ' hr ser v' -
, goal => dbms_ser vi ce. goal_throughput -
, cl b_goal => dbms_ser vi ce. cl b_goal _l ong) ;
- - NONE: LBA di sabl ed
execut e dbms_ser vi ce. modi f y_ser vi ce ( ser vi ce_name => ' hr ser v' -
, goal => dbms_ser vi ce. goal_none -
, cl b_goal => dbms_ser vi ce. cl b_goal _l ong) ;
Monitoring Load Balancing Advisory
V$SERVICEMETRIC : service metrics on the most 5-second and 1-minute intervals
V$SERVICEMETRIC_HISTORY : recent history of the metric values
SELECT
ser vi ce_name
, TO_CHAR( begi n_t i me, ' hh24: mi : ss' ) beg_hi st
, TO_CHAR( end_t i me, ' hh24: mi : ss' ) end_hi st
, i nst _i d
, goodness
, del t a
, f l ags
, cpuper cal l
, dbt i meper cal l
, cal l sper sec
, dbt i meper sec
FROM gv$servicemetric
WHERE ser vi ce_name =' hr ser v'
ORDER BY ser vi ce_name, begi n_t i me DESC, i nst _i d;

SELECT SERVI CE_NAME,
t o_char ( BEGI N_TI ME, ' hh24: mi : ss' ) BEGI N_TI ME,
t o_char ( END_TI ME, ' hh24: mi : ss' ) END_TI ME,
I NTSI ZE_CSEC, GROUP_I D " Ser vi ce Met r i c Gr oup" ,
CPUPERCALL " CPU t i me per cal l " ,
DBTI MEPERCALL " El apsed t i me per cal l " ,
CALLSPERSEC " User Cal l s/ s" ,
DBTI MEPERSEC " DB Ti me/ s"
f r omV$SERVI CEMETRI C_HI STORY
or der by SERVI CE_NAME, BEGI N_TI ME desc;

- - aggr egat ed
SELECT
SERVI CE_NAME,
GROUP_I D " Ser vi ce Met r i c Gr oup" ,
r ound( sum( CPUPERCALL) , 2) " CPU t i me per cal l " ,
r ound( sum( DBTI MEPERCALL) , 2) " El apsed t i me per cal l " ,
r ound( sum( CALLSPERSEC) , 2) " User Cal l s/ s" ,
r ound( sum( DBTI MEPERSEC) , 2) " DB Ti me/ s"
f r omV$SERVI CEMETRI C_HI STORY
gr oup by SERVI CE_NAME, GROUP_I D
or der by SERVI CE_NAME;
Page 482 Oracle DBA Code Examples

Transparent Application Failover (TAF)
TAF Basic Configuration without FAN (From Client Side)
FAILOVER_MODE must be configured in tnsnames.ora
If using TAF, do not set the GLOBAL_DBNAME parameter in the listener.ora
# when you cr eat e t he ser vi ce
sr vct l add ser vi ce - d r ac - s hr ser v - r r ac1, r ac2 - P BASI C
sr vct l st ar t ser vi ce - d r ac - s hr ser v

# i n t he cl i ent t nsnames. or a
# TYPE: SELECT, SESSI ON
hr ser v =
( DESCRI PTI ON =( FAI LOVER=ON) ( LOAD_BALANCE=ON)
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac1- VI P) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac2- VI P) ( PORT=1521) )
( CONNECT_DATA =
( SERVI CE_NAME = hr ser v)
( FAI LOVER_MODE =
( TYPE=SESSI ON)
( METHOD=BASI C)
( RETRI ES=100)
( DELAY=5) ) ) )
TAF Basic Configuration with FAN (Server-Side)
You not need to specify TAF parameters in the tnsnames.ora
sr vct l add ser vi ce - d r ac - s hr ser v - r r ac1, r ac2

sr vct l st ar t ser vi ce - d RACDB - s AP

exec dbms_ser vi ce. modi f y_ser vi ce ( , -
ser vi ce_name => ' hr ser v' , -
aq_ha_not i f i cat i ons => t r ue , -
f ai l over _met hod => dbms_ser vi ce. f ai l over _met hod_basi c , -
f ai l over _t ype => dbms_ser vi ce. f ai l over _t ype_sessi on , -
f ai l over _r et r i es => 100, f ai l over _del ay => 5 , -
cl b_goal => dbms_ser vi ce. cl b_goal _l ong) ;

hr ser v =
( DESCRI PTI ON =( FAI LOVER=ON) ( LOAD_BALANCE=ON)
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac1- VI P) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac2- VI P) ( PORT=1521) )
( CONNECT_DATA = ( SERVI CE_NAME = hr ser v) ) )
TAF Preconnect Configuration
Fast failover but more resources.
The shadow service is always named using the format <service_name>_PRECONNECT.
# conf i gur e t he pr ef er r ed and avai l abl e nodes
sr vct l add ser vi ce - d r ac - s hr ser v - r r ac1 - a r ac2 - P PRECONNECT
sr vct l st ar t ser vi ce - d r ac - s hr ser v

HRSERV =
( DESCRI PTI ON =( FAI LOVER=ON) ( LOAD_BALANCE=ON)
Page 483 Oracle DBA Code Examples

( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac1- vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac2- vi p) ( PORT=1521) )
( CONNECT_DATA = ( SERVI CE_NAME = hr ser v)
( FAI LOVER_MODE = ( BACKUP=HRSERV_PRECONNECT)
( TYPE=SESSI ON) ( METHOD=PRECONNECT) ) ) )

HRSERV_PRECONNECT =
( DESCRI PTI ON =( FAI LOVER=ON) ( LOAD_BALANCE=ON)
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac1- vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=r ac2- vi p) ( PORT=1521) )
( CONNECT_DATA = ( SERVI CE_NAME = HRSERV_PRECONNECT) ) )
Verifying TAF Configuration
SELECT machi ne, f ai l over _met hod, f ai l over _t ype,
f ai l ed_over , ser vi ce_name, COUNT( *)
FROM v$sessi on
GROUP BY machi ne, f ai l over _met hod, f ai l over _t ype,
f ai l ed_over , ser vi ce_name;

sel ect i nst ance_name f r omv$i nst ance;
Enabling Distributed Transaction Processing for Services
# For ser vi ces t hat you ar e goi ng t o use f or di st r i but ed t r ansact i on
pr ocessi ng,
# def i ne onl y one i nst ance as t he pr ef er r ed i nst ance
sr vct l add ser vi ce - d cr m- s xa_01. ser vi ce. us. or acl e. com- r RAC01 - a RAC02,
RAC03
# mar k t he ser vi ce f or di st r i but ed t r ans pr ocessi ng by set t i ng DTP t o TRUE:
execut e dbms_ser vi ce. modi f y_ser vi ce( ser vi ce_name
=>' xa_01. mydomai n. com' , DTP=>TRUE) ;
Page 484 Oracle DBA Code Examples

Administering Services
Service Attributes
Global unique name
Network name
Load Balancing Advisory goal: best service quality (service response time), or best
throughput (how much work is completed in a unit of time).
Distributed transactions flag
Advance queuing notification characteristics for OCI and ODP.NET clients
Failover characteristics
Connection load-balancing algorithm: SHORT: Use Load Balancing Advisory, LONG: Using
session count by service
Threshold: for response time and CPU consumption
Priority: services to consumer groups mapping
High-availability configuration: how the service is distributed across instances when the
system first starts
Administering Services with DBCA
1. On t he DBCA Wel come page, sel ect t he Or acl e Real Appl i cat i on Cl ust er s
opt i on - >Next
2. On t he DBCA Oper at i ons: sel ect Ser vi ces Management - >Next
3. On t he DBCA Li st of Dat abases: sel ect t he cl ust er dat abase - >Next

- - conf i r m
sel ect val ue f r omv$par amet er wher e upper ( name) =' SERVI CE_NAMES'
Administering Services with PL/SQL
/ * Cr eat e a Ser vi ce ( not a r ecommended met hod i n RAC) */
- - some at t r i but es can onl y be modified usi ng PL/ SQL
- - ser vi ce_name and net wor k_name ar e mandat or y
- - ot her s ar e opt i onal wi l l NULL def aul t s
begi n
DBMS_SERVI CE. CREATE_SERVI CE(
ser vi ce_name =>' ol apser v' ,
net wor k_name =>' ol apser v' , - - TNS name f or connect i ons t o t he ser vi ce
goal =>DBMS_SERVI CE. GOAL_SERVI CE_TI ME, - - or GOAL_THROUGHPUT, GOAL_NONE
dt p =>FALSE, - - i s i t f or di st r i but ed t r ansact i on
aq_ha_not i f i cat i ons =>TRUE, - - shoul d HA event s sent t o AQ
f ai l over _met hod =>DBMS_SERVI CE. FAI LOVER_METHOD_BASI C, - - or _NONE
f ai l over _t ype =>DBMS_SERVI CE. FAI LOVER_TYPE_SESSI ON, - - or _NONE _SELECT
f ai l over _r et r i es =>10,
f ai l over _del ay=>1 , - - i n seconds
cl b_goal =>DBMS_SERVI CE. CLB_GOAL_SHORT - - or CLB_GOAL_LONG
) ;
end;
Page 485 Oracle DBA Code Examples

/

sel ect name f r omdba_ser vi ces ;

/ * Modi f y a Ser vi ce Char act ar i st i c */
- - some at t r i but es can onl y be modi f i ed usi ng PL/ SQL
- - i f st opped, st ar t i t bef or e modi f y
begi n
DBMS_SERVI CE. MODI FY_SERVI CE(
ser vi ce_name =>' ol apser v' ,
goal =>DBMS_SERVI CE. GOAL_SERVI CE_TI ME, - - or GOAL_THROUGHPUT, GOAL_NONE
dt p =>FALSE, - - i s i t f or di st r i but ed t r ansact i on
aq_ha_not i f i cat i ons =>TRUE, - - shoul d HA event s sent t o AQ
f ai l over _met hod =>DBMS_SERVI CE. FAI LOVER_METHOD_BASI C, - - or _NONE
f ai l over _t ype =>DBMS_SERVI CE. FAI LOVER_TYPE_SESSI ON, - - or _NONE _SELECT
f ai l over _r et r i es =>10,
f ai l over _del ay=>1 , - - i n seconds
cl b_goal =>DBMS_SERVI CE. CLB_GOAL_SHORT - - or CLB_GOAL_LONG
) ;
end;
/


/ * Del et e Ser vi ce */
begi n
DBMS_SERVI CE. DELETE_SERVI CE( ser vi ce_name =>' ol apser v' ) ;
end;
/


/ * St ar t a ser vi ce */
begi n
DBMS_SERVI CE. START_SERVI CE( ser vi ce_name=>' hr ser v' ,
i nst ance_name => DBMS_SERVI CE. ALL_I NSTANCES, - - i f NULL cur r ent i nst
) ;
end;
/


/ * St op Ser vi ce */
begi n
DBMS_SERVI CE. STOP_SERVI CE( ser vi ce_name=>' hr ser v' ,
i nst ance_name => DBMS_SERVI CE. ALL_I NSTANCES, - - i f NULL cur r ent i nst
) ;
end;
/


/ * Di sconnect Sessi ons */
- - sessi ons connect ed t o t he ser vi ce ar e t er mi nat ed
begi n
- - CAUTI ON: cont r ol doesn' t r et ur n t i l l al l sessi ons ar e t er mi nat ed
DBMS_SERVI CE. DI SCONNECT_SESSI ON( ' hr ser v' ) ;
end;
/
Page 486 Oracle DBA Code Examples

Administering Services with SRVCTL
Creating a Service
sr vct l add ser vi ce - d dbname - s ser vi ce_name - r pr ef er r ed_l i st [ - a
avai l abl e_l i st ] [ - P TAF_pol i cy]
t af pol i cy: NONE, BASI C, or PRECONNECT
/ * Cr eat i ng Ser vi ces */
# i t does NOT add t he r equi r ed t nsnames. or a set t i ngs
sr vct l add ser vi ce d r ac s GL - r RAC02 - a RAC01
sr vct l add ser vi ce d r ac s ERP r RAC01, RAC02 - a RAC03, RAC04

/ * St ar t i ng and St oppi ng Ser vi ces */
sr vct l st ar t ser vi ce - d dbname [ - s ser vi ce_name_l i st ] [ - i i nst _name] [ - o
st ar t _opt i ons]
sr vct l st op ser vi ce - d dbname [ - s ser vi ce_name_l i st [ - i i nst _name] ] [ - c
connect _st r ]

/ * Enabl i ng and Di sabl i ng Ser vi ces */
sr vct l enabl e ser vi ce - d dbname - s ser vi ce_name_l i st [ - i i nst _name]
sr vct l di sabl e ser vi ce - d dbname - s ser vi ce_name_l i st [ - i i nst _name]

/ * Rel ocat i ng Ser vi ces */
sr vct l r el ocat e ser vi ce - d r ac - s hr ser v - i r ac2 - t r ac3

/ * upgr adi ng an avai l abl e i nst ance as a pr ef er r ed i nst ance f or a Ser vi ce*/
- - see al so next sect i on
sr vct l modi f y ser vi ce d r ac s hr ser v - i r ac3 r

/ * Obt ai ni ng t he St at uses of Ser vi ces */
sr vct l st at us ser vi ce - d r ac - s hr ser v

/ * Obt ai ni ng t he Conf i gur at i on of Ser vi ces */
sr vct l conf i g ser vi ce - d r ac - s hr ser v - a

/ * Removi ng Ser vi ces */
r vct l st op ser vi ce - d r ac - s hr ser v
r vct l r emove ser vi ce - d r ac - s hr ser v
Controlling the Preferred and Available Instances
/ * Upgr adi ng an Avai l abl e i nst ance as a Pr ef er r ed i nst ance f or a Ser vi ce */
- - - r upgr ade i nst ance t o pr ef er r ed
sr vct l modi f y ser vi ce d r ac s hr ser v - i r ac3 r


/ * t he scenar i o bel ow makes:
- i 1- i 4 pr ef er r ed, i 5- i 6 avai l abl e f or dwser v
- i 5- i 6 pr ef er r ed, i 1- i 4 avai l abl e f or hr ser v
*/
- - changes t ake ef f ect on next ser vi ces r est ar t
- - i f used, - f Di sconnect al l sessi ons dur i ng st op
sr vct l modi f y ser vi ce d PROD s dwser v n i I 1, I 2, I 3, I 4 a I 5, I 6
sr vct l modi f y ser vi ce d PROD s hr ser v n i I 5, I 6 a I 1, I 2, I 3, I 4

- - f st ops t he ser vi ces gl obal l y on your cl ust er
Page 487 Oracle DBA Code Examples

sr vct l st op ser vi ce d r ac s dwser v, hr ser v - f
sr vct l st ar t ser vi ce d r ac s dwser v, hr ser v
Using Services with Client Applications
/ * TNS connect i on descr i pt or */
- - LOAD_BALANCE=on onl y enabl es a cl i ent - si de connect i on l oad bal anci ng
ERP=( DESCRI PTI ON=
( LOAD_BALANCE=on)
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 1vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 2vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 3vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 4vi p) ( PORT=1521) )
( CONNECT_DATA=( SERVI CE_NAME=ERP) ) )

/ * J DBC connect i on descr i pt i on ( 1) */
ur l =" j dbc: or acl e: oci : @ERP"

/ * J DBC connect i on descr i pt i on ( 2) */
ur l =" j dbc: or acl e: t hi n: @( DESCRI PTI ON=
( LOAD_BALANCE=on)
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 1vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 2vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 3vi p) ( PORT=1521) )
( ADDRESS=( PROTOCOL=TCP) ( HOST=node- 4vi p) ( PORT=1521) )
( CONNECT_DATA=( SERVI CE_NAME=ERP) ) ) "
Services and the Scheduler
BEGI N
DBMS_SCHEDULER. CREATE_J OB_CLASS (
j ob_cl ass_name => ' my_j obs_cl ass' ,
SERVI CE => ' hr ser v' ) ;
END;
/

BEGI N
dbms_schedul er . set _at t r i but e(
name => ' my_j obs_cl ass' ,
at t r i but e => ' ser vi ce' ,
val ue => ' hr ser v' ) ;
END;
/

begi n
dbms_schedul er . cr eat e_j ob (
j ob_name => ' My_J ob' ,
j ob_t ype => ' pl sql _bl ock' , - - st or ed_pr ocedur e, pl sql _bl ock, execut abl e,
chai n
j ob_act i on => ' begi n nul l ; end; ' ,
j ob_cl ass => ' my_j obs_cl ass' ,
st ar t _dat e => SYSDATE+1,
r epeat _i nt er val => ' FREQ=MI NUTELY; I NTERVAL=2' ) ;
end;
Page 488 Oracle DBA Code Examples

/

BEGI N
dbms_schedul er . set _at t r i but e(
name => ' My_J ob' ,
at t r i but e => ' I NSTANCE_STI CKI NESS' ,
val ue => TRUE) ;
END;
/

BEGI N
DBMS_SCHEDULER. DROP_J OB( ' My_J ob' ) ;
END;
/

BEGI N
DBMS_SCHEDULER. DROP_J OB_CLASS( ' my_j obs_cl ass' ) ;
END;
/

DBMS_SCHEDULER. CREATE_J OB_CLASS(
J OB_CLASS_NAME => ' HOT_BATCH_CLASS' ,
RESOURCE_CONSUMER_GROUP => NULL ,
SERVICE => ' HOT_BATCH_SERV' ,
LOGGI NG_LEVEL => DBMS_SCHEDULER. LOGGI NG_RUNS,
LOG_HI STORY => 30, COMMENTS => ' P1 bat ch' ) ;

DBMS_SCHEDULER. CREATE_J OB(
J OB_NAME => ' my_r epor t _j ob' ,
J OB_TYPE => ' st or ed_pr ocedur e' ,
J OB_ACTI ON => ' my_name. my_pr oc( ) ; ' ,
NUMBER_OF_ARGUMENTS => 4, START_DATE => SYSDATE+1,
REPEAT_I NTERVAL => 5, END_DATE => SYSDATE+30,
JOB_CLASS => ' HOT_BATCH_CLASS' ,
ENABLED => TRUE,
AUTO_DROP => f al se, COMMENTS => ' dai l y st at us' ) ;
Measuring Performance by Service Using the AWR
/ * Enabling Gather statiscitc on Service-Module-Action combination */
- - t o di spl ay cur r ent l y connect ed ser vi ces, modul es and act i ons
sel ect SI D, USERNAME, SERVI CE_NAME, MODULE, ACTI ON f r omV$SESSI ON
wher e SERVI CE_NAME i n ( ' hr ser v' , ' oeser v' )

- - ser vi ce name and modul e name ar e mandat or y
begi n
DBMS_MONI TOR. SERV_MOD_ACT_STAT_ENABLE( SERVI CE_NAME => ' hr ser v' ,
MODULE_NAME=>' PAYROLL' ,
ACTI ON_NAME => ' EXCEPTI ONS PAY' ) ;
end;
/

- - gat her st at s f or PAYROLL modul e and ACTI ON whose name i s nul l
begi n
DBMS_MONI TOR. SERV_MOD_ACT_STAT_ENABLE( SERVI CE_NAME => ' hr ser v' ,
Page 489 Oracle DBA Code Examples

MODULE_NAME=>' PAYROLL' ,
ACTI ON_NAME => NULL) ;
end;
/

- - gat her st at s f or PAYROLL modul e and Al l i t s ACTI ONs
begi n
DBMS_MONI TOR. SERV_MOD_ACT_STAT_ENABLE( SERVI CE_NAME => ' hr ser v' ,
MODULE_NAME=>' PAYROLL' ,
ACTI ON_NAME => ' ###ALL_ACTI ONS' ) ;
end;
/

- - t o vi ew enabl ed moni t or i ngs
- - t ypes: SERVI CE, SERVI CE_MODULE, SERVI CE_MODULE_ACTI ON
sel ect A. AGGREGATI ON_TYPE, A. PRI MARY_I D , A. QUALI FI ER_I D1 , A. QUALI FI ER_I D2
f r omDBA_ENABLED_AGGREGATI ONS a

- - t o vi ew gat her ed st at s
sel ect S. AGGREGATI ON_TYPE, S. SERVI CE_NAME, S. MODULE, S. ACTI ON, N. CLASS,
decode( n. CLASS,
' 1' , ' User ' , ' 2' , ' Redo' , ' 4' , ' Enqueue' , ' 8' , ' Cache' , ' 16' , ' OS' , ' 32' , ' RAC' , ' 64' , ' SQL
' , ' 128' , ' Debug' , N. CLASS) STAT_CLASS,
S. STAT_NAME, S. VALUE
f r om V$SERV_MOD_ACT_STATS s, V$STATNAME n
wher e S. STAT_I D = N. STAT_I D
or der by N. CLASS, S. STAT_I D

- - cal l t i mes and per f or mance st at i st i cs vi ews:
V$SERVI CE_STATS
V$SERVI CE_EVENTS
V$SERVI CE_WAI T_CLASSES
V$SERVI CEMETRI C
V$SERVI CEMETRI C_HI STORY

/ * To Disable Cumulative Stats */
- - st at s wi l l be r emoved f r omV$SERV_MOD_ACT_STATS
begi n
DBMS_MONI TOR. SERV_MOD_ACT_STAT_DI SABLE( SERVI CE_NAME => ' hr ser v' ,
MODULE_NAME=>' PAYROLL' ,
ACTI ON_NAME => ' EXCEPTI ONS PAY' ) ;
end;
/


/ * Service Quality Statistics */
- - scr i pt f r omOr acl e document at i on
- - pr ovi des ser vi ce qual i t y st at i st i cs ever y f i ve seconds
SET PAGESI ZE 60 COLSEP ' | ' NUMWI DTH 8 LI NESI ZE 132 VERI FY OFF FEEDBACK OFF
COLUMN ser vi ce_name FORMAT A20 TRUNCATED HEADI NG ' Ser vi ce'
COLUMN begi n_t i me HEADI NG ' Begi n Ti me' FORMAT A10
COLUMN end_t i me HEADI NG ' End Ti me' FORMAT A10
COLUMN i nst ance_name HEADI NG ' I nst ance' FORMAT A10
COLUMN ser vi ce_t i me HEADI NG ' Ser vi ce Ti me| mSec/ Cal l ' FORMAT 999999999
COLUMN t hr oughput HEADI NG ' Cal l s/ sec' FORMAT 99. 99
BREAK ON ser vi ce_name SKI P 1
SELECT
Page 490 Oracle DBA Code Examples

ser vi ce_name
, TO_CHAR( begi n_t i me, ' HH: MI : SS' ) begi n_t i me
, TO_CHAR( end_t i me, ' HH: MI : SS' ) end_t i me
, i nst ance_name
, el apsedper cal l ser vi ce_t i me
, cal l sper sec t hr oughput
FROM gv$i nst ance i
, gv$act i ve_ser vi ces s
, gv$ser vi cemet r i c m
WHERE s. i nst _i d = m. i nst _i d
AND s. name_hash = m. ser vi ce_name_hash
AND i . i nst _i d = m. i nst _i d
AND m. gr oup_i d = 10
ORDER BY ser vi ce_name , i . i nst _i d , begi n_t i me ;
Service Thresholds and Alerts
For the services, you can set alerts for:
o ELAPSED_TIME_PER_CALL Elapsed time for each user call for each service (micro s)
o CPU_TIME_PER_CALL CPU time for each user call for each service (micro s)
Thresholds must be set on each instance supporting the service
- - t hr eshol ds must be set on each i nst ance suppor t i ng t he ser vi ce
begi n
DBMS_SERVER_ALERT. SET_THRESHOLD(
METRI CS_I D => DBMS_SERVER_ALERT. ELAPSED_TI ME_PER_CALL
, WARNI NG_OPERATOR => dbms_ser ver _al er t . oper at or _ge
, WARNI NG_VALUE => ' 500000' - - = 0. 5 seconds
, CRI TI CAL_OPERATOR => dbms_ser ver _al er t . oper at or _ge
, CRI TI CAL_VALUE => ' 750000' = 0. 75 seconds
, OBSERVATI ON_PERI OD => 30 - - i n mi ns
, CONSECUTI VE_OCCURRENCES => 5 - - t ol er ance occur ance bef or e al er t s
, I NSTANCE_NAME => NULL - - must be NULL i n t hi s case
, OBJ ECT_TYPE => dbms_ser ver _al er t . obj ect _t ype_ser vi ce
, OBJ ECT_NAME => ' hr ser v' ) ;
end;
/

- - Ver i f y t he t hr eshol d conf i gur at i on
SELECT METRI CS_NAME, I NSTANCE_NAME, WARNI NG_VALUE, CRI TI CAL_VALUE,
OBSERVATI ON_PERI OD
f r omdba_t hr eshol ds
wher e OBJ ECT_NAME => ' hr ser v' ;

- - most r ecent 60 s
SELECT ser vi ce_name, el apsedper cal l , cpuper cal l
FROM V$SERVI CEMETRI C;

- - l ast hour
SELECT ser vi ce_name, el apsedper cal l , cpuper cal l
FROM V$SERVI CEMETRI C_HI STORY;
Page 491 Oracle DBA Code Examples

Service Performance Views
There are more than 300 performance-related statistics that are tracked and visible in
V$SYSSTAT. Of these, 28 statistics are tracked for services. To see the statistics measured
for services, run the following query: SELECT DISTINCT stat_name FROM v$service_stats.
For service metrics, see Monitoring Load Balancing Advisory
- - gener al st at s per ser vi ce
- - DB t i me ( r esponse t i me) = DB CPU + wai t t i me
sel ect V. SERVI CE_NAME,
decode( n. CLASS,
' 1' , ' User ' , ' 2' , ' Redo' , ' 4' , ' Enqueue' , ' 8' , ' Cache' , ' 16' , ' OS' , ' 32' , ' RAC' , ' 64' , ' SQL
' , ' 128' , ' Debug' , N. CLASS) STAT_CLASS
, V. STAT_NAME , VALUE
f r om V$SERVICE_STATS V , V$STATNAME N
wher e V. STAT_I D = N. STAT_I D
or der by 1, 2;


- - aggr egat ed wai t s ( by wai t cl ass)
SELECT *
FROM V$SERVI CE_WAI T_CLASS
WHERE SERVI CE_NAME NOT LI KE ' SYS$%'
ORDER BY SERVI CE_NAME, TI ME_WAI TED DESC


- - aggr egat ed wai t s ( by wai t event )
SELECT *
FROM V$SERVICE_EVENT
WHERE SERVI CE_NAME NOT LI KE ' SYS$%'
AND EVENT NOT I N ( ' SQL*Net message f r omcl i ent ' )
ORDER BY SERVI CE_NAME, TI ME_WAI TED DESC;


- - st at s f or a speci f i c combi nat i on of ser vi ce/ modul e/ act i on
- - When st at i st i cs col l ect i on f or speci f i c modul es and act i ons i s enabl ed
sel ect *
f r omV$SERV_MOD_ACT_STATS
ORDER BY 1, 2, 3, 4

- - i nf or mat i on about enabl ed on- demand st at i st i c aggr egat i on
sel ect *
f r omDBA_ENABLED_AGGREGATI ONS;

- - i nf or mat i on about enabl ed SQL t r aces
sel ct *
f r omDBA_ENABLED_TRACES;
Restricted Session and Services
If the restricted instance is manually registered in the listener, the incoming connection
requrests may be routed to the instance, refused by the instance and returns error.
If the restricted instance is dynamically registered in the listener, the incoming connection
requrests will not be routed to the instance, even for users with RESTRICTED SESSION
privilege.
Page 492 Oracle DBA Code Examples

Configuring Recovery Manager and Archiving
Backup Possible Distributions in RAC
Network backup server: dedicated backup server manages backups for the whole RAC.
One local drive: one node has access to a local backup appliance.
/ * Mul t i pl e Dr i ves CFS Backup Scheme */
- - cf s = al l nodes have t hei r ar chi ved l og i n shar ed st or age
- - one t i me set up
CONFI GURE DEVI CE TYPE sbt PARALLELI SM 3;
CONFI GURE DEFAULT DEVI CE TYPE TO sbt ;
CONFI GURE CHANNEL 1 DEVI CE TYPE sbt CONNECT ' user 1/ passwd1@node1' ;
CONFI GURE CHANNEL 2 DEVI CE TYPE sbt CONNECT ' user 2/ passwd2@node2' ;
CONFI GURE CHANNEL 3 DEVI CE TYPE sbt CONNECT ' user 3/ passwd3@node3' ;

- - backup i s t hen di st r i but ed i n al l backup t apes i n t he cl ust er
BACKUP DATABASE PLUS ARCHI VELOG DELETE I NPUT;

Multiple drives: each node has access to a local backup appliance.
RMAN Restore Scenarios for Real Application Clusters
Cluster File System Restore Scheme
1. Make the Backup media and all the Archived Log files available to the available node.
2. Then Restore using RESOTRE DATABASE and RECOVER DATABASE commands.
Non-Cluster File System Restore Scheme
1. You must configure a network file system file so that the recovery node can read the
archiving directories on the remaining nodes.
2. Then Restore using RESOTRE DATABASE and RECOVER DATABASE commands.
RMAN and Oracle Net in Real Application Clusters
Connection server must be dedicated.
Each net service name must specify only one instance.
Connecting to Specific Node
r man TARGET=SYS/ ORACLE@RAC1 CATALOG=RMAN/ RMAN@RMAN
Page 493 Oracle DBA Code Examples

Instance Recovery in Real Application Clusters
Single Node Failure in Real Application Clusters
When one instance performs recovery for another instance, the surviving instance reads
online redo logs generated by the failed instance and uses that information to ensure that
committed transactions are recorded in the database.
Multiple-Node Failures in Real Application Clusters
If all instances of an Oracle RAC database fail, then Oracle automatically recovers the
instances the next time one instance opens the database.
Configuring the RMAN Snapshot Control File Location
The snapshot control file is a temporary snapshot control file that RMAN creates to re-
synchronize from a read-consistent version of the control file.
- - conf i gur ed l ocat i on of t he snapshot cont r ol f i l e
SHOWSNAPSHOT CONTROLFI LE NAME;

- - t o change i t ( gl obal l y i n al l nodes)
CONFI GURE SNAPSHOT CONTROLFI LE NAME TO ' $ORACLE_HOME/ dbs/ scf / snap_pr od. cf ' ;
Configuring the RMAN Control File and SPFILE Autobackup Feature
# swi t ch i t on
CONFI GURE CONTROLFI LE AUTOBACKUP ON;

# Aut o cont r ol f i l e and spf i l e backup must be conf i gur ed i n a shared l ocat i on.
CONFI GURE CONTROLFI LE AUTOBACKUP FORMAT = ' / u02/ or adat a/ RAC/ cf _%F' ;
CONFI GURE CONTROLFI LE AUTOBACKUP FORMAT FOR DEVI CE TYPE DI SK TO ' +FRA' ;

# i n t he r ecover y dest i nat i on
CONFI GURE CONTROLFI LE AUTOBACKUP FORMAT FOR DEVI CE TYPE DI SK TO ' %F' ;
Configuring Channels for RMAN in Real Application Clusters
Configuring Channels to use Automatic Workload Balancing
CONFI GURE DEVI CE TYPE [ di sk | sbt ] PARALLELI SM number of channels;

# conf i gur e t he SQL Net ser vi ce name wi t h l oad bal anci ng t ur ned on
CONFI GURE CHANNEL DEVI CE TYPE SBT CONNECT ' sys/ pwd1@<ser vi ce_name>'
Configuring Channels to Use a Specific Instance
# manual i nst ance assi gnment
# To conf i gur e channel s t o use a speci f i c i nst ance, use t he f ol l owi ng synt ax:
CONFI GURE DEVI CE TYPE sbt PARALLELI SM 2;
CONFI GURE CHANNEL 1 DEVI CE TYPE sbt CONNECT ' SYS/ pss@r ac1'
CONFI GURE CHANNEL 2 DEVI CE TYPE sbt CONNECT ' SYS/ pss@r ac2'

# Aut omat i c i nst ance assi gnment
Page 494 Oracle DBA Code Examples

# you can conf i gur e speci al ser vi ce f or r man j obs
# ser vi ce wor kl oad wi l l be used
CONFI GURE DEFAULT DEVI CE TYPE TO sbt ;
CONFI GURE DEVI CE TYPE sbt PARALLELI SM 3;
CONFI GURE CHANNEL DEVI CE TYPE sbt CONNECT=' sys/ r ac@r manser v' ;
# al so, par al l el conf i gur at i on wi l l di st r i but e t he j ob on mul t i pl e i nst ances
CONFI GURE DEVI CE TYPE sbt PARALLELI SM 3;


# conf i gur i ng channel s manual l y
RUN
{
ALLOCATE CHANNEL CH1 CONNECT ' user 1/ pwd1@node1' ;
ALLOCATE CHANNEL CH2 CONNECT ' user 2/ pwd2@node2' ;
ALLOCATE CHANNEL CH3 CONNECT ' user 3/ pwd3@node3' ;
BACKUP DATABASE PLUS ARCHI VED LOG;
}
Node Affinity Awareness of Fast Connections
When deciding which channel to use to back up a particular datafile, RMAN gives
preference to the nodes with faster access to the datafiles that you want to back up.
Archived Redo Log File Conventions in RAC
show par amet er LOG_ARCHI VE_FORMAT
al t er syst emset LOG_ARCHI VE_FORMAT=' l og_%t _%s_%r . ar c' scope=spf i l e si d=' *' ;
Archive Redo Log Configuration Scenarios
Automatic Storage Management and CFS Archiving Scheme
The preferred configuration for RAC is to use Automatic Storage Management (ASM) for a
recovery area with a different disk group for your recovery set than for your datafiles.
show par amet er ar chi ve_dest
show par amet er r ecover y

# each node ar chi ves t o a di r ect or y wi t h t he same name on al l i nst ances
si d1. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest "
si d2. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest "
si d3. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest "
Non-Cluster File System Local Archiving Scheme
In the non-cluster file system local archiving scheme, each node archives to a uniquely
named local directory. The directory in each node can be read only mounted from the
other nodes.
# ar chi ved l og st or ed l ocal l y and t he ot her l ocat i ons can be r ead by t he node
# ( f or r ecover y)
si d1. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest _1"
si d2. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest _2"
si d3. LOG_ARCHI VE_DEST_1=" LOCATI ON=/ ar c_dest _3"
Page 495 Oracle DBA Code Examples

Changing the Archiving Mode in Real Application Clusters
sel ect l og_mode f r omv$dat abase;

sr vct l st op dat abase - d r ac
Back up t he dat abase
set LOG_ARCHI VE_DEST_n
show par amet er LOG_ARCHI VE_DEST
- - no i nst ance i n OPEN mode
STARTUP MOUNT
ALTER DATABASE ARCHI VELOG;
SHUTDOWN I MMEDI ATE
Back up t he dat abase
sr vct l st ar t dat abase - d r ac
Deleting Archived Redo Logs after a Successful Backup
# i f aut omat i c channel s ar e conf i gur ed
DELETE ARCHI VELOG ALL BACKED UP n TI MES TO DEVI CE TYPE devi ce_t ype;

# conf i gur i ng t he channel s manual l y
ALLOCATE CHANNEL FOR MAI NTENANCE DEVI CE TYPE DI SK CONNECT ' SYS/ or acl e@node1' ;
ALLOCATE CHANNEL FOR MAI NTENANCE DEVI CE TYPE DI SK CONNECT ' SYS/ or acl e@node2' ;
ALLOCATE CHANNEL FOR MAI NTENANCE DEVI CE TYPE DI SK CONNECT ' SYS/ or acl e@node3' ;
DELETE ARCHI VELOG ALL BACKED UP n TI MES TO DEVI CE TYPE devi ce_t ype;
Monitoring the Archiver Processes
SELECT A. I NST_I D, A. PROCESS, A. STATUS, A. LOG_SEQUENCE, A. STATE
FROM GV$ARCHI VE_PROCESSES A
WHERE STATUS<>' STOPPED'
ORDER BY A. I NST_I D

# ar chi ved l og f i l es
SELECT I NST_I D , THREAD#, NAME FROM GV$ARCHI VED_LOG;
Log_Archive_Dest_1 Set To Default Even When DB_Recovery_File_Dest Is
Set (Bug 6373164)
You should take this bug into consideration on Oracle 11.1.0.6. If you just leave DEST_10
pointing to the flash recovery areas (as the default case), DEST_1 will also point to the default
location: ORACLE_HOME\RDBMS
Here are the steps to reproduce the bug:
When I disable LOG_ARCHIVE_DEST_1, the v$parameter and V$ARCHIVE_DEST are
correctly updated. But after I restart the db, the LOG_ARCHIVE_DEST_1 is NULL in
v$parameter but it points to C:\app\Administrator\product\11.1.0\db_1\RDBMS in
V$ARCHIVE_DEST.
DEST_10 is pointing to the recovery area but it's shown by V$ARCHIVE_DEST and not by
v$parameter. I also noticed Oracle writes archive log files in the both destinations:
DB_RECOVERY_FILE_DEST and the default one.
Page 496 Oracle DBA Code Examples

Work around: Explicitly set LOG_ARCHIVE_DEST_1 to
LOCATION=USE_DB_RECOVERY_FILE_DEST
SQL> sel ect schedul e, dest i nat i on
2 f r omV$ARCHI VE_DEST
3 wher e dest _name=' LOG_ARCHI VE_DEST_1' ;

SCHEDULE DESTI NATI ON
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ACTI VE C: \ app\ Admi ni st r at or \ pr oduct \ 11. 1. 0\ db_1\ RDBMS


SQL> sel ect name, val ue
2 f r omv$par amet er
3 wher e upper ( name) l i ke ' LOG_ARCHI VE_DEST_1' ;

NAME VALUE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
l og_ar chi ve_dest _1


SQL> al t er syst emset LOG_ARCHI VE_DEST_1=' ' scope=bot h;
Syst emal t er ed.



SQL> sel ect schedul e, dest i nat i on
2 f r omV$ARCHI VE_DEST
3 wher e dest _name=' LOG_ARCHI VE_DEST_1' ;

SCHEDULE DESTI NATI ON
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
I NACTI VE


SQL> shut down i mmedi at e
Dat abase cl osed.
Dat abase di smount ed.
ORACLE i nst ance shut down.

SQL> st ar t up
ORACLE i nst ance st ar t ed.

Tot al Syst emGl obal Ar ea 431038464 byt es
Fi xed Si ze 1333676 byt es
Var i abl e Si ze 343934548 byt es
Dat abase Buf f er s 79691776 byt es
Redo Buf f er s 6078464 byt es
Dat abase mount ed.
Dat abase opened.


SQL> sel ect name, val ue
2 f r omv$par amet er
3 wher e upper ( name) l i ke ' LOG_ARCHI VE_DEST_1' ;

NAME VALUE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Page 497 Oracle DBA Code Examples

l og_ar chi ve_dest _1


SQL> sel ect schedul e, dest i nat i on
2 f r omV$ARCHI VE_DEST
3 wher e dest _name=' LOG_ARCHI VE_DEST_1' ;

SCHEDULE DESTI NATI ON
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ACTI VE C: \ app\ Admi ni st r at or \ pr oduct \ 11. 1. 0\ db_1\ RDBMS



SQL> sel ect schedul e, dest i nat i on
2 f r omV$ARCHI VE_DEST
3 wher e dest _name=' LOG_ARCHI VE_DEST_10' ;

SCHEDULE DESTI NATI ON
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ACTI VE USE_DB_RECOVERY_FI LE_DEST

SQL> sel ect name, val ue
2 f r omv$par amet er
3 wher e upper ( name) l i ke ' LOG_ARCHI VE_DEST_10' ;

NAME VALUE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
l og_ar chi ve_dest _10
Media Recovery in Real Application Clusters
Same as standalone database.
Parallel Recovery in Real Application Clusters
When parallelism is configured, Oracle automatically use the optimum degree of
parallelism for recovery.
# Di sabl i ng I nst ance and Cr ash Recover y Par al l el i sm
conf i gur e RECOVERY_PARALLELI SM t o 0

# Di sabl i ng Medi a Recover y Par al l el i sm
RMAN> RECOVER DATABASE NOPARALLEL
SQL>ALTER DATABASE RECOVER NOPARALLEL
Using a Flash Recovery Area in RAC
Set the parameter DB_RECOVERY_FILE_DEST to a shared location and must be the same
value on all instances.
Page 498 Oracle DBA Code Examples

Managing Backup and Recovery
Page 499 Oracle DBA Code Examples

Administrative Options
Using Enterprise Manager Grid Control to Discover Nodes and Instances
To discover targets if a database is created after agents are installed or if a database is not
automatically discovered at agent install time:
1. Log in to Enterprise Manager and click the Targets tab.
2. Click the Database tab to view all of the available targets. The column labeled Types
shows the Oracle RAC databases using the entry "Cluster Database".
3. Select the target name, then clicking Add. The Add Database Target: Specify Host page
appears, which enables you to add databases, Listeners, and Automatic Storage
Management (ASM) as monitored targets.
4. Click the flashlight icon to display the available host names, select a host, then click
Continue. The Add Database: Specify Source page appears.
5. Either request Enterprise Manager to discover only single-instance databases and
Listeners, or to discover all cluster databases, single-instance databases, and Listeners on
the cluster, then click Continue.
6. Enterprise Manager performs discovery to locate and display the cluster database and its
associated instances. The Targets Discovered on Cluster page appears. If this procedure
did not discover your reconfigured cluster database and all of its instances, you can use
this page to manually configure your cluster databases and single-instance databases.
Additional Information About SQL*Plus in RAC
How SQL*Plus Commands Affect Instances
Most SQL statements affect the current instance.
ALTER SYSTEM SWITCH LOGFILE affects only the current instance.
o To force a global log switch, use the ALTER SYSTEM ARCHIVE LOG CURRENT
statement.
o The INSTANCE option of ALTER SYSTEM ARCHIVE LOG enables you to archive each
online redo log file for a specific instance.
Displaying Running Instances
SHOWI NSTANCE

SELECT * FROM V$ACTI VE_I NSTANCES;
Displaying Connect Identifier
use SQLPROMPT Command _CONNECT_I DENTI FI ER
SET SQLPROMPT " _CONNECT_I DENTI FI ER _USER > "
Page 500 Oracle DBA Code Examples

Quiescing RAC Databases
The ALTER SYSTEM QUIESCE RESTRICTED and ALTER SYSTEM UNQUIESCE statements
affect all instances in an Oracle RAC environment.
ALTER SYSTEM QUI ESCE RESTRI CTED;
To set the database in the QUIESCE state, the Database Resource Manager must be
activated in all the instances.
- - t o make sur e t he r esour ce manager i s act i ve ( not nul l )
sel ect val ue f r omv$par amet er wher e upper ( name) =' RESOURCE_MANAGER_PLAN' ;
Quiesced State and Cold Backups
You cannot use the quiesced state to take a cold backup.
Transparent Data Encryption and Wallets in RAC
One wallet shared by all instances on shared storage.
One copy of the wallet on each local storage: Local copies need to be synchronized each
time master key is changed.
The wal l et must r esi de i n t he di r ect or y speci f i ed by t he set t i ng f or t he
WALLET_LOCATI ON or ENCRYPTI ON_WALLET_LOCATI ON par amet er i n sql net . or a.
Administering System and Network Interfaces with oifcfg
Defining Network Interfaces with oifcfg
Syntax and Commands for the oifcfg Command-Line Tool
Or acl e I nt er f ace Conf i gur at i on

oi f cf g - hel p

oi f cf g i f l i st

oi f cf g get i f [ [ - gl obal | - node nodename] [ - i f i f _name[ / subnet ] ] [ - t ype
i f _t ype] ]

# st or e t he i nt er f ace hme0, wi t h t he subnet 139. 185. 141. 0, as a gl obal
# i nt er f ace ( t o be used as an i nt er connect f or al l of t he RAC i nst ances i n
your cl ust er )
oi f cf g set i f - gl obal hme0/ 139. 185. 141. 0: cl ust er _i nt er connect

# cr eat e t he cms0 i nt er f ace i n r ac1 and r ac2
oi f cf g set i f - node r ac1 cms0/ 139. 185. 142. 1: cl ust er _i nt er connect
oi f cf g set i f - node r ac2 cms0/ 139. 185. 142. 2: cl ust er _i nt er connect

# del et i ng an i nt er f ace
# CAUTION: when no opt i on pr ovi ded, al l i nt er f aces wi l l be del et ed:
oi f cf g del i f - gl obal qf e0/ 204. 152. 65. 16
# al l gl obal i nt er f aces wi l l be del et ed
oi f cf g del i f - gl obal
Page 501 Oracle DBA Code Examples

Changing Public or Interconnect IP Subnet Configuration
A network interface can be stored as a global interface or as a node-specific interface. An
interface is stored as a global interface when all the nodes of a RAC cluster have the same
interface connected to the same subnet (recommended). It is stored as a node-specific
interface only when there are some nodes in the cluster that have a different set of
interfaces and subnets.
su -
$CRS_HOME/ bi n/ oi f cf g get i f

oi f cf g del i f - gl obal et h0
oi f cf g set i f gl obal et h0/ 139. 2. 166. 0: publ i c

oi f cf g del i f gl obal et h1
oi f cf g set i f gl obal et h1/ 192. 168. 1. 0: cl ust er _i nt er connect

oi f cf g get i f
Changing VIP Addresses
If only the IP address is changed, it is not necessary to make changes to the listener.ora,
tnsnames.ora and initialization parameter files, provided they are using the virtual host
names. If changing both the virtual host name and the VIP address for a node, it will be
necessary to modify those files with the new virtual host name. For the listener.ora
file,you can use netca to remove the old listener and create a new listener. In addition,
changes will need to be made to the tnsnames.ora file of any clients connecting to the old
virtual host name.
1. Conf i r mt he cur r ent I P addr ess f or t he VI P by r unni ng t he i f conf i g a
command. On Wi ndows, r un t he i pconf i g / al l command.
i f conf i g a

2. St op Fi r st , t he dat abase i nst ance, and t hen t he ASM i nst ance. When done,
st op nodeapps.
sr vct l st op i nst ance . .
sr vct l st op asm. .
sr vct l st op nodeapps

3. Ver i f y t hat t he VI P i s no l onger r unni ng by execut i ng t he i f conf i g - a
command agai n:
i f conf i g a

I f t he i nt er f ace st i l l onl i ne, t hi s i s an i ndi cat i on t hat a r esour ce whi ch i s
dependent on t he VI P i s st i l l r unni ng. The cr s_st at - t command can hel p t o
show r esour ces t hat ar e st i l l onl i ne:
cr s_st at - t

4. Make any changes necessar y t o al l nodes' / et c/ host s f i l es ( on UNI X) , or
\ WI NNT\ Syst em32\ dr i ver s\ et c\ host s f i l es on Wi ndows, and make t he necessar y DNS
changes, t o associ at e t he new I P addr ess wi t h t he ol d host name.

5. Modi f y nodeapps and pr ovi de t he new vi r t ual I P addr ess:
su -
srvctl modify nodeapps -n rac1 -A 192.168.2.125/255.255.255.0/eth0

6. St ar t nodeapps agai n.
sr vct l st ar t nodeapps - n r ac1
Page 502 Oracle DBA Code Examples


7. Repeat t he same st eps f or al l t he nodes i n t he cl ust er . You can st ay
connect ed f r omt he f i r st node.

8. ver i f i es t he connect i vi t y bet ween al l of t he nodes.
cl uvf y comp nodecon - n al l [ - ver bose]

9. Rest ar t al l of t he i nst ances and node appl i cat i ons

Page 503 Oracle DBA Code Examples

Adding Nodes and Instances on UNIX-Based Systems
Adding Nodes to a RAC Environment
In adding nodes to a cluster, there are three procedures that can be used:
Cloning: copy images of Oracle Clusterware and RAC software onto the other nodes that
have identical hardware and software.
OEM: GUI of cloning.
Interactive or silent procedures using scripts and DBCA.
Cloning Oracle Clusterware and RAC Software in Grid Environments
Prerequisites
Make the required prerequisites changes on OS to prepare the node for the software
cloning. The steps stated in the Preinstallation Tasks illustrates the steps required for
Oracle 10g R2 for Oracle Linux Enterprise 4.5 for x86.
Metalink document ID 169706.1 is quick reference of OS Installation and Configuration
Requirements.
The DB Console should be installed so that the required Perl files are installed in
$ORACLE_HOME/clone/bin
If the server has more than one Perl version installed, it may be necessary to specify
the PERL5LIB environment variable so that the versions of the Perl modules match
with the Perl version used.
Cloning Procedure Steps
Cloning Oracle10g Release 2 on Oracle Linux Enterprise 4.5 for x86 Using OUI:
1. To ensure the integrity of the copy, shutdown any databases, listeners, agents etc. that
are running from the source home.
2. Clone the Oracle Clusterware home then Oracle Database home
cd / u01/ cr s
t ar - cvf / t mp/ sour cecr s. t ar
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0
t ar - cvf / t mp/ sour cedb. t ar
3. Make sure the required users and groups are there on the new node
i d or acl e
i d oi nst al l
4. Extract the tar file
cd / u01/ cr s
t ar - xvf / t mp/ sour cecr s. t ar
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0
t ar - xvf / t mp/ sour cedb. t ar
5. Run the Oracle Universal Installer (OUI) in clone mode
/ * Met hod 1 */
cd $ORACLE_HOME/ cl one/ bi n
per l cl one. pl ORACLE_HOME=" <t ar get _home>" ORACLE_HOME_NAME=" <uni que_home_name>"
/ * Met hod 2 */
cd $ORACLE_HOME/ oui / bi n
. / r unI nst al l er - cl one - si l ent - i gnor ePr eReq ORACLE_HOME=" <t ar get _home>"
ORACLE_HOME_NAME=" <uni que_home_name>"
If necessary, add "-invPtrLoc <path>/oraInst.loc" or "-ignoreSysPrereqs" to the command
line.
Page 504 Oracle DBA Code Examples

6. Run the installation scripts
$ORACLE_HOME/ r oot . sh
7. Repeat steps 1 to 5 on Oracle home with RAC software
8. Run the Oracle Net Configuration Assistant (NETCA) on the new node to create a Listener.
9. Make if necessary, any modification in the tnsnames.ora file.
10. To start the dbconsole on the new server, refer to Metalink Note 467598.1 and Note
278100.1 for
Quick-Start Node and Instance Addition Procedures
Prerequisites
Make the required prerequisites changes on OS to prepare the node for the software
cloning.
o The steps stated in Preinstallation Tasks illustrates the steps required for Oracle 10g
R2 for Oracle Linux Enterprise 4.5 for x86. Be careful about the following changes
in the steps:
The examples in this sections assumes the node to add has the ip
addresses public:192.168.4.15, vip:192.168.4.17, priv:192.168.0.15
with hostname of rac3.
ORACLE_SID=rac3 in the .bash_profile file
Be careful NOT to partition the disks as they are already partitioned
and used by the other node(s). However, raw disks must be binded.
Domain name resolution (/etc/hosts) must apply in all nodes
Remote installation procedure must be redone to all nodes.
Metalink document ID 169706.1 is quick reference of OS Installation and Configuration
Requirements for the supported Operating Systems.
Adding an Oracle Clusterware Home to a New Node
Practically, I noticed the procedure does not work unless all the existing nodes in the RAC
are alive.
# ( 1) r un add node i n r ac1
# as or acl e
expor t CRS_HOME=/ u01/ cr s
cd $CRS_HOME/ oui / bi n
. / addNode. sh
# Speci f y t he New Nodes t hen Next
# Ver i f y t he new node names i n t he Summar y page t hen Fi ni sh ( copy si ze: 80 MB)
# r un t he scr i pt s as i ndi cat ed by OUI . They must be:
# / u01/ app/ or acl e/ or aI nvent or y/ or ai nst Root . sh i n r ac3
# / u01/ cr s/ i nst al l / r oot addnode. sh i n r ac1
# in rac3: EDIT root.sh and f i x t he node l i st i n i t s header BEFORE r unni ng i t
# / u01/ cr s/ r oot . sh i n r ac3
# exi t t he OUI

## i f r oot . sh f ai l ed, you can cancel i t s ef f ect by r unni ng:
# $CRS_HOME/ i nst al l / r oot del et e. sh

# ( 2) r ac1 as or acl e: r un t he Or acl e Not i f i cat i on Ser vi ce ( RACGONS)
# obt ai n r emot e por t number
cat $CRS_HOME/ opmn/ conf / ons. conf i g
$CRS_HOME/ bi n/ r acgons add_conf i g r ac3: 6200
#t o ver i f y
pi ng r ac3- vi p
cr s_st at - t

Page 505 Oracle DBA Code Examples

# i f you' r e usi ng vmwar e, make backup of t he envi r onment now.
Adding an Oracle Home with RAC to a New Node
OUI can be used interactively or in silent mode. This example shows the interactive mode
steps.
# ( 1) copy Or acl e home
# i n r ac1 as or acl e
cd $ORACLE_HOME/ oui / bi n
. / addNode. sh
# sel ect node t hen Next
# ver i f y i nf o i n t he Summar y page t hen Next
# about 1. 5 GB wi l l be copi ed t o r ac3
# r un t he r equi r ed scr i pt

# ( 2) add Li st ener
# r ac3 as or acl e: r un net ca t o add a l i st ener i n r ac3 node ( sel ect r ac3 ONLY)
$ORACLE_HOME/ bi n/ net ca

# ( 3) cr eat e db i nst ance as descr i ed i n " Addi ng Dat abase I nst ances t o New
Nodes"

# ( 4) Per f or mPost i nst al l at i on St eps. Be awar e t o check t he ASM i nst ance name
bef or e edi t i ng / et c/ or act ab f i l e: ps - ef | gr ep asm

# ( 5) Revi ew $ORACLE_HOME/ net wor k/ admi n/ t nsnames. or a f i l e and f i x node
# names er r or s, i f any.

# ( 6) pr ef er abl y per f or mGener al Usef ul Post i nst al l at i on Tasks.
Detailed Node and Instance Addition Procedure
Step 1: Connecting New Nodes to the Cluster
Making Physical Connections
Installing the Operating System
Creating Oracle Users
Verifying the Installation with the Cluster Verification Utility
Checking the Installation
Step 2: Extending Clusterware and Oracle Software to New Nodes
Adding Nodes at the Vendor Clusterware Layer
Adding Nodes at the Oracle Clusterware Layer
Step 3: Preparing Storage on New Nodes
Raw Device Storage Preparation for New Nodes
Page 506 Oracle DBA Code Examples

Step 4: Adding Nodes at the Oracle RAC Database Layer
Step 5: Adding Database Instances to New Nodes
Using Enterprise Manager to Add Database Instances to New Nodes
Using DBCA in Interactive Mode to Add Database Instances to New Nodes
1. Start dbca in rac1:
$ORACLE_HOME/ bi n/ dbca &
2. Follow: Real Application Cluster-> Instance Management-> Add Instanc-> Select RAC
database-> Next-> Enter the Instance Name, select node-> Enter service info->
$CRS_HOME/ bi n/ cr s_st at - t

sr vct l st ar t ser vi ce - d r ac - s " hr ser v" - i r ac3
sr vct l st ar t ser vi ce - d r ac - s " oeser v" - i r ac3
Using DBCA in Silent Mode to Add Database Instances to New Nodes
Page 507 Oracle DBA Code Examples

Deleting Nodes and Instances on UNIX-Based Systems
Option 1: Quick-Start Node and Instance Deletion Procedures
Oracle Database home is always deleted first, then the Clusterware home is deleted.
Quick-Start node and instance deleteion procedure could be the convenient option when
you want to delete one or two nodes.
Deleting an Oracle Home with RAC from an Existing Node
The target here is to delete the Oracle database home. OUI can be used in interactive or
silent mode to acheive this target. Interactive method is shown here.
The example below assumes that you remove Oracle Database home from a node named
rac2:
1. Remove rac2 from the available or preferred list of all the services:
# l i st t he ser vi ces
sr vct l st at us ser vi ce - d r ac

# st op t he ser vi ces i n r ac2
sr vct l st op ser vi ce - d r ac - s hr ser v - i r ac2
sr vct l st op ser vi ce - d r ac - s oeser v - i r ac2

# check r ac2 i s used by any ser vi ce
sr vct l conf i g ser vi ce - d r ac

# my ser vi ces avai l abl e onl y i n t he r emai ni ng nodes
sr vct l modi f y ser vi ce - d r ac - s hr ser v - n - i r ac1
sr vct l modi f y ser vi ce - d r ac - s oeser v - n - i r ac1

# conf i r m
sr vct l conf i g ser vi ce - d r ac
2. From rac1, remove DB instance in rac2 using DBCA (OEM can also be used). Follow the
steps as in the sub-section "Using DBCA in Interactive Mode to Delete Database
Instances from Existing Nodes". To confirm:
cr s_st at - t
3. Delete ASM instance as described in the sub-section "ASM Instance Clean-Up Procedures
for Node Deletion".
4. Use NETCA to remove the listener. To confirm:
cr s_st at - t
5. Stop nodeapps from rac2 then remove them.
su -
cd / u01/ cr s/ bi n
. / sr vct l st op nodeapps - n r ac2
. / cr s_st at - t
. / sr vct l r emove nodeapps - n r ac2
6. On rac2, to make the OUI remove the software home only from rac2:
su - or acl e
echo $ORACLE_HOME
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
Page 508 Oracle DBA Code Examples

cd $ORACLE_HOME/ oui / bi n
. / r unI nst al l er - updat eNodeLi st ORACLE_HOME=$ORACLE_HOME " CLUSTER_NODES={r ac2}"
l ocal
7. Run OUI from the home and deinstall this home. Make sure that you choose the home to
be removed and not just the products under that home.
. / r unI nst al l er &
8. On rac1, run the following command where "CLUSTER_NODES={remaining_list}":
echo $ORACLE_HOME
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
cd $ORACLE_HOME/ oui / bi n
. / r unI nst al l er - updat eNodeLi st ORACLE_HOME=$ORACLE_HOME " CLUSTER_NODES={r ac1}"
Deleting an Oracle Clusterware Home from an Existing Node
The target here is to delete the Oracle Clusterware home from a node. OUI can be used in
interactive or silent mode to acheive this target. Interactive method is shown here.
The example below assumes that you remove Oracle Clusterware home from a node named
as rac2:
1. Makre sure Oracle Database home was removed before going on the clusterware home
deletion procedure.
2. If you ran the Oracle Interface Configuration Tool (OIFCFG) with the -global flag during
the installation, then skip this step. Otherwise, from a node that is going to remain in
your cluster, from the CRS_home/bin directory, run the following command:
. / oi f cf g del i f node r ac2
3. Obtain the remote port number, which you will use in the next step, using the following
command from the CRS_HOME/opmn/conf directory:
echo $CRS_HOME
expor t CRS_HOME=/ u01/ cr s
cd $CRS_HOME/ opmn/ conf
cat ons. conf i g
4. In rac1: run the Oracle Notification Service (RACGONS)
cd $CRS_HOME/ bi n
./racgons remove_config rac2:remote_port
5. On rac2 as root:
su -
expor t CRS_HOME=/ u01/ cr s
$CRS_HOME/ i nst al l / r oot del et e. sh
6. On rac1 as root: run ./rootdeletenode.sh node2,node2-number
su -
expor t CRS_HOME=/ u01/ cr s
# i f you want t o i dent i f y t he node number
$CRS_HOME/ bi n/ ol snodes - n

$CRS_HOME/ i nst al l / r oot del et enode. sh r ac2, 2
$CRS_HOME/ bi n/ ol snodes - n
Page 509 Oracle DBA Code Examples

7. On rac2:
su - or acl e
expor t CRS_HOME=/ u01/ cr s
cd $CRS_HOME/ oui / bi n
. / r unI nst al l er - updat eNodeLi st ORACLE_HOME=$CRS_HOME " CLUSTER_NODES={r ac2}"
CRS=TRUE - l ocal
8. On rac2, de-install the Oracle Clusterware using the OUI:
cd $CRS_HOME/ oui / bi n
. / r unI nst al l er &
9. On rac1, where "CLUSTER_NODES={remaining_nodes_list}":
su - or acl e
cd $CRS_HOME/ oui / bi n
. / r unI nst al l er - updat eNodeLi st ORACLE_HOME=$CRS_HOME " CLUSTER_NODES={r ac1}"
CRS=TRUE

cr s_st at - t
ol snodes - n
Option 2: Detailed Node and Instance Deletion Procedure
Detailed node and instance deleteion procedure could be more convenient when you want
to delete high number of nodes.
Step 1: Deleting DB Instances from Real Application Clusters Databases
Using Enterprise Manager to Delete Database Instances from Existing Nodes
Follow the links: Cluster Database Home page-> Maintenance-> Deployments section->
Delete Instance-> Deletion Wizard starts
Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes
1. On rac1, open DBCA from Oracle home.
2. On the DBCA Welcome page select Oracle Real Application Clusters Database, click
Next
3. On the DBCA Operations page, select Instance Management, click Next
4. On the Instance Management page, Select Delete Instance, click Next
5. On the List of Cluster Databases page, select the Oracle RAC database. Enter a
SYSDBA user name and password. Click Next
6. On the List of Cluster Database Instances page, select an instance to delete and click
Finish.
7. If you have services assigned to this instance, then the DBCA Services Management
page appears. Use this feature to reassign services from this instance to other
instances in the cluster database.
8. On the Summary page and click OK.
9. DBCA removes the instance and the instance's Oracle Net configuration.
10. After completion, exit DBCA
Page 510 Oracle DBA Code Examples

Using DBCA in Silent Mode to Delete Instance from Existing Nodes
1. General Syntax:
dbca -silent -deleteInstance [-nodeList node] -gdbName gdbname instanceName
instname -sysDBAUserName sysdba -sysDBAPassword password
- - i f r unni ng f or mr ac2:
dbca - si l ent - del et eI nst ance - gdbName r ac - i nst anceName r ac2 - sysDBAUser Name
sys - sysDBAPasswor d syspasswor d

- - i f r unni ng f r omr ac1:
dbca - si l ent - del et eI nst ance - nodeLi st r ac2 - gdbName r ac - i nst anceName r ac2 -
sysDBAUser Name sys - sysDBAPasswor d syspasswor d
Step 2: Deleting Nodes from Real Application Clusters Databases
The example assumes rac2 is the node to delete and that Oracle home is local (not shared).
1. If there are instances on the node that you want to delete, then perform one of the
procedures in the previous section Setp1.
2. Perform ASM clean up procedure as described in the sub-section "ASM Instance Clean-
Up Procedures for Node Deletion".
3. Use NETCA to remove the listener from rac2.
4. On rac2:
cd $ORACLE_HOME/ oui / bi n
r unI nst al l er - updat eNodeLi st ORACLE_HOME=$ORACLE_HOME CLUSTER_NODES=" " l ocal
5. Run OUI from the home and deinstall this home. Make sure that you choose the home to
be removed and not just the products under that home.
. / r unI nst al l er &
6. On rac1, where "CLUSTER_NODES={node_list}":
r unI nst al l er - updat eNodeLi st ORACLE_HOME=Or acl e_home " CLUSTER_NODES={r ac1}"
7. Remove node-specific interface configurations:
# t o obt ai n por t number
echo $CRS_HOME
expor t CRS_HOME=/ u01/ cr s
cd $CRS_HOME/ opmn/ conf
cat ons. conf i g

r acgons r emove_conf i g r ac2: <r emot e_por t >
oi f cf g del i f - node r ac2
8. On rac2, disable the Oracle Clusterware applications that are on the node:
echo $CRS_HOME
expor t CRS_HOME=/ u01/ cr s
cd $CRS_HOME/ i nst al l
# I f t he ocr . l oc f i l e i s on a l ocal f i l e syst em
r oot del et e. sh r emot e noshar edvar
# I f t he ocr . l oc f i l e i s on a shar ed f i l e syst em
r oot del et e. sh r emot e shar edvar
9. On any remaining node in the cluster (rac1), to delete the nodes from the Oracle cluster
and to update the Oracle Cluster Registry (OCR):
Page 511 Oracle DBA Code Examples

su -
echo $CRS_HOME
expor t CRS_HOME=/ u01/ cr s
# t o di spl ay node number s
$CRS_HOME/ bi n/ ol snodes - n.

# t o del et e t he node
# gener al synt ax: r oot del et enode. sh node1, node1- number , node2, node2- number , . . .
$CRS_HOME/ i nst al l / r oot del et enode. sh r ac2, 2
10. On rac2:
$CRS_HOME/ oui / bi n/ r unI nst al l er - updat eNodeLi st ORACLE_HOME=$CRS_HOME
CLUSTER_NODES=" " l ocal CRS=t r ue
11. Run OUI from the home and deinstall this home. Make sure that you choose the home to
be removed and not just the products under that home.
$CRS_HOME/ oui / bi n/ r unI nst al l er &
12. On rac1, where "CLUSTER_NODES={ramining_nodelist}":
r unI nst al l er - updat eNodeLi st ORACLE_HOME=CRS_home " CLUSTER_NODES=r ac1"
13. Verify node removal:
cl uvf y comp cr s - n al l [ - ver bose]
ASM Instance Clean-Up Procedures for Node Deletion
The target here is to remove ASM instance from a node.
1. Stop, if any, all of the databases that use the ASM instance. If you follow this procedure
as part of a node deletion, the Db instance must have been removed by this step.
2. On rac2:
sr vct l st op asm- n r ac2

sr vct l r emove asm- n r ac2

sr vct l conf i g asm- n r ac2

sr vct l conf i g asm- n r ac1

cr s_st at - t
3. On rac2:
r m- r $ORACLE_BASE/ admi n/ +ASM
r m- f $ORACLE_HOME/ dbs/ *ASM*

Page 512 Oracle DBA Code Examples

Adding and Deleting Nodes and Instances on
Windows-Based Systems
Page 513 Oracle DBA Code Examples

Cloning Oracle Clusterware and RAC Software in Grid Environments
Quick-Start Node and Database Instance Addition and Deletion Procedures
Adding an Oracle Clusterware Home to a New Node
Adding an Oracle Home with RAC to a New Node
Deleting an Oracle Home with RAC from an Existing Node
Deleting an Oracle Clusterware Home from an Existing Node
Detailed Node and Database Instance Addition and Deletion Procedures
Overview of Node Addition Procedures
Step 1: Connecting New Nodes to the Cluster
Making Physical Connections
Installing the Operating System
Verifying the Installation with the Cluster Verification Utility
Checking the Installation
Step 2: Extending Oracle Software to New Nodes at the Oracle Clusterware
Step 3: Preparing Storage on New Nodes
Raw Device Storage Preparation for New Nodes
Step 4: Adding Nodes at the Oracle RAC Database Layer
Step 5: Adding Database Instances to New Nodes
Using Enterprise Manager to Add Database Instances to New Nodes
Using DBCA in Interactive Mode to Add Database Instances to New Nodes
Using DBCA in Silent Mode to Add Database Instances to New Nodes
Connecting to iSQL*Plus after Adding a Node
Page 514 Oracle DBA Code Examples

Adding Nodes that Already Have Clusterware and Oracle Software to a
Cluster
Overview of Node Deletion Procedures
Step 1: Deleting Instances from Real Application Clusters Databases
Using Enterprise Manager to Delete Database Instances from Existing Nodes
Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes
Using DBCA in Silent Mode to Delete Instance from Existing Nodes
Step 2: Deleting Nodes from Real Application Clusters Databases
Step 3: ASM Instance Clean-Up Procedures for Node Deletion
Page 515 Oracle DBA Code Examples

Monitoring Performance
RAC Common Tuning Tips
Application tuning is often the most beneficial
Resizing and tuning the buffer cache
Increasing sequence caches to a high value: to avoid index leaf contention caused by high
or batch inserts.
Reducing long full-table scans in OLTP systems: to reduce GCS requests.
Using Automatic Segment Space Management
Using partitioning to reduce interinstance traffic
Avoiding unnecessary parsing
Minimizing locking usage
Removing unselective indexes
Configuring interconnect properly
Instance Recovery and RAC
_FAST_START_INSTANCE_RECOVERY_TARGET initialization parameters controls the time in
seconds from the start of instance recovery to the time when GCD is open for lock
requests.
If FAST_START_MTTR_TARGET is also configured, the more aggressive will be used.
Practically, using either of them is useless because one of the surviving instances is doing
the recovery. You can however consider the following:
o Increase PARALLEL_EXECUTION_MESSAGE_SIZE (message size for parallelism and its
buffer taken from shared pool) from its default of 2,148 bytes to 4 KB or 8 KB.
o Set PARALLEL_MIN_SERVERS to CPU_COUNT-1. This will prespawn recovery slaves at
startup time.
o Using asynchronous I/O is one of the most crucial factors in recovery time. The first-
pass log read uses asynchronous I/O.
o Instance recovery uses 50 percent of the default buffer cache for recovery buffers. If
this is not enough, you will see it in the alert.log. In that case, increase the size of
your default buffer cache.
Global Cache Wait Events
gc current/cr request
gc [current/cr] [2/3]-way
gc [current/cr] block busy
gc [current/cr] grant 2-way: grant occurs before I/O
gc current grant busy
gc [current/cr] [block/grant] congested: congested means it is internally > 1ms
gc [current/cr] [failure/retry]
gc buffer busy
Page 516 Oracle DBA Code Examples

Monitoring Performance in Enterprise Manager
Using the Cluster Database Performance Page
Chart: Cluster Host Load Average
Desc.: load on CPU in all cluster nodes
Vertical: No of CPUs in all the cluster
Notice : If the load average is higher than the average of the total number of CPUs across all
of the hosts in the cluster, then too many processes are waiting for CPU resources.

Chart: Global Cache Block Access Latency
Desc.: end-to-end elapsed time or latency for a block request
Vertical: latency in ms
Notice : - interconnect delay - unoptimized SQL plans to acheive local cache hit ration. - to
resolve: drill down to the Cluster Cache Coherency page

Chart: Global Cache Block Transfer Rate
Desc.: number of data blocks received by all instances
Notice: drid down till segment type

Chart: Average Active Sessions
Desc.: average number of active sessions per wait class.
Notice: Consider tuning the database, if the Average Active Sessions chart displays a large
number of sessions waiting, indicating internal contention, and throughput the Database
Throughput charts is low.

Chart : Database Throughput Charts
Desc. : summarize any contentions that appear in the Average Active Sessions chart
Notes : drill down to instance level then top consumers

Chart : Top Segments Page
Desc. : to identify hot tables or indexes in a database
Notes : tracks the number of CR and current blocks received by an object.

Chart : Database Locks Page
Desc. : to determine whether multiple instances are holding locks for the same object.
Using the Cluster Database Instance Performance Page
To access it, Performance tab-> instance name in the bottom.
Instance-level statistics including generating ADDM and ASH reports.
AWR: gather statistics about each individual instance in the RAC and not the entire database.
ADDM Report: create a new AWR snapshot and run ADDM on this and the previous snapshot.
exec dbms_advi sor . set _def aul t _t ask_par amet er ( ' ADDM' , ' DB_ACTI VI TY_MI N' , 30)
exec dbms_wor kl oad_r eposi t or y. modi f y_snapshot _set t i ngs( i nt er val =>600)

exec dbms_wor kl oad_r eposi t or y. cr eat e_snapshot

Page 517 Oracle DBA Code Examples

ASH Report: create a performance data report of the database based on session-sampling
data over a specified period of time. This report is very useful for diagnosing small (five- to
ten-minute) performance spikes that might be averaged out and consequently hidden or
minimized by other issues in the 1-hour AWR report.
Using the Cluster Performance Page
With this information, you can determine whether resources need to be added, suspended, or
redistributed.
Using the Cluster Interconnects Page
Home page-> Interconnect Findings
Home page-> Performance-> Cluster Cache Coherency-> Interconnects
This page helps determine the load added by individual instances and databases on the
interconnect. Sometimes you can immediately identify interconnect delays that are due to
applications that are outside Oracle Database.
Page 518 Oracle DBA Code Examples

Making Applications Highly Available Using Oracle
Clusterware
Note: You can install the Oracle Clusterware high availability Application Programming
Interface (API) from the Oracle Database 10g release 10.2 client installation media.
Note: Your Listener.ora file should contain one entry for the virtual internet protocol (VIP)
address, using the VIP's name, and another entry for the physical host, by IP address not
name.
Making an Application Highly Available Examples
Example1: Making an Application Highly Available
If the application is accessed by network, define a VIP per application.
VIP is failed over to another node together with the application(s).
From there, clients can still connect through the VIP.

1. Create an application profile by editing an ASCII file or by running the crs_profile command.
# file name format resource_name.cap
save file in
$CRS_HOME\crs\profile for root user
$CRS_HOME\crs\public for non-root user

# Required Ones
# resource-specific script (start, stop or check will be passed by crs)
ACTION_SCRIPT
# application name
NAME
# resource type (must be APPLICATION)
TYPE
# ordered list of cluster nodes (use names as listed by olsnodes)
HOSTING_MEMBERS

# Optional Ones
# description of the resource
DESCRIPTION='myapplication'
# list of required resources (must be registered)
REQUIRED_RESOURCES
# placement policy: (balanced), favored, or restricted
PLACEMENT
# when 1 (0), crs re-evaluates the placement of a resource
# during addition or restart of a cluster node
ACTIVE_PLACEMENT=0
# when 1 (0), it atuo-restarts on system reboot
AUTO_START=1
# check intervals in seconds (60)
Page 519 Oracle DBA Code Examples

CHECK_INTERVAL
# failover interval (0)
FAILOVER_DELAY
# interval (s) during which crs applies the failure threshold
FAILURE_INTERVAL
# (max 20) number of failures within FAILURE_INTERVAL after which
# the resource is marked offline
FAILURE_THRESHOLD
# space-delimited liste of resource used during placement decisions
OPTIONAL_RESOURCES
# restart attempts before relocate (1)
RESTART_ATTEMPTS
# maintained by crs
RESTART_COUNT
# timeout in seconds the script needs before returning an error (60)
SCRIPT_TIMEOUT
START_TIMEOUT
STOP_TIMEOUT
# application up-time to be considered stable by crs
UPTIME_THRESHOLD
# exampl e 1
or acl e$cr s_pr of i l e - cr eat e post man - t appl i cat i on - B
/ opt / emai l / bi n/ cr s_post man \
- d " Emai l Appl i cat i on" - r net wor k1 - l appl i cat i on2 \
- a post man. scr - o ci =5, f t =2, f i =12, r a=2

# i n $CRS_HOME/ cr s/ publ i c
# wi l l gener at e f i l e post man. cap cont ai ni ng:
NAME=post man
TYPE=appl i cat i on
ACTI ON_SCRI PT=/ or acl e/ cr s/ scr i pt / post man. scr
ACTI VE_PLACEMENT=0
AUTO_START=0
CHECK_I NTERVAL=5
DESCRI PTI ON=emai l app
FAI LOVER_DELAY=0
FAI LURE_I NTERVAL=12
FAI LURE_THRESHOLD=2
HOSTI NG_MEMBERS=
OPTI ONAL_RESOURCES=appl i cat i on2
PLACEMENT=bal anced
REQUI RED_RESOURCES=net wor k1
RESTART_ATTEMPTS=2
SCRI PT_TI MEOUT=60
. . .
# and scr i pt f i l e post man. scr

# Cr eat e Appl i cat i on VI P
# cr eat e net wor k1 VI P addr ess appl i cat i on
# wher e et h0 i s t he publ i c net wor k ni c
# 138. 3. 83. 78 i s t he vi p addr ess
cr s_pr of i l e cr eat e net wor k1 - t appl i cat i on \
Page 520 Oracle DBA Code Examples

- a $CRS_HOME/ bi n/ usr vi p \
- o oi =et h0, ov=138. 3. 83. 78, on=255. 255. 240. 0

# as or acl e, r egi st er net wor k1
or acl e$cr s_r egi st er net wor k1

# change t he owner of t he r esour ce
cr s_set per mnet wor k1 o r oot

# enabl e or acl e user t o r un t he scr i pt
cr s_set per mnet wor k1 u user : or acl e: r - x

# as or acl e st ar t s t he vi p
cr s_st ar t net wor k1
2. Register the application profile using the crs_register command.
cr s_r egi st er post man
# I f you modi f y post man pr of i l e, t hen updat e t he OCR:
cr s_r egi st er - u post man
3. Run the crs_start command to initiate the application profile and then the Oracle
Clusterware runs the action program command that you have included in the profile to start
your application.
cr s_st ar t post man

# t o st ar t an appl i cat i on r esour ce, even i f one of t he r equi r ed r esour ces
# i s of f l i ne:
cr s_st ar t - f post man
4. The Oracle Clusterware periodically runs the action program command to check an
applications status.
5. In the event of a check or node failure, the Oracle Clusterware recovers the applications
either by restarting it on the current node or by relocating the application to another node. To
manually relocate the application and its resources to another node:
# t he appl i cat i on and i t s r equi r ed r esour ces must be of f l i ne
cr s_r el ocat e post man - c r ac2
6. If you run the crs_stop command to stop the application, then the Oracle Clusterware runs
the action program command to stop it.
cr s_st op post man

# t o st op an appl i cat i on t hat i s r equi r ed by an onl i ne r esour ce
cr s_st op - f post man
Example2: Making an Application Highly Available
/ * Maki ng xcl ock pr ogr amhi ghl y avai l abl e */

#
# 1) cr eat e t he act i on scr i pt f i l e
# cr eat e f ol l owi ng scr i pt i n bot h nodes ( i n $CRS_HOME/ cr s/ scr i pt )
# make t he f i l e execut abl e
# you can t hen t est i t by passi ng st ar t st op and check

Page 521 Oracle DBA Code Examples

su -
expor t CRS_HOME=/ u01/ cr s
vi $CRS_HOME/ cr s/ scr i pt / cr scl ock_act i on. scr
chmod 777 $CRS_HOME/ cr s/ scr i pt / cr scl ock_act i on. scr

#! / bi n/ bash
# st ar t / st op/ check scr i pt f or xcl ock exampl e
# t he scr i pt assumes xcl ock i s t her e
# and DI SPLAY var i abl e i s set
APP=/ usr / X11R6/ bi n/ xcl ock
BI N_NAME=xcl ock
LOG_DI R=/ t mp

expor t DI SPLAY=: 0. 0

echo `dat e +" %M: %S" ` $0 $* $$>>/ t mp/ myl og. l og

PI D1=`ps - ef | gr ep $BI N_NAME | gr ep - v gr ep | gr ep - v xcl ock_app | awk ' {
pr i nt $2 }' `

case $1 i n
' st ar t ' )
i f [ " $PI D1" ! = " " ]
t hen
st at us_p1=" r unni ng"
el se
i f [ - x $APP ]
t hen
#umask 002
${APP} &
PI D1=`ps - ef | gr ep $BI N_NAME | gr ep - v gr ep | gr ep - v xcl ock_app | awk
' { pr i nt $2 }' `
echo `dat e +" %M: %S" ` $* $PI D1 $USER>>/ t mp/ myl og. l og
st at us_p1=" st ar t ed"
el se
echo `basename $0`" : $APP: Execut abl e not f ound"
f i
f i
echo " $APP: $st at us_p1"
; ;
' st op' )
i f [ " ${PI D1}" ! = " " ]
t hen
ki l l - 9 ${PI D1} && echo " $APP ki l l ed"
el se
echo " $BI N_NAME: no r unni ng Pr ocess! "
f i
; ;
' check' )
i f [ " $PI D1" ! = " " ]
t hen
echo " r unni ng"
exi t 0
el se
echo " not r unni ng"
echo `dat e +" %M: %S" ` $0 $* " ERR" >>/ t mp/ myl og. l og
exi t 1
Page 522 Oracle DBA Code Examples

f i
; ;
*)
echo " Usage: " `basename $0`" {st ar t | st op| check}"
; ;
esac


#
# 2) cr eat e appl i cat i on r esour ce pr of i l e named myCl ock
# i f you copy past e, f i x t he hyphen i ssue
su -
$CRS_HOME/ bi n/ cr s_pr of i l e - cr eat e myCl ock - t appl i cat i on - a
cr scl ock_act i on. scr - p f avor ed - h " r ac1- vi p r ac2- vi p" - o ci =5, r a=2

# check t he gener at ed f i l e
cat $CRS_HOME/ cr s/ pr of i l e/ myCl ock. cap

#
# 3) Regi st er t he r esour ce ( i n ONE node onl y)
# must be done as r oot and t hen per mi ssi on i s gr ant ed t o or acl e
su -
$CRS_HOME/ bi n/ cr s_r egi st er myCl ock
$CRS_HOME/ bi n/ cr s_set per mmyCl ock - u user : or acl e: r - x
$CRS_HOME/ bi n/ cr s_st at myCl ock
$CRS_HOME/ bi n/ cr s_st at - t

#
# 4) St ar t t he r esour ce
# as or acl e
su - or acl e
$CRS_HOME/ bi n/ cr s_st ar t myCl ock
$CRS_HOME/ bi n/ cr s_st at - t

Managing Automatic Oracle Clusterware Resource Operations for Action Scripts
/ * Pr event i ng Aut omat i c Dat abase I nst ance Rest ar t s */
I n t he appl i cat i on pr of i l e, set AUTO_START t o ( l ower case onl y) :
al ways, r est or e, never

/ * Aut omat i cal l y Manage Rest ar t At t empt s Count er f or Resour ces */
Thi s i s cont r ol l ed by t he at t r i but es RESTART_ATTEMPTS and RESTART_COUNT.
Displaying Clusterware Application and Application Resource Status Information
# application status
crs_stat postman

# all resources status
crs_stat -t
# specific resource status
crs_stat -t ora.rac1.ASM1.asm

# stats about the resources ( R=Restart, F=Fail)
crs_stat -v

# appl i cat i on pr of i l e
cr s_st at - p
Page 523 Oracle DBA Code Examples

cr s_st at - p ora.rac1.ASM1.asm
Unregistering Applications and Application Resources
su -
$CRS_HOME/ bi n/ cr s_unr egi st er post man
$CRS_HOME/ bi n/ cr s_st at - t
Page 524 Oracle DBA Code Examples

RAC Troubleshooting
Diagnosing the Oracle Clusterware High Availability Components
Debugging Recommnedation
Always make sure that your nodes have exactly the same system time. Use NTP.
Clusterware Log Files and the Unified Log Directory Structure
# Cl ust er Ready Ser vi ces Daemon ( cr sd)
# I t i s ar chi ved ever y 10 MB ( cr sd. l 01, cr sd. l 02, )
$CRS_HOME/ l og/ host name/ cr sd

# Or acl e Cl ust er Regi st r y ( OCR)
$CRS_HOME/ l og/ host name/ cl i ent

# Cl ust er Synchr oni zat i on Ser vi ces ( CSS)
# i s ar chi ved ever y 20 MB ( cssd. l 01, cssd. l 02, )
$CRS_HOME/ l og/ host name/ cssd

# Event Manager ( EVM)
$CRS_HOME/ l og/ host name/ evmd

# RACG Log Fi l es
$CRS_HOME/ l og/ host name/ r acg
$ORACLE_HOME/ l og/ host name/ r acg

# SRVM ( sr vct l ) and OCR ( ocr dump, ocr conf i g, ocr check) l ogs
$ORA_CRS_HOME/ l og/ <host name>/ cl i ent

# cr s al er t s
$ORA_CRS_HOME/ l og/ <host name>/ al er t <nodename>. l og
Dynamic Debugging
/ * t o Enabl e Debuggi ng */
# as r oot
# f or t he Or acl e Cl ust er war e
cr sct l debug l og cr s " CRSRTI : 1, CRSCOMM: 2"

# f or EVM
cr sct l debug l og evm" EVMCOMM: 1"

# f or r esour ces ( 1 i s t he debuggi ng l evel )
cr sct l debug l og r es " r esname: 1"
# exampl e:
cr sct l debug l og r es " or a. r ac1. vi p: 1"
Component Level Debugging
# t o enabl e debuggi ng f or al l of t he modul es
# wher e l evel 1 ( l east ) t o 5 ( max)
set ORA_CRSDEBUG_ALL <l evel >

# t o enabl e t r aci ng f or a speci f i c sub- modul e
Page 525 Oracle DBA Code Examples

set ORA_CRSDEBUG_modul ename
# t o l i st t he sub- modul es
# wher e modul e i s cr s, evm, or css
cr sct l l smodul es <modul e>
Oracle Clusterware Shutdown and Startup
su -
cr sct l st op cr s
cr sct l st ar t cr s
Enabling and Disabling Oracle Clusterware Daemons
su -
cr sct l enabl e cr s
cr sct l di sabl e cr s
Diagnostics Collection Script
Generates the following files in the local directory:
basDat a_<host name>. t ar . gz
cr sDat a _<host name>. t ar . gz
ocr Dat a _<host name>. t ar . gz
or aDat a _<host name>. t ar . gz
# when asked by Or acl e suppor t
su -
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1
expor t ORA_CRS_HOME=/ u01/ cr s1020
expor t ORACLE_BASE= =/ u01/ app/ or acl e
cd $ORA_CRS_HOME/ bi n
$CRS_HOME/ bi n/ di agcol l ect i on. pl - col l ect
The Oracle Clusterware Alerts
# can be f ound i n:
$CRS_Home/ l og/ host name/ al er t host name. l og
Resource Debugging
# met hod 1: wher e 1 i n t he f ol l owi ng exampl e i s t he debuggi ng l evel
cr sct l debug l og r es " or a. node1. vi p: 1"

# met hod 2:
expor t USER_ORA_DEBUG=1
# . . t hen i ssue cr sct l st ar t , st op, or check
Checking the Health of the Clusterware
cr sct l check cr s
Troubleshooting the Oracle Cluster Registry

Troubleshooting Hostname Changes and CSS
If you change the host name for ASM, then the Oracle CSS daemon will not start. In order to
counter this problem, please use the following steps:
Page 526 Oracle DBA Code Examples

Login as the root user
Run localconfig delete to deconfigure CSS. This will remove any configuration related files
on the system that referenced the old host name.
Run localconfig add to reconfigure CSS using the new host name.
Enabling Additional Tracing for Real Application Clusters High Availability

Diagnosing Oracle Real Application Clusters Components

Where to Find Files for Analyzing Errors

Using Instance-Specific Alert Files in Real Application Clusters

Enabling Tracing for Java-Based Tools and Utilities in Real Application Clusters

Resolving Pending Shutdown Issues

Using the Cluster Verification Utility
Cluster Verify Locations
Download it from OTN
Oracle software DVD:
. / cl uvf y/ r uncl uvf y. sh
Oracle Clusterware home:
$ORA_CRS_HOME/ bi n/ cl uvf y
Oracle Home:
$ORACLE_HOME/ bi n/ cl uvf y
Cluster Verify Stages
You can list verifiable stages with the cl uvf y st age - l i st
Valid stage options and stage names are (ordered):
- post hwos: Post check f or har dwar e and oper at i ng syst em
- pr e cf s: Pr echeck f or OCFS set up
- post cf s: Post check f or OCFS set up
- pr e cr si nst : Pr echeck f or CRS i nst al l at i on
- post cr si nst : Post check f or CRS i nst al l at i on
- pr e dbi nst : Pr echeck f or dat abase i nst al l at i on
- pr e dbcf g: Pr echeck f or dat abase conf i gur at i on
Page 527 Oracle DBA Code Examples

Cluster Verify Components
You can list verifiable CVU components with the cluvfy comp -list
Verifiable CVU components:
noder each: Checks r eachabi l i t y bet ween nodes
nodecon: Checks node connect i vi t y
cf s: Checks Or acl e Cl ust er Fi l e Syst emi nt egr i t y
ssa: Checks shar ed st or age accessi bi l i t y
space: Checks space avai l abi l i t y
sys: Checks mi ni mumsyst emr equi r ement s
cl u: Checks cl ust er i nt egr i t y
cl umgr : Checks cl ust er manager i nt egr i t y
ocr : Checks OCR i nt egr i t y
cr s: Checks CRS i nt egr i t y
nodeapp: Checks node appl i cat i ons exi st ence
admpr v: Checks admi ni st r at i ve pr i vi l eges
peer : Compar es pr oper t i es wi t h peer s
CVU Component Verification Examples
#ver i f y t he mi ni mal syst emr equi r ement s on t he nodes bef or e i nst al l i ng
Cl ust er war e
cl uvf y comp sys - n node1, node2 - p cr s - ver bose


#check t he syst emr equi r ement s bef or e i nst al l i ng RAC:
cl uvf y comp sys - n node1, node2 - p dat abase - ver bose


#ver i f y whet her st or age i s shar ed among t he nodes i n your cl ust er dat abase or
t o i dent i f y al l of t he st or age t hat i s avai l abl e on t he syst emand can be
shar ed acr oss t he cl ust er nodes:
cl uvf y comp ssa - n al l - s / dev/ sda1


#check t her e i s 5 GB f r ee i n al l nodes:
cl uvf y comp space - n al l - l / home/ pr oduct - z 5G


#can node1 r each node2:
cl uvf y comp noder each - n node2 - sr cnode node1


#checks whet her node1 and node2 can communi cat e t hr ough t he et h0 net wor k
i nt er f ace ( wi t hout i , al l i nt er f aces ar e checked) :
cl uvf y comp nodecon - n node1, node2 i et h0 - ver bose


#ver i f y user equi val ence f or al l t he nodes:
cl uvf y comp admpr v - n al l - o user _equi v - ver bose


#ver i f y exi st ence of node appl i cat i ons, namel y VI P, ONS, and GSD, on al l
t he nodes:
cl uvf y comp nodeapp - n al l - ver bose
Page 528 Oracle DBA Code Examples


#compar es al l t he nodes and det er mi nes whet her any di f f er ences exi st bet ween
t he val ues of pr esel ect ed pr oper t i es
cl uvf y comp peer - n al l ver bose | mor e
Understanding CVU Commands, Help, Output, and Nodelist Shortcuts

Performing Various CVU Tests

Known Issues for the Cluster Verification Utility

Page 529 Oracle DBA Code Examples

Part 8 Oracle RAC One Node
Page 530 Oracle DBA Code Examples

Installing Oracle 11g R2 RAC One Node on Linux 5
Overview
This installation implements Oracle RAC One Node. Oracle RAC One Node is a single instance
of Oracle RAC running on a node in a cluster. RAC One Node offers a form of virtualization
where multiple databases can be consolidated on the same physical server, sharing a common
pool of storage and server resources and thus reducing the physical IT footprints.
Note: The metalink document RAC Starter Kit and Best Practices (Linux) [ID 811306.1] is a
good source reference for this task.
Note: The procedure applies on 11.2.0.1. Version 11.2.0.2 provides simplified procedure.
Installation Environment
Emulation software: VMWare Workstation 7
RAC Node: 2 node with 2.5 GB RAM and 2 ethernet cards.
OS: Red Hat Linux Enterprise 5.2 for x86 32-bit
Required Software
Oracle Database 11g Release 2 for Linux x86 32-bit
Oracle Database 11g Release 2 Grid Infrastructure (11.2.0.1.0) for Linux x86 32-bit
RAC One Node patch# 9004119 : RACONENODE_p9004119_112010_LINUX.zip
Used Hardware
In the VMWare: create one virtual machine (rac1) with the following specs:
o 2.5 GB RAM
o Two ethernet cards: both can be configured as bridged or host-only in VMware.
o One local hardisk with 24 GB on SCSI 0:0.
o CPU Count: 2
o Create a folder in the same directory structure level as the parent folder containing the
created virtual machine. Give it a meaningful name like 'shared_disks'. Create in that
folder the following disks:
Disk1: of 3 GB. Allocate its disk space. It will be used for OCR and Voting
disk. Set it on controller SCSI 1:1
Disk2: of 4 GB. Allocate its disk space. It will be used for +Data. Set it on
controller SCSI 1:2
Disk3: of 2 GB. Allocate its disk space. It will be used for +Flash. Set it on
controller SCSI 1:3

Page 531 Oracle DBA Code Examples


Installation Plan
1. Preinstallation tasks
Hardware requirements
Software requirements
Environment configuration
2. Oracle Grid Infrastructure installation
3. Oracle Grid Infrastructure Patching
4. Checking Oracle Grid Infrastructure Status
5. Oracle Database 11g R2 Software Installation
6. Oracle Database 11g R2 Software Patching
7. Install EM Agent in cluster nodes (if required)
8. ASM Diskgroups Creation
9. RAC Database Creation
10. Initialize the Database to RAC One Node
11. Complete postinstallation tasks
12. Useful postinstallation tasks
Note: The installation is explained without GNS and IPMI
Note: For this installation we will be using ASM for Clusterware and Database storage
Page 532 Oracle DBA Code Examples

1. Preinstallation tasks
Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining
disks.
Note: for a production system, consider becoming an Oracle Unbreakable Linux customer
and register your server on the Unbreakable Linux Network.
o Configure the swap area in the local hardisk to have 3 GB disk space.
o Give the first ethernet card IP 192.0.2.100 and the second 172.0.2.100 and the
hostname r ac1. mydomai n. com. Define a gateway. If it does not exist, make it same as
the host IP address.
o Insall the following packages:
Desktop Environments
o GNOME Desktop Environment
Applications
o Graphical Internet (optional)
o Editors (optional)
Development
o Development Libraries
o Development Tools
Servers
o Do not select anything in this group.
Base System
o Administration Tools
o System Tools
Add the package 'sysstat' by clicking on the Details link
and selecting "sysstat - The sar an iostat system
monitoring commands." from the Optional Packages list.
X Window System
Complete the installation.
After the Installation compelets, RHEL 5.2 and below will hang on booting when it reaches
to "starting udev" line. To solve this problem, shutdown the Vmware machine and change
the CPU count and Core Count to only one. Implement the changes below, then shutdown
the machine, set CPU count back to 2 and startup the machine.
put the kernel command line parameters at the end of the "kernel" line:
vi / boot / gr ub/ gr ub. conf
add di vi der =10 cl ocksour ce=acpi _pm
For example: ker nel / vml i nuz- 2. 6. 18 . . cl ock=acpi _pmdi vi der =10
For Vmware machines, install VMWare tools and set it to synchronize its time with the
guest: vmwar et ool box. Alternatvily, you can use Oracle Cluster Time Synchronization
Service (ctssd) (metalink document 551704.1)
Install further packages:
# t o know di st r i but i on and ver si on of Li nux ( Red Hat Ent . 5. 2 used)
cat / et c/ i ssue
Page 533 Oracle DBA Code Examples

# t o know ker nel ver si on ( and i t s er r at a l evel ) ( 2. 6. 18- 92 or newer )
uname - r

# t o l i st mi ssed packages:
r pm- q - - qf ' %{NAME}- %{VERSI ON}- %{RELEASE} ( %{ARCH}) \ n' bi nut i l s \
compat - l i bst dc++- 33 \
el f ut i l s- l i bel f \
el f ut i l s- l i bel f - devel \
gcc \
gcc- c++ \
gl i bc \
gl i bc- common \
gl i bc- devel \
gl i bc- header s \
ksh \
l i bai o \
l i bai o- devel \
l i bgcc \
l i bst dc++ \
l i bst dc++- devel \
make \
sysst at \
uni xODBC \
uni xODBC- devel

# f or mi ssed packages, i nst al l t hem:
r pm- Uvh l i bai o- devel - 0. 3. 106- 3. 2. i 386. r pm
r pm- Uvh uni xODBC*

# Downl oad t he appr opr i at e ASMLi b RPMs f r omOTN.
# t o know t he ker nel ver i on: uname - r m
# I n t hi s case we need:
r pm- Uvh or acl easm- suppor t - 2. 1. 3- 1. el 5. i 386. r pm
r pm- Uvh or acl easm- 2. 6. 18- 92. el 5- 2. 0. 5- 1. el 5. i 686. r pm
r pm- Uvh or acl easml i b- 2. 0. 4- 1. el 5. i 386. r pm


# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
Check the hardware requirements
# Har dwar e Requi r ement s ( i n cl ust er nodes)
# At l east 1. 5 GB of physi cal memor y but pr act i cal l y 1. 5 i s not f i ne
gr ep MemTot al / pr oc/ memi nf o

# swap space: same as t he amount of physi cal memor y
gr ep SwapTot al / pr oc/ memi nf o

# t o di spl ay swap and memor y i n one command:
f r ee

# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
Page 534 Oracle DBA Code Examples

dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap

# 1 GB di sk space i n / t mp
df - h / t mp
# 8 GB of di sk space f or Or acl e sof t war e
df

The si ze of t he shar ed memor y shoul d be at l east t he gr eat er of
MEMORY_MAX_TARGET and MEMORY_TARGET f or each Or acl e i nst ance on t he comput er .
To det er mi ne t he amount of shar ed memor y avai l abl e, ent er t he f ol l owi ng
command:
# df - h / dev/ shm/
Create the required network configuration (rac2 will be created later):
o Public and Private interface names must be the same for all nodes.
o This private hostname does not need to be resolvable through DNS and should be
entered in the /etc/hosts file.
o SCAN VIPs must NOT be in the /etc/hosts file, it must be resolved by DNS. But here
I've defined it as a single IP address in the "/etc/hosts" file, which is wrong and will
cause the cluster verification to fail, but it allows me to complete the install without the
presence of a DNS.
o If you are using a DNS, Oracle recommends that you add lines to the /etc/hosts file on
each node, specifying the public IP, VIP and private addresses.
o If you configured the IP addresses in a DNS server, then, as the root user, change the
hosts search order in /etc/nsswitch.conf on all nodes as shown:
Old: host s: f i l es ni s dns
New: host s: dns f i l es ni s
o Then restart nscd daemon on each node: / sbi n/ ser vi ce nscd r est ar t
# Net wor k names Resol ut i on
# conf i gur e / et c/ host s i f no domai n ser ver i s used ( bot h nodes)
vi / et c/ host s
127. 0. 0. 1 l ocal host . l ocal domai n l ocal host
#et h0 - PUBLI C
192. 0. 2. 100 r ac1. mydomai n. comr ac1
192. 0. 2. 101 r ac2. mydomai n. comr ac2
#VI P
192. 0. 2. 102 r ac1- vi p. mydomai n. comr ac1- vi p
192. 0. 2. 103 r ac2- vi p. mydomai n. comr ac2- vi p
#et h1 - PRI VATE
172. 0. 2. 100 r ac1- pr i v
172. 0. 2. 101 r ac2- pr i v

# i n r eal pr oduct i on: t he f ol l wi ng shoul d not be t her e at al l
# SCAN: cl ust er _name- scan. GNS_subdomai n_name
192. 0. 2. 104 r ac- scan. mydomai n. comr ac- scan
Create and configure the required OS users and groups
Page 535 Oracle DBA Code Examples

Note: userid and groupid must be the same in all nodes. You can check them by i d
or acl e command.
# al l gr oup and user i ds on al l t he nodes must have i dent i cal i d
# Gr i d I nf r ast r uct ur e ( GI ) and t he Or acl e RDBMS home wi l l
# be i nst al l ed usi ng di f f er ent user s:
/ usr / sbi n/ gr oupadd - g 501 oi nst al l
/ usr / sbi n/ gr oupadd - g 502 dba
/ usr / sbi n/ gr oupadd - g 504 asmadmi n
/ usr / sbi n/ gr oupadd - g 506 asmdba
/ usr / sbi n/ gr oupadd - g 507 asmoper
/ usr / sbi n/ user add - u 501 - g oi nst al l - G asmadmi n, asmdba, asmoper gr i d
/ usr / sbi n/ user add - u 502 - g oi nst al l - G dba, asmdba or acl e

# set passwor ds
passwd or acl e
passwd gr i d

# make sur e nobody user exi st s ( i f not t her e, cr eat e i t user add nobody)
id nobody

# define the env variables for oracle user
vi /home/oracle/.bash_profile
# Oracle Settings
export EDITOR=vi
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR
ORACLE_HOSTNAME=rac1.mydomain.com; export ORACLE_HOSTNAME
ORACLE_UNQNAME=ron; export ORACLE_UNQNAME
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1; export ORACLE_HOME
ORACLE_SID=RON1; export ORACLE_SID
ORACLE_TERM=xterm; export ORACLE_TERM
PATH=/usr/sbin:$PATH; export PATH
PATH=$ORACLE_HOME/bin:$PATH; export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export
CLASSPATH

# shel l st ar t up f i l e
vi / et c/ pr of i l e
i f [ $USER = " or acl e" ] | | [ $USER = " gr i d" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
umask 022
f i


# f or C shel l
vi / et c/ csh. l ogi n
i f ( $USER = " or acl e" | | $USER = " gr i d" ) t hen
l i mi t maxpr oc 16384
l i mi t descr i pt or s 65536
endi f

# define the env variables for oracle user
Page 536 Oracle DBA Code Examples

vi /home/grid/.bash_profile
# Oracle Settings
export ORACLE_SID=+ASM1
export EDITOR=vi
export ORACLE_HOME=/u01/11.2.0/grid
export LD_LIBRARY_PATH=$ORACLE_HOME/lib
export PATH=$ORACLE_HOME/bin:/bin:/usr/bin:/usr/sbin:/usr/local/bin
Configure kernel parameters and shell limits
Note: If you make a mistake with a parameter setting and your system does not start,
then you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the
/etc/sysctl.conf file is not run.
# Ker nel Par amet er s
# t o t une t hme, r ef er t o met al i nk document 169706. 1
# Append t he f ol l owi ng t o t he / et c/ sysct l . conf f i l e as t he r oot user :
vi / et c/ sysct l . conf

# ker nel . shmmax not st at ed i n 11g R2 ( max: 4G) ( 169706. 1)
ker nel . shmmni = 4096
ker nel . sem= 250 32000 100 128
f s. ai o- max- nr = 1048576
f s. f i l e- max = 6815744
net . i pv4. i p_l ocal _por t _r ange = 9000 65500
net . cor e. r mem_def aul t = 262144
net . cor e. r mem_max = 4194304
net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 1048576

# t o t ake i mmedi at e ef f ect
/ sbi n/ sysct l - p

# User Shel l Li mi t s
# meml ock i s used t o i ncr ease t he per - pr ocess max l ocked memor y
vi / et c/ secur i t y/ l i mi t s. conf
gr i d sof t npr oc 2047
gr i d har d npr oc 16384
gr i d sof t nof i l e 1024
gr i d har d nof i l e 65536
or acl e sof t npr oc 2047
or acl e har d npr oc 16384
or acl e sof t nof i l e 1024
or acl e har d nof i l e 65536

vi / et c/ pam. d/ l ogi n
sessi on r equi r ed pam_l i mi t s. so
Create the required directories for the Oracle software:
# t o know i f t her e i s an exi st i ng or acl e i nvent or y
# from its output, ORACLE_BASE will be parent of oraInventory
more /etc/oraInst.loc
# t o i dent i f y exi st i ng Or acl e home di r ect or i es
mor e / et c/ or at ab

# Or acl e I nvent or y Di r ect or y
# as a r oot
mkdi r - p / u01/ app/ or aI nvent or y
chown - R gr i d: oi nst al l / u01/ app/ or aI nvent or y
Page 537 Oracle DBA Code Examples

chmod - R 775 / u01/ app/ or aI nvent or y

# Gr i d I nf r ast r uct ur e Home Di r ect or y
mkdi r - p / u01/ 11. 2. 0/ gr i d
chown - R gr i d: oi nst al l / u01/ 11. 2. 0/ gr i d
chmod - R 775 / u01/ 11. 2. 0/ gr i d

# Or acl e Base Di r ect or y
mkdi r - p / u01/ app/ or acl e
#needed t o ensur e t hat dbca i s abl e t o r un af t er t he r dbms i nst al l at i on
mkdi r / u01/ app/ or acl e/ cf gt ool l ogs
chown - R or acl e: oi nst al l / u01/ app/ or acl e
chmod - R 775 / u01/ app/ or acl e

# Or acl e RDBMS Home Di r ect or y
mkdi r - p / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chown - R or acl e: oi nst al l / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
chmod - R 775 / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
Disable screensavers after logging as root, oracle and grid:
o In Oracle Linux: Applications-> Preferences-> Screen Saver
In rac1, partition the disks:
Note: On a real life storage, you would create a single whole-disk partition with exactly 1 MB
offset on each LUN to be used as ASM Disk. In fdisk: u (to change units from cylinder to
sectors), n, p, 1, 2048, w.
# as a r oot , f or t he di sks / dev/ sdb . . / dev/ sdd
# conf i r mt hey ar e seen:
l s / dev/ sd*
#par t i t i on t he di sks:
f di sk / dev/ sdb
# answer s: " n" , " p" , " 1" , " Ret ur n" , " Ret ur n" , " p" and " w"
Not e: i f t he f ol l owi ng message appear s af t er t he " w" command:
WARNI NG: Re- r eadi ng t he par t i t i on t abl e f ai l ed wi t h er r or 16: Devi ce or
r esour ce busy, t hen you can avoi d r est ar t i ng t he machi ne by t he f ol l owi ng
command: par t pr obe

# t o make sur e par t i ons ar e cr eat ed
l s - l X / dev/ sd*
Shutdown rac1 and the Vmware machine soiftware. Then edit its VMware file of rac1 (with
vmx extensions) and add the following entry to allow sharing the disks (make sure the scsi
controller number is the one you used):
di sk. l ocki ng = " FALSE"
di skLi b. dat aCacheMaxSi ze = " 0"
di skLi b. dat aCacheMaxReadAheadSi ze = " 0"
di skLi b. dat aCacheMi nReadAheadSi ze = " 0"
di skLi b. dat aCachePageSi ze = " 4096"

scsi 1. shar edBus = " vi r t ual "

scsi 1: 1. devi ceType = " di sk"
scsi 1: 2. devi ceType = " di sk"
scsi 1: 3. devi ceType = " di sk"
Copy the folder containing rac1 into a new folder in the same directory structure level.
Let's name it "rac2". This will be the second node in the cluster.
Edit the VMware file of rac2 and edit the following: displayName = "rac2"
Page 538 Oracle DBA Code Examples

Open rac2, then perform:
o in a terminal issue: syst em- conf i g- net wor k- gui
o Remove the devices with the "%.bak" nicknames. To do this, highlight a device,
deactivate, then delete it.
o Highlight the "eth0" interface and click the "Edit" button. Change its IP addresses and
gate way: IP 192.0.2.101. Click on the "Hardware Device" tab and click the "Probe"
button.
o For eth1 set its ip address to 172.0.2.101. Do not define a gateway.
o In DNS tab, change hostname to rac2.mydomain.com.
o Activate the network cards.
In rac2, perform:
# change t he var i abl e i n t he f i l e
vi / home/ or acl e/ . bash_pr of i l e
# mar k t he f ol l owi ng:
# ORACLE_SI D=RON1; expor t ORACLE_SI D
ORACLE_HOSTNAME=r ac2. l ocal domai n; expor t ORACLE_HOSTNAME

vi / home/ gr i d/ . bash_pr of i l e
expor t ORACLE_SI D=+ASM2
Start rac1. Make sure the machines can see each other:
pi ng - c 3 r ac1
pi ng - c 3 r ac1- pr i v
pi ng - c 3 r ac2
pi ng - c 3 r ac2- pr i v
In rac1, configure ASM drivers:
Note: If you see that the shared disks are not synced between rac1 and rac2, one of the
things you can examine is to see if there is any "debug" command in any of the nodes'
vmx files. If you find one, shutdown the node, remove the command from the vmx file and
restart.
# as r oot
or acl easmconf i gur e - i

Def aul t user t o own t he dr i ver i nt er f ace [ ] : grid
Def aul t gr oup t o own t he dr i ver i nt er f ace [ ] : oinstall
St ar t Or acl e ASM l i br ar y dr i ver on boot ( y/ n) [ n] : y
Fi x per mi ssi ons of Or acl e ASM di sks on boot ( y/ n) [ y] : y
# I n al l nodes: Load t he ker nel modul e usi ng t he f ol l owi ng command:
/ usr / sbi n/ or acl easmi ni t
# I f you have any pr obl ems, make sur e you have t he cor r ect
# ver si on of t he dr i ver :
/ usr / sbi n/ or acl easmupdat e- dr i ver

# mar k t he shar ed di sks: ( one node)
/ usr / sbi n/ or acl easmcr eat edi sk DI SK1 / dev/ sdb1
/ usr / sbi n/ or acl easmcr eat edi sk DI SK2 / dev/ sdc1
/ usr / sbi n/ or acl easmcr eat edi sk DI SK3 / dev/ sdd1

# check t he di sks ar e mar ked and seen:
/ usr / sbi n/ or acl easml i st di sks

Page 539 Oracle DBA Code Examples

# i n ot her nodes:
/ usr / sbi n/ or acl easmscandi sks
/ usr / sbi n/ or acl easml i st di sks

#I f you need t o unmar k a di sk t hat was used i n a cr eat edi sk command:
/ usr / sbi n/ or acl easmdel et edi sk DI SK1
/ usr / sbi n/ or acl easmdel et edi sk DI SK2
/ usr / sbi n/ or acl easmdel et edi sk DI SK3
2. Oracle Grid Infrastructure installation
# i n r ac1: copy t he sof t war e i n a st agi ng f ol der
mkdi r - p / u01/ st age/ or a11gr 2gr i di nf r a
chown - R gr i d: oi nst al l / u01/ st age/ or a11gr 2gr i di nf r a
chmod - R 775 / u01/ st age/ or a11gr 2gr i di nf r a

mkdi r - p / u01/ st age/ or a11gr 2db
chown - R or acl e: oi nst al l / u01/ st age/ or a11gr 2db
chmod - R 775 / u01/ st age/ or a11gr 2db

# do not use cl uvf y because SSH was not conf i gur ed.


# i f you ar e i nst al l i ng 11. 2. 0. 2: i nst al l t he package cvuqdi sk- 1. 0. 9- 1
su -
cd / u01/ st age/ or a11gr 2gr i di nf r a/ st age/ cvu/ cv/ r emenv/
r pm- i v cvuqdi sk- 1. 0. 9- 1. r pm
# i nst al l i t i n r ac2 as wel l


# l unch OUI f r omt he cl ust er war e ( as grid f r omr ac1)
# i f l ogged i n i n Genome usi ng anot her user , l og out and l og i n as gr i d
cd / u01/ app/ st age/ or a11gr 2gr i di nf r a
. / r unI nst al l er

I nst al l at i on Opt i on
>Sel ect r adi o but t on ' I nst al l and Conf i gur e Gr i d I nf r ast r uct ur e f or a Cl ust er '
>Next

I nst al l at i on Type
>Sel ect ' Advanced I nst al l at i on'
>Next

Pr oduct Language
>Accept ' Engl i sh' as l anguage'
>Next

Gr i d Pl ug and Pl ay
>cl ust er name: r ac
>SCAN name: r ac- scan. mydomai n. com
>Make sur e ' Conf i gur e GNS' i s NOT sel ect ed
>Next

Cl ust er Node I nf or mat i on
>Add but t on
>Host name: r ac2. mydomai n. com
>Vi r t ual I P Name: r ac2- vi p. mydomai n. com
>OK
Page 540 Oracle DBA Code Examples


>" SSH Connect i vi t y" but t on
>Ent er t he passwor d
>Set up but t on
>Test but t on
>Next

Net wor k I nt er f ace Usage
>check t he publ i c and pr i vat e net wor ks ar e speci f i ed cor r ect l y
>Next

St or age Opt i on
>Sel ect ' Aut omat i c St or age Management ( ASM) '
>Next

Cr eat ASM Di sk Gr oup
>Di sk Gr oup Name: DGOCRVOTE ( 3GB di sk: Di sk1)
>Redundancy: ext er nal
>Next
NOTE: I f you see an empt y scr een f or you candi dat e di sks i t i s l i kel y t hat
ASMLi b has not been pr oper l y conf i gur ed. Tr y r econf i gur e t hem.
I f you ar e sur e t hat ASMLi b has been pr oper l y conf i gur ed cl i ck on ' Change
Di scover y Pat h' and pr ovi de t he cor r ect dest i nat i on.

ASM Passwor d
>Speci f y and conf or mt he passwor d you want t o use
>Next

Fai l ur e I sol at i on Suppor t
>Sel ect NOT t o use I PMI
>Next

Pr i vi l eged OS Gr oups
>Assi gn t he cor r ect OS gr oups f or OS aut hent i cat i on ( most l y def aul t i s OK)
>Next

I nst al l at i on Locat i on
>ORACLE_BASE: / u01/ app/ or acl e
Sof t war e l ocat i on: / u01/ 11. 2. 0/ gr i d
>Next

Cr eat e I nvent or y
>Speci f y t he l ocat i ons: / u01/ app/ or aI nvent or y
>Next

Per f or mPr er equi si t e Checks
>OUI per f or ms cer t ai n checks
>Check t hat st at us of al l checks i s Succeeded
Not e: i n t hi s exampl e, NPS er r or can be i gnor ed
# 11. 2. 0. 2 r et ur ns " PRVF- 5150: Pat h ORCL: i s not a val i d pat h on al l nodes"
# i n t hi s case: ver i f y manual l y t he asmdevi ce. I f i t succeeds, i gnor e t he
# er r or . I f i t f ai l s, r un / et c/ i ni t . d/ or acl easmconf i gur e - i on al l nodes and
# set gr i d user and oi nst al l as a gr oup ( Not e I D 1210863. 1)

# For t he er r or " PRVF- 5636 : The DNS r esponse t i me f or an unr eachabl e node
# exceeded " 15000" ms" , t he r esponse t i me can be measur ed by t he command:
# t i me nsl ookup r ac1
Page 541 Oracle DBA Code Examples

>Next

Summar y
>Fi ni sh

/ * For 64- bi t , bef or e you r un r oot . sh appl y pat ch# 9974223
( t hi s pat ch shoul d al so be appl i ed on RDBMS) :
expor t PATH=$PATH: / u01/ app/ 11. 2. 0/ gr i d/ OPat ch
opat ch ver si on
cd / u01/ app/ or acl e/ admi n/ pat ches
opat ch l si nvent or y - det ai l - oh / u01/ app/ 11. 2. 0/ gr i d
unzi p p9974223_112020_Li nux- x86- 64. zi p
pwd
/ u01/ app/ or acl e/ admi n/ pat ches
opat ch nappl y - l ocal - oh / u01/ app/ 11. 2. 0/ gr i d - i d 9974223
opat ch l si nvent or y - det ai l - oh / u01/ app/ 11. 2. 0/ gr i d
*/

Execut e Conf i gur at i on Scr i pt s
>Run t he scr i pt s as i nst r uct ed i n t he scr een
Not e: The scr i pt s must be r un on one node at a t i me.
/ *
I f you f ace pr obl ems i n r unni ng r oot . sh and you want
t o deconf i gur e t he pr evi ous r un of r oot . sh:
/ u01/ 11. 2. 0/ gr i d/ cr s/ i nst al l / r oot cr s. pl - ver bose - deconf i g - f or ce
*/
>OK

/ * Not e: when I r an r oot . sh i n node2, I f aced " ORA- 15018: di skgr oup cannot
be cr eat ed" . I deconf i gur ed what made by r oot . sh, i ssued or acl easm
st op, st ar t and t hen r an r oot . sh agai n */

We expect t he ver i f i cat i on phase t o f ai l wi t h an er r or r el at i ng t o t he SCAN,
assumi ng you ar e not usi ng DNS.
I NFO: Checki ng Si ngl e Cl i ent Access Name ( SCAN) . . .
I NFO: Checki ng name r esol ut i on set up f or " r ac- scan. l ocal domai n" . . .
I NFO: ERROR:
I NFO: PRVF- 4664 : Found i nconsi st ent name r esol ut i on ent r i es f or SCAN name
" r ac- scan. l ocal domai n"
I NFO: ERROR:
I NFO: PRVF- 4657 : Name r esol ut i on set up check f or " r ac- scan. l ocal domai n"
( I P addr ess: 192. 168. 2. 201) f ai l ed
I NFO: ERROR:
I NFO: PRVF- 4664 : Found i nconsi st ent name r esol ut i on ent r i es f or SCAN name
" r ac- scan. l ocal domai n"
I NFO: Ver i f i cat i on of SCAN VI P and Li st ener set up f ai l ed
Pr ovi ded t hi s i s t he onl y er r or , i t i s saf e t o i gnor e t hi s
>Next

Message: The i nst al l at i on of t he Gr i d I nf r ast r uct ur e was successf ul l .
>Cl ose


Not e: I f your OS i s SUSE Li nux, shut t i ng down on node wi l l r esul t i n shut t i ng
t he ot her nodes. To wor kar ound:
#cd / et c/ r c3. d
#l n - s / et c/ i ni t . d/ ohasd K07ohasd
Page 542 Oracle DBA Code Examples

3. Oracle Grid Infrastructure Patching
at t i me of t hi s wr i t i ng ( J an, 2011) , no pat ches appl i ed.
4. Checking Oracle Grid Infrastructure Status
# Appl i cat i on r esour ces
cr sct l st at r es - t


# Or acl e Cl ust er Ready Ser vi ces ( CRS)
cr sct l check cr s


# Or acl e Cl ust er Regi st r y ( OCR) and Vot i ng Di skCl ust er Ready Ser vi ces ( CRS)
ocr check


# Or acl e Hi gh Avai l abi l i t y Ser vi ces aut ost ar t
su -
/ u01/ 11. 2. 0/ gr i d/ bi n/ cr sct l conf i g cr s


# Or acl e Aut omat i c St or age Management ( ASM)
su - gr i d
sr vct l conf i g asm- a


# Or acl e Li st ener
sr vct l conf i g l i st ener - a


# Si ngl e Cl i ent Access Name ( SCAN)
sr vct l conf i g scan
5. Oracle Database 11g R2 Software Installation
# as oracle
cd / u01/ app/ st age/ or a11gr 2db/ db
unzi p L11gR2_dat abase_1of 2. zi p >/ dev/ nul l
unzi p L11gR2_dat abase_2of 2. zi p >/ dev/ nul l

cd dat abase
. / r unI nst al l er


Conf i gur e Secur i t y Updat es
>Pr ovi de your e- mai l addr ess, i f you want or l eave t hembl ank
>Next

I nst al l at i on Opt i ons
>Sel ect ' I nst al l Dat abase sof t war e onl y'
>Next >

I nst al l Type
i n 11. 2. 0. 1:
>Sel ect ' Real Appl i cat i on Cl ust er s dat abase i nst al l at i on' , and sel ect al l
nodes.
Page 543 Oracle DBA Code Examples

i n i n 11. 2. 0. 2:
>sel ect Or acl e RAC One Node i nst al l at i on
>Use t he ' SSH Connect i vi t y' but t on t o conf i gur e/ t est t he passwor dl ess SSH
connect i vi t y.
>Next

Pr oduct Languages
>Conf i r m' Engl i sh'
>Next

Dat abase Edi t i on
>' Ent er pr i se Edi t i on' i s t i cked
Opt i onal : Cl i ck on Sel ect Opt i ons> Sel ect " Or acl e Par t i t i oni ng" and " Or acl e
Real Appl i cat i on Test i ng"
>OK
>Next

I nst al l at i on Locat i on
>Or acl e Base: / u01/ app/ or acl e
Sof t war e Locat i on: / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1
>Next

Pr i vi l eged OS Gr oups
>OSDBA: dba
>OSOPER: oi nst al l
>Next

Pr er equi si t e Checks
. . OUI per f or ms pr er equi si t e checks
>Check t hat st at us of al l checks i s Succeeded
>I f you ar e sur e t he unsuccessf ul l checks can be i gnor ed t i ck t he box ' I gnor e
Al l '
>Next

Summar y
>Check summar y i nf o
>Fi ni sh

I nst al l Pr oduct
. . OUI i nst al l s t he db sof t war e
>as a r oot , r un t he r oot . sh scr i pt on t he f i r st node t hen t he ot her nodes ( One
at a t i me)
>OK

Fi ni sh
>Cl ose
6. Oracle Database 11g R2 Software Patching
Patch 9004119 should be applied on 11.2.0.1. Do not apply it to 11.2.0.2. The patch just
installes the following scripts which are used for RAC One Node:
o raconefix Fixes metadata after an Omotion failure or failover
o raconeinit Initialize the database to RAC One Node
o raconestatus Check the status of RAC One Node database
o racone2rac Upgrade RAC One Node database to RAC
o Omotion Migrate database online from one node to another
Page 544 Oracle DBA Code Examples

# at t i me of t hi s wr i t i ng, Pat ch #9004119 shoul d be appl i ed f or RAC One Node

/ * Downl oad and appl y pat ch 9004119 */
- - t he pat ch wi l l be appl i ed i n a r ol l i ng f or war d st yl e
su - or acl e
expor t PATH=$PATH: $ORACLE_HOME/ OPat ch
unzi p p9004119_112010_LI NUX. zi p
cd 9004119

# Ver i f y t he OUI I nvent or y i s accessi bl e by OPat ch:
opat ch l si nvent or y


# appl y t he pat ch
opat ch appl y
# NOTE: t he pat ch asks you t o shut down t he i nst ance bef or e appl yi ng t he pat ch.
I n t hi s case, you do not need t o do so because t he pat ch j ust i nst al l s some
scr i pt s. Pr oceed wi t h appl yi ng t he scr i pt wi t hout st oppi ng t he i nst ances i n
nei t her r ac1 nor r ac2.

# make sur e t he scr i pt s wer e i nst al l ed i n bot h nodes:
cd $ORACLE_HOME/ bi n
l s r acone* Omot i on
7. Install EM Agent in cluster nodes (if required)

8. ASM Diskgroups Creation
Note: It is Oracle's Best Practise to have an OCR mirror stored in a second disk group. To
follow this recommendation add an OCR mirror. Mind that you can only have one OCR in a
diskgroup. To add OCR mirror to an Oracle ASM disk group, ensure that the Oracle
Clusterware stack is running and
ocr conf i g - add +ORADATA
ocr check
# as gr i d user : st ar t t he ASM Conf i gur at i on Assi st ant ( ASMCA)
#su - grid
cd / u01/ 11. 2. 0/ gr i d/ bi n
. / asmca

>Di sk Gr oups t ab
>Cr eat e but t on
>Di sk Gr oup Name: DGDATA
>Redundancy: Ext er nal
>Di sk2
>OK

>Cr eat e but t on
>Di sk Gr oup Name: DGFRA
>Redundancy: Ext er nal
>Di sk3
>OK

>Exi t
>Yes
Page 545 Oracle DBA Code Examples

9. RAC Database Creation
After the database is created, create a service.
# as or acl e
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n
. / dbca

Wel come
11. 2. 0. 1:
Sel ect ' Or acl e Real Appl i cat i on Cl ust er s dat abase'
11. 2. 0. 2:
Sel ect ' Or acl e RAC One Node Dat abase'
>Next

Oper at i ons
> choose opt i on ' Cr eat e a Dat abase'
>Next

Dat abase Templ at e
>Sel ect Gener al Pur pose or any t empl at e
>Next

Dat abase I dent i f i cat i on
>Conf i gur at i on Type: Admi n
>Gl obal e Dat abase Name: r on
>SI D: r on
11. 2. 0. 2:
>Ser i ve Name: r onsr v
11. 2. 0. 1:
> Sel ect t he nodes: r ac1. Make sur e you sel ect j ust ONE NODE.
11. 2. 0. 2:
> Sel ect t he nodes: r ac1, r ac2
>Next

Management Opt i ons
>Sel ect t he opt i on you want . I sel ect ed " Conf i gur e Ent er pr i se Manager "
>Next

Dat abase Cr edent i al s
>Set t he passwor d( s)
>Next

Dat abase Fi l e Locat i ons
>Or acl e- Managed Fi l es
>Dat abase Ar ea: +DGDATA
>Pr act i cal l y ( but not i n t hi s case) , you shoul d def i ne ' Mul t i pl ex Redo Logs
and Cont r ol Fi l es' .
>Next

/ * Not e: I f you cannot see t he di skgr oups, per f or mt he f ol l owi ng ( I D:
1177483. 1) :
su -
cd <Gr i d_Home>/ bi n
chmod 6751 or acl e
l s - l or acl e
- r wsr - s- - x 1 gr i d oi nst al l
*/
Page 546 Oracle DBA Code Examples


ASM Cr edent i al s
. . I f you chose t o set up EM, you wi l l be asked about ASMSNMP passwor d
>Ent er t he passwor d
>Ok but t on

Recover y Conf i gur at i on
>Fl ash r ecover y ar ea: +DGFRA
>def i ne t he si ze: 2000 MB
I f t he si ze i s smal l er t han r ecommended a war ni ng wi l l popup.
>Next

Dat abase Cont ent
>Sel ect i f you want t o have sampl e schemas cr eat ed i n your dat abase
>Next

I ni t i al i zat i on Par amet er s
>Revi ew and change t he set t i ngs f or memor y al l ocat i on, char act er set et c.
>Next

Dat abase St or age
>Revi ew t he dat abase st or age set t i ngs and change as r equi r ed
>Next

Cr eat i on Opt i ons
>Make sur e t he t i ckbox ' Cr eat e Dat abase' i s t i cked
>Fi ni sh

Summar y
>OK
. . Dat abase cr eat i on pr oceedi ng
>af t er compl et i on Exi t


/ * Fi x / home/ or acl e/ . bash_pr of i l e */
vi / home/ or acl e/ . bash_pr of i l e
ORACLE_SI D=RON_1


/ * Check Conf i r mat i on */
# t o show t he cur r ent conf i gur at i on and st at us of t he RAC dat abase
sr vct l conf i g dat abase - d r on
sr vct l st at us dat abase - d r on

sql pl us / nol og
conn syst em@r on
sel ect i nst ance_name, st at us f r omv$i nst ance ;
sel ect name, db_uni que_name f r omv$dat abase;


# check OEM ( i f conf i gur ed) :
ht t ps: / / r ac1. mydomai n. com: 1158/ em/
# i f not st ar t ed, you can st ar t i t :
su - or acl e
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n
expor t ORACLE_UNQNAME=r on
expor t ORACLE_SI D=RON_1
Page 547 Oracle DBA Code Examples

. / emct l st at us dbconsol e
. / emct l st ar t dbconsol e


# check Or acl e pr ocesses:
ps - eo pi d - o command | gr ep or a_ | gr ep - v gr ep


/ * I n 11. 2. 0. 1: Cr eat e t he db ser vi ce( s) */
OEM home- > Avai l abi l i t y- > Cl ust er Managed Dat abase Ser vi ces- > ent er
cr edent i al s- > Cr eat e Ser vi ce- > ent er Ser vi ce Name: hr _sr v- > Ok but t on

# check ser vi ce st at us:
sr vct l conf i g ser vi ce - d r on
10. Initialize the Database to RAC One Node (11.2.0.1 Only)
The raconeinit utility renames the db instance and creates the directories and files
supporting the renamed instance.
Renaming the instance name resulted in the DB Control to return the error: "ORA-12505:
TNS:listener does not currently know of SID given in connect descriptor". Personally, the
only solution I found was to recreate the DB Control configuration as follows. Refer to the
"Administrator's Guide" for further details about administering DB Control.
sr vct l st at us dat abase - d r on
r aconest at us
r aconei ni t
Out put >>
Candi dat e Dat abases on t hi s cl ust er :
# Dat abase RAC One Node Fi x Requi r ed
=== ======== ============ ============
[ 1] r on NO N/ A
Ent er t he dat abase t o i ni t i al i ze [ 1] :
Dat abase r on i s now r unni ng on ser ver r ac1
Candi dat e ser ver s t hat may be used f or t hi s DB: r ac2
Ent er t he names of addi t i onal candi dat e ser ver s wher e t hi s DB may r un ( space
del i mi t ed) : rac2
Pl ease wai t , t hi s may t ake a f ew mi nut es t o f i ni sh. . . . . . .
Dat abase conf i gur at i on modi f i ed.


# check t he new i nst ance was cr eat ed:
sr vct l st at us dat abase - d r on
sr vct l conf i g dat abase - d r on


# i f DB Cont r ol r et ur ns ORA- 12505, you can r ecr eat e i t s r eposi t or y as f ol l ows:
/ * Dr op t he DB Conf i g Fi l es and Rep Obj ect s */
# Remove t he f ol l owi ng di r ect or i es f r omyour f i l e syst em:
# $ORACLE_HOME/ host name_si d
# $ORACLE_HOME/ oc4j / j 2ee/ OC4J _DBConsol e_host name_si d
r m- r $ORACLE_HOME/ r ac1_r on
r m- r $ORACLE_HOME/ oc4j / j 2ee/ OC4J _DBConsol e_r ac1_r on

# $ORACLE_HOME/ sysman/ admi n/ emdr ep/ bi n/ RepManager host name l i st ener _por t si d -
act i on dr op
$ORACLE_HOME/ sysman/ admi n/ emdr ep/ bi n/ RepManager r ac1 1521 r on_1 - act i on dr op

Page 548 Oracle DBA Code Examples

/ * Add DB Cont r ol Conf i g */
[ or acl e@r ac1 ~] $ $ORACLE_HOME/ bi n/ emca - conf i g dbcont r ol db - r epos cr eat e -
cl ust er

STARTED EMCA at J an 4, 2011 12: 18: 02 PM
EM Conf i gur at i on Assi st ant , Ver si on 11. 2. 0. 0. 2 Pr oduct i on
Copyr i ght ( c) 2003, 2005, Or acl e. Al l r i ght s r eser ved.

Ent er t he f ol l owi ng i nf or mat i on:
Dat abase uni que name: r on
Ser vi ce name: r on
Li st ener por t number : 1521
Li st ener ORACLE_HOME [ / u01/ 11. 2. 0/ gr i d ] : / u01/ 11. 2. 0/ gr i d
Passwor d f or SYS user :
Passwor d f or DBSNMP user :
Passwor d f or SYSMAN user :
Cl ust er name: r on
Emai l addr ess f or not i f i cat i ons ( opt i onal ) :
Out goi ng Mai l ( SMTP) ser ver f or not i f i cat i ons ( opt i onal ) :
ASM ORACLE_HOME [ / u01/ 11. 2. 0/ gr i d ] : / u01/ 11. 2. 0/ gr i d
ASM por t [ 1521 ] :
ASM user name [ ASMSNMP ] :
ASM user passwor d:
11. Postinstallation tasks
# backup t he r oot . sh scr i pt ( on al l nodes)
cp / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ r oot . sh ~/ r oot . sh. bak
12. General Useful Postinstallation Tasks in Linux
Following are tips to consider after the successful installation to make managing RAC
easier.
Consider using rlwrap utility with SQL*Plus and RMAN:
o Using rlwrap Utility with RMAN in Unix-Based Systems
o Using rlwrap Utility with SQL*Plus in Unix-Based Systems

/ * Easy Acces t o cr s and db homes */
# i t i s common t o access bi n di r ect or i es i n cl ust er war e and db homes

# add t he f ol l owi ng t o . bashr c of or acl e user
al i as db=' cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ bi n'

Page 549 Oracle DBA Code Examples

Instance Relocation using Omotion (11.2.0.1)
"Omotion" moves one instance from one node to another in a cluster.
To migrate an instance without client interruption, implement FAN. You can then also
enable TAF.
You can also provide the database name and migration time as inputs on the command
line:
. / Omot i on - d adm2 - m5
# i n cl i ent t nsnames. or a i mpl ement TAF:
RONTAF =
( DESCRI PTI ON =
( ENABLE = BROKEN)
( LOAD_BALANCE = OFF)
( FAI LOVER = ON)
( ADDRESS = ( PROTOCOL = TCP) ( HOST = r ac- scan. mydomai n. com) ( PORT = 1521) )
( CONNECT_DATA =
( SERVER = DEDI CATED)
( SERVI CE_NAME = r on)
( FAI LOVER_MODE =
( TYPE = SELECT)
( METHOD = BASI C)
( BACKUP = RON)
)
)
)


# check on whi ch i nst ance t he db i s r unni ng:
sr vct l st at us dat abase - d r on


# t o t est t he TAF, i ssue a l ong quer y i n a cl i ent


# mi gr at e t he i nst ance ( - v ver bose) :
. / Omot i on - v
Page 550 Oracle DBA Code Examples

Instance Relocation using Omotion (11.2.0.2)
sr vct l r el ocat e dat abase - d r ac1 - n node7
Coni nue>>

Page 551 Oracle DBA Code Examples

Part 9 Oracle Warehousing
Page 552 Oracle DBA Code Examples

Oracle Warehouse Builder (OWB)
Oracle Warehouse Builder Architecture

Starting and Stoping the Service
St ar t i ng and St oppi ng OWB Ser vi ce

- - st op ser vi ce
sql pl us OWBSYS/ <passwor d> @<ORACLE_HOME>\ st op_ser vi ce. sql

- - st ar t ser vi ce
sql pl us OWBSYS/ <passwor d> @<ORACLE_HOME>\ st ar t _ser vi ce. sql

- - i f st ar t f ai l s, check t he pr obl emusi ng t he f ol l owi ng scr i pt :
sql pl us OWBSYS/ <passwor d> @<ORACLE_HOME>\ ser vi ce_doct or . sql

- - i f OWBSYS user i s l ocked or i t s passwor d was modi f i ed, t he st ar t
- - wi l l f ai l . St or e t he changed passwor d i n t he r eposi t or y usi ng:
sql pl us OWBSYS/ <passwor d> @<ORACLE_HOME>\ set _r eposi t or y_passwor d. sql
Configuring the Repository and Workspaces
Goto Start>Oracle Home> Warehouse Builder>Administration>Repository Assistant
on UNIX, locate OWB_ORACLE_HOME/owb/bin/ and run reposinst.sh
Select Manage Workspaces> Create a New Workspace> Workspace Owner> ...
The user must have OWB_USER role.
Select a base language for the repository (cannot be changed later)
Select Workspace users
Page 553 Oracle DBA Code Examples

Steps of Using Warehouse Builder
Design the target structure
o Design a dimensional model and implement it in a database as:
Relational implementation (star schema)
Multidimensional implementation (OLAP)
Create a project
Tip: to delete a project, expand another project then right click on the project you want
to delete.
Create source module(s):
o Oracle module: specify hostname:port rather than using SQL*Net Connection.
o Non-Oracle module: create ODBC connection to the database then configure Oracle to
connect to the ODBC connection:
Copy the file ORACLE_HOME\hs\admin\initdg4odbc.ora to init<odbc connection>.ora
HS_FDS_CONNECT_I NFO = <odbc dat a_sour ce_name>
HS_FDS_TRACE_LEVEL = <t r ace_l evel >
For example:
HS_FDS_CONNECT_I NFO = MYSQLSERVER
HS_FDS_TRACE_LEVEL = 0
Edit the listener.ora then restart the listener:
# PROGRAM=dg4odbc i n Or acl e 11g
# PROGRAM=hsodbc i n 10g
SI D_LI ST_LI STENER=
( SI D_LI ST=
( S Gl obal Expl or er > Secut i r yt >User s >NewI D_DESC=
( SI D_NAME=mysql ser ver )
( ORACLE_HOME=D: \ app\ bob\ pr oduct \ 11. 1. 0\ db_1)
( PROGRAM=dg4odbc)
)
)
Right-click on the ODBC node in the Design Center and select New
Edit the connection. Make sure that both username and password are enclosed in
double quotes. Enter the Host where the Oracle database resides.
Tip: to delete a connection, unregister it first from Control Manager then delete it from
Design Center.
Note: The transparent gateway agents must be purchased and installed separately from
the Oracle Database, and then configured to support the communication with the
external database. The generic connectivity agent is included with the Oracle Database.
o Import source metadata from files:
Files> New> define path (not file)
On the created object> Import..> Sample>.. >Finish

Page 554 Oracle DBA Code Examples

Import source metadata: by using the Import Metadata Wizard or manually. Manual
method: under Tables node, New> Data Object Editor.
Create the target user
Global Explorer> Secutiryt>Users >New (always created in the db repository)
Create the target module
Create target dimensions in OWB:
o Dimension: Dimension Attributes, Levels, Level Attributes and Hierarchies
o Time dimension: Project Explorer> Databases> Ourproject> Dimensions> New> Using
Time Wizard. A mapping and a sequence will be as a result created.
Create target cubes in OWB
Design staging area table(s)
Create a mapping from source to staging table: add source tables, add the staging target
table then link from source to staging target. Linking may include:
o Joiner: edit it to add more Input Groups, link source tables to it, define join condition.
Note: Oracle 10.2.0.4 returns "Bad expression return type" error (bug ID 7417869).
o Aggregator: link output of Joiner to its input. Set its Group By Clause setting. Add
required aggregation functions (usually SUM) by right clicking on OUTGRP1> Open
details> Output Attributes> Add button to add something like AMOUNT> OK> click on
AMOUNT in the aggregator> Properties Window> Expression> set the function> OK
o Transformation
Validate the mapping
Generate the mapping
Deploy the mapping
Execute the mapping
Mapping Operators
Source and Target Operators: Cube, Dimension, External Table, Table, Constant, View,
Sequence, Construct (returns SYS_REFCURSOR)
Data Flow Operators: Aggregator, Deduplicator (distinct SQL function), Expression, Filter,
Joiner, Key Lookup, Pivot, Set Operation, Splitter, Transformation, Table Function
Pre/Post Processing Operators: Mapping Input Parameter, Mapping Output Parameter,
Post-Mapping Process, Pre-Mapping Process
Pluggable Mappings: group of operators act as single operator

Page 555 Oracle DBA Code Examples



Page 556 Oracle DBA Code Examples

Part 10 Oracle Database Utilities
Page 557 Oracle DBA Code Examples

Using SQL*Plus
Using SQL*Plus Command-Line Options
sql pl us [ [ <opt i on>] [ <l ogon>] [ <st ar t >] ]
<st ar t > i s: @<URL>| <f i l ename>[ . <ext >] [ <par amet er > . . . ]
The silent option (-S): no output on screen
The no-prompt logon option (-L): no username/password question after login fail
The markup option (-M): HTML generation
sql pl us hel p
Starting SQL*Plus Session
$expor t ORACLE_HOME= / u01/ app/ or acl e/ pr oduct / 11. 1. 0/ db_1
$ORACLE_SI D=or cl
$expor t ORACLE_SI D
NLS_LANG and ORA_NLS11
sql pl us oe/ oe@/ / myser ver . mydomai n: 1521/ t est db
sql pl us user name/ passwd
sql pl us user name/ passwd AS SYSDBA
sql pl us user name/ passwd@( DESCRI PTI ON =( ADDRESS=( PROTOCOL=t cp) ( HOST=sal es-
ser ver ) ( PORT=1521) ( CONNECT_DATA= ( SERVI CE_NAME=or cl . mycompany. com) ) )
Controlling User Privileges in SQL*Plus
Product_user_profile table controls what commands a user can issue in SQL*Plus session.
The following commands can be prevented by using this feature.
SQL: ALTER, AUDIT, ANALYZE, CREATE, DELETE, DROP, INSERT, LOCK, NOAUDIT, RENAME,
SELECT, UPDATE, VALIDATE, TRUNCATE, GRANT, REVOKE, SET ROLE, SET TRANSACTION
PL/SQL:DECLARE, BEGIN
SQL*PLUS: COPY, HOST, SET, EDIT, PASSWORD, SPOOL, EXECUTE, QUIT, START, EXIT,
RUN, GET, SAVE
You can use the RESTRICT command to prevent users from using certain operating system
commands. It disables the commands even where there are no connections to the server.
Command Level 1 Level 2 Level 3
EDIT Disabled Disabled Disabled
GET Disabled
HOST Disabled Disabled Disabled
SAVE Disabled Disabled
SPOOL Disabled Disabled
START Disabled
STORE Disabled Disabled
Page 558 Oracle DBA Code Examples

SQL> DESC pr oduct _user _pr of i l e
Name Nul l ? Type
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PRODUCT NOT NULL VARCHAR2( 30)
USERI D VARCHAR2( 30)
ATTRI BUTE VARCHAR2( 240) - - command t o di sabl e i n upper
case
SCOPE VARCHAR2( 240)
NUMERI C_VALUE NUMBER( 15, 2)
CHAR_VALUE VARCHAR2( 240) - - r ol e name t o di sabl e
DATE_VALUE DATE
LONG_VALUE LONG

- - no i nser t
I NSERT I NTO pr oduct _user _pr of i l e VALUES
( ' SQL*PLUS' , ' OE' , ' I NSERT' , NULL, NULL, NULL, NULL, NULL) ;
- - no OS command
I NSERT I NTO pr oduct _user _pr of i l e ( pr oduct , user i d, at t r i but e) VALUES
( ' SQL*Pl us' , ' myuser ' , ' HOST' ) ;
- - no set Rol e t o DBA
i nser t i nt o pr oduct _user _pr of i l e( pr oduct , user i d, at t r i but e, char _val ue)
val ues( ' SQL*Pl us' , ' APPS' , ' ROLES' , ' DBA' ) ;
- - Pr event i ng access usi ng PL/ SQL
i nser t i nt o syst em. pr oduct _pr of i l e ( pr oduct , user i d, at t r i but e, char _val ue)
val ues ( ' SQL*Pl us' , ' AMAR' , ' DECLARE' , ' DI SABLED' ) ;
i nser t i nt o syst em. pr oduct _pr of i l e ( pr oduct , user i d, at t r i but e, char _val ue)
val ues ( ' SQL*Pl us' , ' AMAR' , ' BEGI N' , ' DI SABLED' ) ;

sql pl us - RESTRI CT 1
Setting the SQL*Plus Environment with the SET Command
help index list of available commands by typing
help set variable possible values
AUTO[COMMIT] Specifies whether commits of transactions are automatic or manual.
DEF[INE]{&/C/ON/OFF} Sets the prefix character used during variable substitutions.
ECHO {OFF/ON} when ON, each command will be displayed before its output
onscreen.
FEED[BACK] {OFF/ON} whether to show the number of records returned by your query.
LONG {80/n} maximum width of the LONG, CLOB, NCLOB, and XMLType values
NEWP[AGE] {1/n/none} Specifies the number of blank lines at the top of each new page.
PAGES[IZE] {24/n} Specifies the number of lines in each page
TI[ME] {OFF/ON} Displays time if set to on.
TIMI[NG] {OFF/ON} Controls the display of timing for SQL commands.
VER[IFY] {OFF/ON} Specifies whether SQL text is displayed after variable substitution.
Setting SQL*Plus Preferances
Globally glogin.sql
User level login.sql: in Oracle 11g, executed even after connect command
Page 559 Oracle DBA Code Examples

Logging SQL*Plus Errors
In Oracle 11g, SET ERRORLOGGING ON command writes all subsequent errors into a table
called sperrorlog.
SET ERRORLOGGI NG ON
SHOWERRORLOGGI NG
Key SQL*Plus "Working" Commands
Set t i ng SQLPROMPT Command
_USER
_CONNECT_I DENTI FI ER
_PRI VI LEGE as sysdba
_DATE
SET SQLPROMPT " _USER > "

host
HOST cp / u01/ app/ or acl e/ new. sql / t mp

SPOOL { f i l e_name[ . ext ] [ CRE[ ATE] | REP[ LACE] | APP[ END] ] | OFF}
SPOOL / u01/ app/ or acl e/ dat a/ empl oyees. t xt ;
SELECT * FROM hr . empl oyees;
SPOOL OFF;

- - ACCEPT and PROMPT Commands
ACCEPT MYTI TLE PROMPT ' Ti t l e: '

- - usi ng PAUSE t o check l ong l i st i ng out put
SQL> SHOWPAUSE
PAUSE i s OFF
SQL> SET PAUSE ON
SQL> ver y l ong l i st i s di spl ayed
Creating Command Files in SQL*Plus
SAVE st at us. sql
- - set t he sear ch di r ect or y usi ng env var ORACLE_PATH
@myscr i pt f i l e. sql

- - Cr eat i ng a Wi ndows Bat ch Scr i pt
sql pl us user name/ passwor d@connect _i dent i f i er @C: \ t emp\ t est scr i pt . sql

- - subst i t ut i on var s
DEFI NE owner = ' &1'
SELECT segment _name, segment _t ype, ext ent s
FROM dba_segment s
WHERE owner = upper ( ' &owner ' ) ;
Copying Tables with the COPY Command
commits while data are moved
slower than CREATE TABLE .. AS SELECT
Page 560 Oracle DBA Code Examples

SQL> COPY
usage: COPY FROM <db> TO <db> <opt > <t abl e> { ( <col s>) } USI NG <sel >
<db> : dat abase st r i ng, e. g. , hr / your _passwor d@d: chi cago- mkt g
<opt > : ONE of t he keywor ds: APPEND, CREATE, I NSERT or REPLACE
<t abl e>: name of t he dest i nat i on t abl e
<col s> : a comma- separ at ed l i st of dest i nat i on col umn al i ases
<sel > : any val i d SQL SELECT st at ement

set ARRAYSI ZE 100
SQL> COPY FROM sysadm/ sysadm1@f i nance1-
> CREATE t est 01 -
> USI NG SELECT * FROM empl oyee;
Creating Web Pages Using SQL*Plus
SQLPLUS - MARKUP " HTML ON"
SQL> SET MARKUP HTML ON SPOOL ON
SQL> commands her e . . .
SQL> SET MARKUP HTML OFF SPOOL OFF
Using SQL to Generate SQL
SET ECHO OFF HEADI NG OFF FEEDBACK OFF
SPOOL t est . t xt
SELECT ' gr ant connect , r esour ce t o ' | | user name| | ' ; ' FROM dba_user s;
@t est . t xt
Enabling AUTOTRACE for a User
- - cr eat e pl an_t abl e ( i f not t her e)
desc pl an_t abl e
- - l ogi n as t he user who want s t o use t he AUTOTRACE
conn / as sysdba
@d: \ or acl e\ pr oduct \ 10. 1. 0\ db_1\ RDBMS\ ADMI N\ ut l xpl an. sql

- - cr eat e pl ust r ace r ol e
@d: \ or acl e\ pr oduct \ 10. 1. 0\ db_1\ sql pl us\ admi n\ pl ust r ce. sql

gr ant pl ust r ace t o scot t ;

- - t he f ol l owi ng pr i vi l ege i s al so r equi r ed:
gr ant sel ect any di ct i onar y t o t est ;

SET AUTOTRACE
ON
ON STATI STI CS
ON EXPLAI N
TRACEONLY
TRACEONLY STATI STI CS
OFF
Page 561 Oracle DBA Code Examples

Using rlwrap Utility with SQL*Plus in Unix-Based Systems
rlwrap utility allows you to navigate history of commands in SQL*Plus and edit them.
/ * I nst al l */
# Opt i on 1: f or r pmver si on:
# can be downl oaded f r om:
# ht t p: / / r pm. pbone. net
# ht t p: / / i van. kar t i k. sk
r pm- i vh r l wr ap*. r pm


# Opt i on 2: f or t ar ver si on
# downl oad r l wr ap- 0. 30. t ar . gz ( sear ch t he net or f r om
ht t p: / / www. ahmedbar aka. com/ downl oad/ or acl e/ r l wr ap- 0. 30. t ar . gz )
# unzi p t he f i l e and i nst al l
su -
gunzi p r l wr ap- 0. 30. t ar . gz
t ar - xvf r l wr ap- 0. 30. t ar
cd r l wr ap- 0. 30
. / conf i gur e
make
make i nst al l

/ * Recommended */
vi / home/ or acl e/ . bashr c
al i as sql pus=' r l wr ap sql pl us / nol og'
# or
echo " al i as sql pus=' r l wr ap sql pl us / nol og' " >> / home/ or acl e/ . bashr c
Escaping Special Characters
/ * Escape quot es */
Use t wo quot es f or ever y one di spl ayed. Exampl es:
SELECT ' Fr ank' ' s Or acl e si t e' AS t ext FROM DUAL;
TEXT
- - - - - - - - - - - - - - - - - - - -
Fr anks' s Or acl e si t e

SELECT ' A ' ' quot ed' ' wor d. ' AS t ext FROM DUAL;
TEXT
- - - - - - - - - - - - - - - -
A ' quot ed' wor d.

SQL> SELECT ' A ' ' ' ' doubl e quot ed' ' ' ' wor d. ' AS t ext FROM DUAL;
TEXT
- - - - - - - - - - - - - - - - - - - - - - - - -
A ' ' doubl e quot ed' ' wor d.


/ * Escape wi l dcar d char act er s */

The LI KE keywor d al l ows f or st r i ng sear ches. The ' _' wi l d car d char act er i s
used t o mat ch exact l y one char act er , whi l e ' %' i s used t o mat ch zer o or mor e
occur r ences of any char act er s. These char act er s can be escaped i n SQL.
Exampl es:
SELECT name FROM emp
Page 562 Oracle DBA Code Examples

WHERE i d LI KE ' %/ _%' ESCAPE ' / ' ;
SELECT name FROM emp
WHERE i d LI KE ' %\ %%' ESCAPE ' \ ' ;
Escape amper sand ( &) char act er s i n SQL*Pl us

When usi ng SQL*Pl us, t he DEFI NE set t i ng can be changed t o al l ow &' s
( amper sands) t o be used i n t ext :

SET DEFI NE ~
- - i f SP2- 0317 r et ur ned, t r y SET DEF &
SELECT ' Laur el & Har dy' FROM dual ;
Ot her met hods:

Def i ne an escape char act er :

SET ESCAPE ' \ '
SELECT ' \ &abc' FROM dual ;
Don' t scan f or subst i t ut i on var i abl es:

SET SCAN OFF
SELECT ' &ABC' x FROM dual ;
Anot her way t o escape t he & woul d be t o use concat enat i on, whi ch woul d not
r equi r e any SET commands -

SELECT ' Laur el ' | | ' &' | | ' Har dy' FROM dual ;

/ * Use t he 10g Quot i ng mechani sm: */
Synt ax
q' [ QUOTE_CHAR] Text [ QUOTE_CHAR] '
Make sur e t hat t he QUOTE_CHAR f ol l owed by an ' doesn' t exi st i n t he t ext .
SELECT q' {Thi s i s Or af aq' s ' quot ed' t ext f i el d}' FROM DUAL;

Page 563 Oracle DBA Code Examples

Using SQL*Loader Utility
Invoking SQL*Loader
SQLLDR keywor d=val ue [ , keywor d=val ue, . . . ]
Parameters can be specified in a parameter file:
sql l dr PARFI LE=c: \ . . . \ mypar f i l e. t xt
You specify the command-line parameters (which also could be specified in the control file):
USERI D = usr name/ passwor ed
CONTROL = ' / . . / mycont r ol . ct l '
DATA = ' / . . / mydat a. dat '
LOG = ' / . . . / myl og. l og'
BAD = ' / . . . / mybadf i l e. bad' if not specified, Oracle will create one
DI SCARD=' / . . / mydi scar d. dat ' discarded data do not meet the criteria
DI SCARDMAX=100
SKI P = 235550
in conventional path mode, bind size in bytes OR number of rows
BI NDSI ZE = 512000
ROWS = 64000
DI RECT=t r ue
UNRECOVERABLE=Y (see direct load options in the following sections)
ERRORS = 0 no errors tolerated
LOAD = 10000 maximum number of logical records to be loaded into the table
SI LENT = ALL all generated message are NOT displayed
PARALLEL=t r ue only when DIRECT=true
RESUMABLE=t r ue default is false
RESUMABLE_NAME = f i nance1_l oad
RESUMABLE_TI MEOUT = 3660 in seconds
Using SQL*Loader Control File
Datafile:
o Input File
External Input file: I NFI LE=' / a01/ app/ or acl e/ or adat a/ l oad/ consumer . dat '
Inline Data: I NFI LE = * t hen BEGI NDATA . . .
o Physical and Logical Records
CONCATENATE n RECLEN mevery n rows of data is considered one logical row,
and the row length is m characters
CONTI NUEI F THI S ( 1: 4) = ' next ' if SQL*Loader finds the four letters next at
the beginning of a line, it should treat the data that follows as a continuation of
the previous line
CONTI NUEI F LAST = ' &' continue if last character is &
o Record Format
specific record terminator: by default new line. To change it to something else
like the pipe for example:
i nf i l e " t est . dat " " st r ' | \ n' "
Page 564 Oracle DBA Code Examples

in this case, the following data are two records (multi-line fields) :
one l i ne; hel l o dear wor l d; |
t wo l i nes; Dear wor l d,
hel l o! ; |
Fixed record format: I NFI LE ' . . ' " f i x 12" (12-byte-size records)
ahmed, 1234, j ohnso, 1234= " ahmed, 1234, " and " 12j ohnson, 1234"
Variable record format: I NFI LE ' . . ' " var 2"
05ahmed12j ohnson, 1234 = " ahmed" and " 12j ohnson, 1234"
Loading:
o defining destination table(s) : I NTO TABLE . . I NSERT | REPLACE | APPEND
o defining rejection condition: WHEN <condi t i on>
WHEN( act i vi t y_t ype <>' H' ) and ( act i vi t y_t ype <>' T' )
Note: OR operator cannot be used in the WHEN condition. To workaraound, load into multiple
tables. Check the examples.
Table- and Field-Mapping
o Fields position (either you use this or the delimiters)
Relative: employee_name to start in position 7 and continue for 30 characters
empl oyee_i d POSI TI ON( *) NUMBER EXTERNAL 6
empl oyee_name POSI TI ON( *) CHAR 30
Absolute
empl oyee_i d POSI TI ON( 1: 6) I NTEGER EXTERNAL
empl oyee_name POSI TI ON( 7: 36) CHAR
Note: a field can be skipped using FILLER keyword.
o Data Types:
INTEGER(n)binary integer, where n can be 1, 2, 4, or 8
SMALLINT
CHAR
INTEGER EXTERNAL
FLOAT EXTERNAL
DECIMAL EXTERNAL
LOBFILE
o Delimiters: using POSITION is faster than delimiters
TERMI NATED BY WHI TESPACE
TERMI NATED BY " , "
FI ELDS TERMI NATED BY ' , ' OPTI ONALLY ENCLOSED BY ' " '
o Data Transformation Parameters: SQL function(s) is specified after the data type and
should be enclosed in double quotation marks
f i el d_name CHAR TERMI NATED BY " , " " SUBSTR( : f i el d_name, 1, 10) "
empl oyee_name POSI TI ON 32- 62 CHAR " UPPER( : ename) "
sal ar y posi t i on 75 CHAR " TO_NUMBER( : sal , ' $99, 999. 99' ) "
commi ssi on I NTEGER EXTERNAL " " : commi ssi on * 100"
Command-Line Parameters in the Control File
USERI D = usr name/ passwor ed
CONTROL = ' / . . / mycont r ol . ct l '
DATA = ' / . . / mydat a. dat '
LOG = ' / . . . / myl og. l og'
BAD = ' / . . . / mybadf i l e. bad' if not specified, Oracle will create one
DI SCARD=' / . . / mydi scar d. dat ' discarded data do not meet the criteria
DI SCARDMAX=100
Page 565 Oracle DBA Code Examples

SKI P = 235550
in conventional path mode, bind size in bytes OR number of rows
BI NDSI ZE = 512000
ROWS = 64000
DI RECT=t r ue (see direct load options in the following sections)
ERRORS = 0 no errors tolerated
LOAD = 10000 maximum number of logical records to be loaded into the table
SI LENT = ALL all generated message are NOT displayed
PARALLEL=t r ue only when DIRECT=true
RESUMABLE=t r ue default is false
RESUMABLE_NAME = f i nance1_l oad
RESUMABLE_TI MEOUT = 3660 in seconds
Generating Data
o Constant
l oaded_by CONSTANT " sysadm"
o Expression: SQL or PL/SQL function (doesnt work in direct loading)
col umn_name EXPRESSI ON " SQL st r i ng"
o Record Number in the datafile
r ecor d_numRECNUM
o System Date
l oaded_dat e sysdat e
o Sequence
l oadseq SEQUENCE( max, 1)

/ * Exampl e 1 */
- - t abe separ at ed wi t h nul l s i n t he dat a
Dat a t o I mpor t :
1 Ahmed Bar aka 1000 1. 87 1- 1- 2000
2 J ohn Ri ce 5000 2. 4 10- 5- 1998
3 Emme Rak 2500 2. 34
4 Ki ng Si ze 2700
5 Smal l Si ze 3000 31- 3- 2001


Tabl e St r uct ur e
PERSONS
( I D NUMBER,
PNAME VARCHAR2( 100) ,
BALANCE NUMBER,
RATE NUMBER,
J OI N_DATE DATE ) ;

Cont r ol Fi l e:
OPTI ONS ( ERRORS=0)
LOAD DATA
I NFI LE ' C: \ t emp\ dat a\ per sons. dat '
BADFI LE ' C: \ t emp\ dat a\ per sons. bad'
DI SCARDFI LE ' C: \ t emp\ dat a\ per sons. dsc'

I NTO TABLE " HR" . " PERSONS" REPLACE
FI ELDS TERMI NATED BY X' 9' TRAI LI NG NULLCOLS
Page 566 Oracle DBA Code Examples

( I D I NTEGER EXTERNAL,
PNAME CHAR,
BALANCE I NTEGER EXTERNAL,
RATE FLOAT EXTERNAL,
J OI N_DATE dat e ' dd- mm- yyyy' )



/ * Exampl e 2 */
- - posi t i onal col umns
l oad dat a
i nf i l e *
r epl ace
i nt o t abl e depar t ment s
( dept posi t i on ( 02: 05) char ( 4) ,
dept name posi t i on ( 08: 27) char ( 20)
)
begi ndat a
COSC COMPUTER SCI ENCE
ENGL ENGLI SH LI TERATURE
MATH MATHEMATI CS
POLY POLI TI CAL SCI ENCE

/ * Exampl e 3 */
- - dat a t r ansf or mat i on
LOAD DATA
I NFI LE *
I NTO TABLE modi f i ed_dat a
( r ec_no " my_db_sequence. next val " ,
r egi on CONSTANT ' 31' ,
t i me_l oaded " t o_char ( SYSDATE, ' HH24: MI ' ) " ,
dat a1 POSI TI ON( 1: 5) " : dat a1/ 100" ,
dat a2 POSI TI ON( 6: 15) " upper ( : dat a2) " ,
dat a3 POSI TI ON( 16: 22) " t o_dat e( : dat a3, ' YYMMDD' ) "
)
BEGI NDATA
11111AAAAAAAAAA991201
22222BBBBBBBBBB990112

LOAD DATA
I NFI LE ' mai l _or der s. t xt '
BADFI LE ' bad_or der s. t xt '
APPEND
I NTO TABLE mai l i ng_l i st
FI ELDS TERMI NATED BY " , "
( addr ,
ci t y,
st at e,
zi pcode,
mai l i ng_addr " decode( : mai l i ng_addr , nul l , : addr , : mai l i ng_addr ) " ,
mai l i ng_ci t y " decode( : mai l i ng_ci t y, nul l , : ci t y, : mai l i ng_ci t y) " ,
mai l i ng_st at e,
move_dat e " subst r ( : move_dat e, 3, 2) | | subst r ( : move_dat e, 7, 2) "
)


/ * Exampl e 4 */
Page 567 Oracle DBA Code Examples

- - l oadi ng f r ommul t i pl e i nput f i l es
LOAD DATA
I NFI LE f i l e1. dat
I NFI LE f i l e2. dat
I NFI LE f i l e3. dat
APPEND
I NTO TABLE emp
( empno POSI TI ON( 1: 4) I NTEGER EXTERNAL,
ename POSI TI ON( 6: 15) CHAR,
dept no POSI TI ON( 17: 18) CHAR,
mgr POSI TI ON( 20: 23) I NTEGER EXTERNAL
)


/ * Exampl e 5 */
- - l oadi ng i nt o mul t i pl e t abl es
- - ski ppi ng col umns ( FI LLER)
- - POSI TI ON( 1: 4) i n t he exampl e i s a must t o r esent t he poi nt er back
- - t o t he begi nni ng of t he r ow
- - I n del i mi t ed f or mat s, use " POSI TI ON( 1) " af t er t he f i r st
- - col umn t o r eset t he poi nt er
LOAD DATA
I NFI LE *
I NTO TABLE t ab1 WHEN t ab = ' t ab1'
( t ab FI LLER CHAR( 4) ,
col 1 I NTEGER
)
I NTO TABLE t ab2 WHEN t ab = ' t ab2'
( t ab FI LLER POSI TI ON( 1: 4) ,
col 1 I NTEGER
)
BEGI NDATA
t ab1| 1
t ab1| 2
t ab2| 2
t ab3| 3

- - anot her exampl e
LOAD DATA
I NFI LE ' mydat a. dat '
REPLACE
I NTO TABLE emp
WHEN empno ! = ' '
( empno POSI TI ON( 1: 4) I NTEGER EXTERNAL,
ename POSI TI ON( 6: 15) CHAR,
dept no POSI TI ON( 17: 18) CHAR,
mgr POSI TI ON( 20: 23) I NTEGER EXTERNAL
)
I NTO TABLE pr oj
WHEN pr oj no ! = ' '
( pr oj no POSI TI ON( 25: 27) I NTEGER EXTERNAL,
empno POSI TI ON( 1: 4) I NTEGER EXTERNAL
)


/ * Exampl e 6 */
- - wor k ar ound on bei ng unabl e t o use OR i n t he WHEN condi t i on
LOAD DATA
I NFI LE ' mydat a. dat ' BADFI LE ' mydat a. bad' DI SCARDFI LE ' mydat a. di s'
Page 568 Oracle DBA Code Examples

APPEND
I NTO TABLE my_sel ect i ve_t abl e
WHEN ( 01) <> ' H' and ( 01) <> ' T'
(
r egi on CONSTANT ' 31' ,
ser vi ce_key POSI TI ON( 01: 11) I NTEGER EXTERNAL,
cal l _b_no POSI TI ON( 12: 29) CHAR
)
I NTO TABLE my_sel ect i ve_t abl e
WHEN ( 30: 37) = ' 20031217'
(
r egi on CONSTANT ' 31' ,
ser vi ce_key POSI TI ON( 01: 11) I NTEGER EXTERNAL,
cal l _b_no POSI TI ON( 12: 29) CHAR
)



/ * Exampl e 7 */
- - l oad r ecor ds wi t h mul t i - l i ne f i el ds
- - doesn' t wor k wi t h i nl i ne dat a
l oad dat a
i nf i l e " t est . dat " " st r ' | \ n' "
i nt o t est _t abl e
f i el ds t er mi nat ed by ' ; ' TRAI LI NG NULLCOLS
(
desc, t xt
)

t est . dat :
one l i ne; hel l o dear wor l d; |
t wo l i nes; Dear wor l d,
hel l o! ; |


/ * Exampl e 8 */
- - l oadi ng bi nar y f i l es ( wor d, i mages, vi deo. . . et c)
CREATE TABLE i mage_t abl e (
i mage_i d NUMBER( 5) ,
f i l e_name VARCHAR2( 30) ,
i mage_dat a BLOB) ;

Cont r ol Fi l e:

LOAD DATA
I NFI LE *
I NTO TABLE i mage_t abl e
REPLACE
FI ELDS TERMI NATED BY ' , '
(
i mage_i d I NTEGER( 5) ,
f i l e_name CHAR( 30) ,
i mage_dat a LOBFI LE ( f i l e_name) TERMI NATED BY EOF
)
BEGI NDATA
001, i mage1. gi f
002, i mage2. j pg
Page 569 Oracle DBA Code Examples

003, i mage3. j pg


/ * Exampl e 9 */
- - usi ng speci f i ed char act er set

LOAD DATA
CHARACTERSET WE8EBCDI C500
I NFI LE dat a. ebc " f i x 86 buf f er s 1024"
BADFI LE dat a. bad'
DI SCARDFI LE dat a. dsc'
REPLACE
I NTO TABLE t emp_dat a
(
. . .

/ * Exampl e 10 */
- - Loadi ng a Sequence Number
LOAD DATA
I NFI LE ' / u01/ app/ or acl e/ or adat a/ l oad/ t est l oad. t xt '
I NSERT I NTO TABLE t est 123
( t est _seq. next val , . . . )
Loading Excel File into a Table using SQL*Loader
1. If any cell data has newline characters (Alt+ENTER), remove them using the following
Excel script:
' Removi ng t abs and car r i age r et ur ns f r omwor ksheet cel l s
Sub Cl eanUp( )
Di mTheCel l As Range
On Er r or Resume Next

For Each TheCel l I n Act i veSheet . UsedRange
Wi t h TheCel l
I f . HasFor mul a = Fal se Then
. Val ue = Appl i cat i on. Wor ksheet Funct i on. Cl ean( . Val ue)
End I f
End Wi t h
Next TheCel l
End Sub
2. Save Excel file as CSV
3. Use SQL*Loader to load from CSV.
Loading Large Fields into a Table
If you try to load any field larger than 255 bytes into a table, even if the table column is
defined as VARCHAR2(2000) or a CLOB, "Field in datafile exceeds maximum length" error will
be returned. You need to specify the size of the table column in the control file:
LOAD DATA
I NFI LE ' / u01/ app/ or acl e/ or adat a/ l oad/ t est l oad. t xt '
I NSERT I NTO TABLE t est 123
Page 570 Oracle DBA Code Examples

FI ELDS TERMI NATED BY ' , '
( t ext CHAR( 2000) )
Using Direct Load Options
DI RECT = true
DATA_CACHE: (default 1000) used if you have duplicate data and timestamp values in your
data.
ROWS: save data every number of ROWS
UNRECOVERABLE=Y (default N) used with direct=true and disables redo log generation
SKI P_I NDEX_MAI NTENANCE=t r ue (default false) do not bother maintaining the indexes during
the load.
COLUMNARRAYROWS: number of rows loaded before the building of the stream buffer
STREAMSI ZE: the size of the stream buffer
MULTI THREADI NG: (default true) parallel conversion of column arrays to stream buffers and
stream buffer
Page 571 Oracle DBA Code Examples

Data Pump Export and Import
Data Pump Components
The DBMS_DATAPUMP package: this is the main engine of the Data Pump utilities. It contains
procedures that do the export and import actions.
The DBMS_METADATA package: this package is used to extract and modify data dictionary metadata.
The command-line clients, expdp and impdp.
Data Pump Export Interfaces
Using the Command Line
expdp syst em/ manager di r ect or y=dpump_di r 1 dumpf i l e=expdat 1. dmp
Using a Parameter File
expdp par f i l e=myf i l e. t xt
paramerer file may contain:
SCHEMAS=HR
DI RECTORY=dpump_di r 1
DUMPFI LE=syst em1. dmp
SCHEMAS=hr . . .
Using Interactive-command Data Pump Export
This mode is enabled by pressing [Ctrl] + [C] during an export operation started with the command-
line interface or the parameter file interface.
Using EM Database Control
Start the Database Control and go to the Maintenance | Utilities page.
Export Modes Parameters
FULL ( requires EXPORT_FULL_DATABASE role) , SCHEMAS, TABLES, TABLESPACES,
TRANSPORT_TABLESPACES, and TRANSPORT_FULL_CHECK
Required Rrivileges
# basi c pr i vi l eges:
gr ant cr eat e sessi on, cr eat e t abl e, cr eat e pr ocedur e t o dat apump_user ;

# i f you want t o do any of t he f ol l owi ng:
- t o r un a f ul l dat abase Expor t or
- t o r un a t r anspor t _t abl espace j ob or
- t o r un an Expor t Dat aPump j ob wi t h t he TRACE par amet er or
- t o r un an oper at i on t hat expor t s a di f f er ent schema.
gr ant exp_f ul l _dat abase, i mp_f ul l _dat abase t o dat apump_user ;
Invoking Export Data Pump Examples
# t he command r equi r es CREATE ANY DI RECTORY pr i vi l eges
Page 572 Oracle DBA Code Examples

CREATE DI RECTORY dpump_di r 1 AS ' / u01/ mydi r ' ;
GRANT READ, WRI TE ON DI RECTORY dpump_di r 1 TO bar aka;


# schema mode i s t he def aul t
expdp bar aka/ passwor d DI RECTORY=dpump_di r 1 dumpf i l e=t est exp01. dmp
LOGFI LE=dpump_di r 2: myl og. l og
# gener at e f i l enames based on dat e and t i me ( sed used t o get r i d of spaces)
expdp sa/ s di r ect or y=dpdi r dumpf i l e=sa`dat e +%d- %m- %y_%k- %M | sed
' s/ [ [ : space: ] ] / / ' `. dmp l ogf i l e=dpdi r : sa`dat e +%d- %m- %y_%k- %M | sed
' s/ [ [ : space: ] ] / / ' `. l og

# t abl es mode
expdp bar aka/ passwor d t abl es=empl oyees DI RECTORY=dpump_di r 1
dumpf i l e=t est exp01. dmp
expdp syst em/ passwor d t abl es=hr . empl oyees . .

# nol og f i l e ( by def aul t expor t . l og i s gener at ed)
expdp nol ogf i l e=y

# over wr i t e exi st i ng dumpf i l es ( 11g)
expdp REUSE_DUMPFI LES=y

# compr essi on: ALL, DATA_ONLY, METADATA_ONLY, NONE
expdp COMPRESSI ON=NONE
Export Filtering Parameters
/ * EXCLUDE & I NCLUDE */
EXCLUDE=I NDEX
EXCLUDE=PROCEDURE
EXCLUDE=TABLE: " LI KE ' EMP%' "
EXCLUDE=SCHEMA: " =' HR' "
I NCLUDE=TABLE: " I N ( ' EMP' , ' DEPT' ) "

# When used i n command l i ne, use sl ashes t o escape si ngl e and doubl e
quot at i on:
expdp . . schemas=SCOTT EXCLUDE=TABLE: \ " =\ ' EMP\ ' \ "

/ * QUERY */
QUERY=OE. ORDERS: " WHERE or der _i d > 100000 ORDER BY or der _dat e desc"
Export Remapping Parameters
/ * REMAP_DATA ( 11g) */
- - t he r emappi ng f unct i on shoul dn t have commi t or r ol l back
REMAP_DATA=[ schema. ] t abl ename. col umn_name: [ schema. ] pkg. f unct i on

expdp hr / passwd DI RECTORY=dp_di r DUMPFI LE=r emap. dmp
TABLES=hr . empl oyees REMAP_DATA=hr . empl oyees. l ast _name: hr . r emap_pckg. modi f ychar
Page 573 Oracle DBA Code Examples

Sampling Export Data
When you sample a parent table, the child table may contain rows unreferenced by the parent. In
such case, impdp will generate "ORA-02298: cannot validate (<foreign key constraint name>)-
parent keys not found"
SAMPLE=[ [ schema_name. ] t abl e_name: ] sampl e_pct
SAMPLE=10
SAMPLE=" HR" . " EMPLOYEES" : 50
Export Encryption Parameters
(11g): To secure the exported dump file, the following new parameters are presented in Oracle 11g
Data pump: ENCRYPTION, ENCRYPTION_PASSWORD and ENCRYPTION_ALGORITHM. To enable
encryption, you must specify either the ENCRYPTION or ENCRYPTION_PASSWORD parameter, or
both.
ENCRYPTI ON = {al l | dat a_onl y | encr ypt ed_col umns_onl y | met adat a_onl y | none}
ENCRYPTI ON_ALGORI THM = { AES128 | AES192 | AES256 }
ENCRYPTI ON_MODE = { DUAL | PASSWORD | TRANSPARENT }
expdp hr DUMPFI LE=dp_di r . hr _enc. dmp J OB_NAME=enc ENCRYPTI ON=dat a_onl y
ENCRYPTI ON_PASSWORD=mypasswor d

expdp hr DI RECTORY=dp_di r DUMPFI LE=hr _enc. dmp
ENCRYPTI ON=al l ENCRYPTI ON_PASSWORD=mypasswor d
ENCRYPTI ON_ALGORI THM=AES256 ENCRYPTI ON_MODE=dual
Export Estimating Parameters
ESTI MATE={BLOCKS | STATI STI CS}
ESTI MATE_ONLY=y
expdp syst em/ pswd est i mat e_onl y=y
Export Network Link Parameter
You can initiate an export job from your server and have Data Pump export data from a remote
database to dump files located on the instance from which you initiate the Data Pump export job.
READ ONLY DB can still be loaded from.
expdp hr / hr DI RECTORY=dpump_di r 1 NETWORK_LI NK=sour ce_dat abase_l i nk
DUMPFI LE=net wor k_expor t . dmp

- - mor e det ai l ed st eps:
- - scenar i o: I wi l l t ake a dat a pump expor t f r omdat abase ORCL
- - and dumpf i l e wi l l be wr i t t en t o dat abase TI GER
sql pl us sa/ a@t i ger
cr eat e dat abase l i nk or cl . net usi ng ' ORCL' ;
OR
Cr eat e dat abase l i nk or cl . net connect t o sa i dent i f i ed by a
usi ng ' ( DESCRI PTI ON=( ADDRESS = ( PROTOCOL = TCP) ( HOST =10. 4. x. x) ( PORT=1521) )
( connect _dat a=( ser vi ce_name=or cl ) ) ) ' ;

sel ect * f r omdual @or cl . net ;

$expdp ar j u/ a@t i ger di r ect or y=d schemas=ar j u dumpf i l e=ar j u_dump_f r om_or cl . dmp
Page 574 Oracle DBA Code Examples

net wor k_l i nk=or cl . net
Export PARALELL Parameter
You should specify number of dump files equal to the PARALLEL value.
expdp syst em/ manager f ul l =y
par al l el =4
dumpf i l e=
DI R1: f ul l 1%U. dat ,
DI R2: f ul l 2%U. dat ,
DI R3: f ul l 3%U. dat ,
DI R4: f ul l 4%U. dat
f i l esi ze = 2G
Import Modes Parameters
You can perform a Data Pump import in various modes, using the TABLE, SCHEMAS, TABLESPACES,
and FULL
File- and Directory-Related Parameters
The Data Pump import utility uses the PARFI LE, DI RECTORY, DUMPFI LE, LOGFI LE, and NOLOGFI LE
commands in the same way as the Data Pump export utility.
SQLFI LE
This parameter enables you to extract the DDL from the export dump file, without importing any data.
i mpdp sal apat i / sammyy1 DI RECTORY=dpump_di r 1 DUMPFI LE=f i nance. dmp
SQLFI LE=dpump_di r 2: f i nance. sql
REUSE_DATAFI LES
This parameter tells Data Pump whether it should use existing datafiles for creating tablespaces during an
import.
Using TABLE_EXISTS_ACTION Parameter
TABLE_EXI STS_ACTI ON=SKI P, APPEND, TRI NCATE, REPLACE
Import Filtering Parameters
Same as export filtering parameters
Import Remapping Parameters
/ * REMAP_TABLE ( 11g) */
- - r ename t abl e dur i ng expor t or i mpor t
- - i t won t wor k i f t abl e al r eady exi st s
i mpdp dumpf i l e=dp_di r : docs. dmp REMAP_TABLE=hr . docs: docs2 user i d=hr / passwor d
i mpdp dumpf i l e=dp_di r : docs. dmp REMAP_TABLE=hr . docs. par t 1: docs3
user i d=hr / passwor d

Page 575 Oracle DBA Code Examples

REMAP_SCHEMA
i mpdp syst em/ manager dumpf i l e=newdump. dmp REMAP_SCHEMA=hr : oe

REMAP_DATAFI LE
Changes the name of the source datafile to the target datafile name in all SQL statements where the
source datafile is referenced: CREATE TABLESPACE, CREATE LI BRARY, and CREATE DI RECTORY.
Remapping datafiles is useful when you move databases between platforms that have different file
naming conventions.
i mpdp hr / hr FULL=y DI RECTORY=dpump_di r 1 DUMPFI LE=db_f ul l . dmp
REMAP_DATAFI LE=' DB1$: [ HRDATA. PAYROLL] t bs6. f ' : ' / db1/ hr dat a/ payr ol l / t bs6. f '

REMAP_TABLESPACE
This parameter enables you to move objects from one tablespace into a different tablespace during an
import.
i mpdp hr / hr REMAP_TABLESPACE=' exampl e_t bs' : ' new_t bs' DI RECTORY=dpump_di r 1
PARALLEL=2 J OB_NAME=cf 1n02 DUMPFI LE=empl oyees. dmp NOLOGFI LE=Y
Ignoring Nondeferred Constraints
(11g): setting the DATA_OPTIONS parameter to SKIP_CONSTRAINT_ERRORS will cause the import
program to skip errors generated by the nondeferred database constraints. In the case of deferred
constraints, imports will always be rolled back.
i mpdp Rober t / r ober t DI RECTORY=dat a_pump_di r DUMPFI LE=r emap. dmp
t abl es=ROBERT. NAMES dat a_opt i ons=SKI P_CONSTRAI NT_ERRORS
Import Network Link Parameter
Get data from a remote database through db link.
Read Only DB can still be loaded from.
When the NETWORK_LINK parameter is used in conjunction with the TABLES parameter, only whole
tables can be imported (not partitions of tables).
If the USERID that is executing the import job has the IMP_FULL_DATABASE role on the target
database, then that user must also have the EXP_FULL_DATABASE role on the source database.
The only types of database links supported by Data Pump Import are: public, fixed-user, and
connected-user. Current-user database links are not supported.
i mpdp hr / hr TABLES=empl oyees DI RECTORY=dpump_di r 1
NETWORK_LI NK=sour ce_dat abase_l i nk EXCLUDE=CONSTRAI NT
Import Flashback Parameters
FLASHBACK_TIME and FLASHBACK_SCN enable you to import data consistent as of the flashback
time you specify in your import job.
i mpdp syst em/ manager FLASHBACK_TI ME=" TO_TI MESTAMP( ' 01- 06- 2009 07: 00: 00; ' , ' DD-
MM- YYYY HH24: MI : SS' ) "
Page 576 Oracle DBA Code Examples

Import PARALELL Parameter
You should specify number of dump files equal to the PARALLEL value.
If you received the errors: ORA-39029, ORA-31671, ORA-39078, try increasing
STREAMS_POOL_SIZE:
alter system set STREAMS_POOL_SIZE=100M;
i mpdp syst em/ manager
di r ect or y = MYDI R
par al l el = 4
dumpf i l e = f ul l 1%U. dat , f ul l 2%U. dat ,
f ul l 3%U. dat , f ul l 4%U. dat
Monitoring a Data Pump Jobs
# dat a pump j obs
SELECT * FROM dba_dat apump_j obs;

# dat a pump sessoi ns
SELECT si d, ser i al #
FROM v$sessi on s, dba_dat apump_sessi ons d
WHERE s. saddr = d. saddr ;

# vi ewi ng j ob pr ogr ess
SELECT opname, t ar get _desc, sof ar , t ot al wor k
FROM v$sessi on_l ongops;
Page 577 Oracle DBA Code Examples

LogMiner
Types of Supplemental Logging
Unconditional supplemental log group: column values are always logged.
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( ALL) COLUMNS;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( PRI MARY KEY) COLUMNS;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( UNI QUE) COLUMNS;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( FOREI GN KEY) COLUMNS;
Conditional supplemental log group: column values are logged if changed.
Levels of Supplemental Logging
Database Level: more resourse consuming, least required level is:
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( PRI MARY KEY) COLUMNS;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA ( UNI QUE) COLUMNS;
Table Level:
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG DATA ( ALL) COLUMNS;
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG DATA ( PRI MARY KEY) COLUMNS;
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG DATA ( UNI QUE) COLUMNS;
Table-Level User-Defined Supplemental Log Groups
o User-defined unconditional log groups
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG GROUP emp_par t t i me
( EMPLOYEE_I D, LAST_NAME, DEPARTMENT_I D) ALWAYS;
o User-defined conditional supplemental log groups
- - al ways keywor d i sn' t used:
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG GROUP emp_f ul l t i me
( EMPLOYEE_I D, LAST_NAME, DEPARTMENT_I D) ;
ALTER TABLE HR. EMPLOYEES ADD SUPPLEMENTAL LOG GROUP emp_par t t i me(
DEPARTMENT_I D NO LOG, EMPLOYEE_I D) ;
Note: you must enable at least minimal supplemental logging prior to generating log files
which will be analyzed by LogMiner.
Disabling Database-Level Supplemental Logging
ALTER DATABASE DROP SUPPLEMENTAL LOG DATA ( PRI MARY KEY) COLUMNS;
ALTER DATABASE DROP SUPPLEMENTAL LOG DATA ( UNI QUE) COLUMNS;
ALTER DATABASE DROP SUPPLEMENTAL LOG DATA;
Page 578 Oracle DBA Code Examples

LogMiner Dictionary Options
Using the Online Catalog: use it, if you believe no DDL is performed during Analysis.
Extracting a LogMiner Dictionary to the Redo Log Files: good if DDL might be there during
analysis
Extracting the LogMiner Dictionary to a Flat File: forget this option!
Redo Log File Options
Automatically: required redo log is automaitcally detected and used by the utility.
Manually: you provide list of the redo files to analyse.
OPTIONS possible values in DBMS_LOGMNR.START_LOGMNR:
DICT_FROM_ONLINE_CATALOG : Using the Online Catalog
DICT_FROM_REDO_LOGS : Start LogMiner
CONTINUOUS_MINE : Redo Log File Options
COMMITTED_DATA_ONLY : Showing Only Committed Transactions
SKIP_CORRUPTION : Skipping Redo Corruptions
NO_SQL_DELIMITER : Formatting Reconstructed SQL Statements for Reexecution
PRINT_PRETTY_SQL : Formatting the Appearance of Returned Data for Readability
NO_ROWID_IN_STMT : Formatting Reconstructed SQL Statements for Reexecution
DDL_DICT_TRACKING : Tracking DDL Statements in the LogMiner Dictionary (not with
DICT_FROM_ONLINE_CATALOG)
Obtaining LogMiner Operational Information
- - speci f i ed r edo l og f i l es
- - STATUS: 0: t he l og f i l e wi l l be pr ocessed
1: t he f i l e wi l l be t he f i r st r edo l og f i l e t o be pr ocessed
2: t he f i l e wi l l not be pr ocessed by LogMi ner ( pr uned)
4: t he f i l e i s mi ssi ng
sel ect * f r omV$LOGMNR_LOGS;

- - opt i onal LogMi ner par amet er s
sel ect * f r omV$LOGMNR_PARAMETERS;

- - cur r ent set t i ngs f or suppl ement al l oggi ng
sel ect SUPPLEMENTAL_LOG_DATA_FK, SUPPLEMENTAL_LOG_DATA_ALL,
SUPPLEMENTAL_LOG_DATA_UI , SUPPLEMENTAL_LOG_DATA_MI N
f r om V$DATABASE;

sel ect * f r om DBA_LOG_GROUPS;

sel ect * f r om ALL_LOG_GROUPS;

sel ect * f r om USER_LOG_GROUPS;

Page 579 Oracle DBA Code Examples

sel ect * f r om DBA_LOG_GROUP_COLUMNS;

sel ect * f r om ALL_LOG_GROUP_COLUMNS;

sel ect * f r om USER_LOG_GROUP_COLUMNS;
Examples of Using LogMiner
Without Sepecifying the Redo Files
Exampl e:
LogMi ner Di ct i onar y: Onl i ne Cat al og,
Redo Log Fi l e Opt i ons: Aut omat i cal l y

- - check Suppl ement al Loggi ng i s enabl ed
( see t he exampl es above)

- - st ar t LogMi ner
ALTER SESSI ON SET NLS_DATE_FORMAT = ' DD- MON- YYYY HH24: MI : SS' ;
begi n
DBMS_LOGMNR. START_LOGMNR(
STARTTI ME => ' 01- J an- 2003 08: 30: 00' ,
ENDTI ME => ' 01- J an- 2003 08: 45: 00' , - - f ut ur e val ue can be set SYSDATE+5/ 24
OPTI ONS => DBMS_LOGMNR. DI CT_FROM_ONLI NE_CATALOG +
DBMS_LOGMNR. CONTI NUOUS_MI NE +
DBMS_LOGMNR. COMMI TTED_DATA_ONLY +
DBMS_LOGMNR. PRI NT_PRETTY_SQL ) ;
end;
/


- - quer y V$LOGMNR_CONTENTS
SELECT USERNAME AS usr , ( XI DUSN | | ' . ' | | XI DSLT | | ' . ' | | XI DSQN) as XI D,
SQL_REDO FROM V$LOGMNR_CONTENTS
WHERE SEG_OWNER I S NULL OR SEG_OWNER NOT I N ( ' SYS' , ' SYSTEM' ) AND
TI MESTAMP > ' 10- j an- 2003 15: 59: 53' ;


SELECT OPERATI ON, SQL_REDO, SQL_UNDO
FROM V$LOGMNR_CONTENTS
WHERE SEG_OWNER = ' OE' AND SEG_NAME = ' ORDERS' AND
OPERATI ON = ' DELETE' AND USERNAME = ' RON' ;

- - Quer yi ng Based on Col umn Val ues
SELECT SQL_REDO FROM V$LOGMNR_CONTENTS
WHERE
SEG_NAME = ' EMPLOYEES' AND
SEG_OWNER = ' HR' AND
OPERATI ON = ' UPDATE' AND
DBMS_LOGMNR. MI NE_VALUE( REDO_VALUE, ' HR. EMPLOYEES. SALARY' )
DBMS_LOGMNR. MI NE_VALUE( UNDO_VALUE, ' HR. EMPLOYEES. SALARY' ) ;


- - end t he Mi ner sessi on
EXECUTE DBMS_LOGMNR. END_LOGMNR;
Page 580 Oracle DBA Code Examples

Wit Sepecifying the Redo Files
Exampl e:
LogMi ner Di ct i onar y: Usi ng t he LogMi ner Di ct i onar y i n t he Redo Log Fi l es,
Redo Log Fi l e Opt i ons: l i st of f i l es pr ovi ded
Redo l og f i l e t hat cont ai ns t he end of t he di ct i onar y ext r act must have been
cr eat ed bef or e t he r edo l og f i l e t hat you want t o anal yze, but shoul d be as
r ecent as possi bl e.
Assume: you want t o anal yze f i l e no 210


- - check Suppl ement al Loggi ng i s enabl ed
( see t he exampl es above)


- TO ext r act t he dat a di ct i onar y t o t he r edo l ogs ( must be done bef or e t he
r edo t o anal yze)
EXECUTE sys. DBMS_LOGMNR_D. bui l d( OPTI ONS =>
sys. DBMS_LOGMNR_D. st or e_i n_r edo_l ogs) ;

- Fi nd a r edo l og f i l e t hat cont ai ns t he end of t he di ct i onar y ext r act
SELECT NAME, SEQUENCE#, DI CTI ONARY_BEGI N d_beg, DI CTI ONARY_END d_end
FROM V$ARCHI VED_LOG
WHERE SEQUENCE# = ( SELECT MAX ( SEQUENCE#) FROM V$ARCHI VED_LOG
WHERE DI CTI ONARY_END = ' YES' and SEQUENCE# <= 210) ;

- Fi nd t he r edo l og f i l e t hat cont ai ns t he st ar t of t he dat a di ct i onar y
ext r act t hat mat ches t he end of t he di ct i onar y f ound i n t he pr evi ous st ep:
SELECT NAME, SEQUENCE#, DI CTI ONARY_BEGI N d_beg, DI CTI ONARY_END d_end
FROM V$ARCHI VED_LOG
WHERE SEQUENCE# = ( SELECT MAX ( SEQUENCE#) FROM V$ARCHI VED_LOG
WHERE DI CTI ONARY_BEGI N = ' YES' and SEQUENCE# <= 208) ;

- Speci f y t he l i st of t he r edo l og f i l es of i nt er est . Or der doesn' t mat t er :
EXECUTE DBMS_LOGMNR. ADD_LOGFI LE( -
LOGFI LENAME => ' / usr / or acl e/ dat a/ db1ar ch_1_210_482701534. dbf ' , -
OPTI ONS => DBMS_LOGMNR. NEW) ;
EXECUTE DBMS_LOGMNR. ADD_LOGFI LE( -
LOGFI LENAME => ' / usr / or acl e/ dat a/ db1ar ch_1_208_482701534. dbf ' ) ;
EXECUTE DBMS_LOGMNR. ADD_LOGFI LE( -
LOGFI LENAME => ' / usr / or acl e/ dat a/ db1ar ch_1_207_482701534. dbf ' ) ;

- Quer y t he V$LOGMNR_LOGS :
SELECT FI LENAME AS name, LOW_TI ME, HI GH_TI ME FROM V$LOGMNR_LOGS;


- St ar t LogMi ner :
EXECUTE DBMS_LOGMNR. START_LOGMNR( -
OPTI ONS => DBMS_LOGMNR. DI CT_FROM_REDO_LOGS + -
DBMS_LOGMNR. COMMI TTED_DATA_ONLY + -
DBMS_LOGMNR. PRI NT_PRETTY_SQL) ;

- Quer y t he V$LOGMNR_CONTENTS:
SELECT USERNAME AS usr , SQL_REDO FROM V$LOGMNR_CONTENTS
WHERE SEG_OWNER I S NULL OR SEG_OWNER NOT I N ( ' SYS' , ' SYSTEM' ) AND
TI MESTAMP > ' 10- j an- 2003 15: 59: 53' ;

- t o di spl ay al l t he DML st at ement s t hat wer e execut ed as par t of t he CREATE
Page 581 Oracle DBA Code Examples

TABLE DDL st at ement :
SELECT SQL_REDO FROM V$LOGMNR_CONTENTS
WHERE XI DUSN = 1 and XI DSLT = 2 and XI DSQN = 1594;

- - end t he Mi ner sessi on
EXECUTE DBMS_LOGMNR. END_LOGMNR;
Page 582 Oracle DBA Code Examples

Part 11 Miscellaneous Oracle Database Topics
Page 583 Oracle DBA Code Examples

Managing Oracle Database Control
Configuring and Using the Database Control
Note ID 1099271.1 Master Note for Enterprise Manager Configuration Assistant (EMCA) in Single
Instance Database Environment is a good reference.
In one situation, I faced the error "System error 1060 has occurred." when I issued the command
emctl start on Oracle 10g for Windows Server. To resolve it:
Issue the command and get from its output the Agent process ID. Usin the Process manager, kill
the corresponding emAgent.exe process. Then issue emctl start command. If error presists, try
killing all the emAgent.exe processes.
- - ORACLE_SI D shoul d be set
expor t ORACLE_SI D=mydb

- - manual l y conf i gur i ng db cont r ol
emca - conf i g dbcont r ol db

emct l st at us dbconsol e
emct l st ar t dbconsol e
emct l st op dbconsol e
ht t p: / / l ocal host : 5500/ em
$ORACLE_HOME/ i nst al l / por t l i st . i ni

i sql pl usct l st ar t
Implementing EM Database Control Auto Startup
# ( 1) as r oot cr eat e or aemct l f i l e
su -
vi / et c/ i ni t . d/ or aemct l

#! / bi n/ bash
#
# or aemct l St ar t i ng and st oppi ng Or acl e Ent er pr i se Manager Dat abase Cont r ol .
# Scr i pt i s val i d f or 10g and 11g ver si ons.
#
# chkconf i g: 35 80 30
# descr i pt i on: Ent er pr i se Manager DB Cont r ol st ar t up scr i pt

# Sour ce f unct i on l i br ar y.

. / et c/ r c. d/ i ni t . d/ f unct i ons

ORACLE_OWNER=" or acl e"
ORA_HOME=" / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1"

case " $1" i n
st ar t )
echo - n $" St ar t i ng Or acl e EM DB Consol e: "
su - $ORACLE_OWNER - c " $ORA_HOME/ bi n/ emct l st ar t dbconsol e"
echo " OK"
Page 584 Oracle DBA Code Examples

; ;
st op)
echo - n $" St oppi ng Or acl e EM DB Consol e: "
su - $ORACLE_OWNER - c " $ORA_HOME/ bi n/ emct l st op dbconsol e"
echo " OK"
; ;
*)
echo $" Usage: $0 {st ar t | st op}"
esac


# ( 2) change per mi ssi ons and r unl evel s
chmod 750 / et c/ i ni t . d/ or aemct l
chkconf i g - - add or aemct l - - l evel 0356
Dropping and Recreating the Management Repository
- - Or acl e 11g R2:
cd / u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ sysman/ admi n/ emdr ep/ bi n
. / RepManager r ac1 1521 r on_1 - sys_passwor d qwer 5 - act i on dr op - r epos_user
sysman

. / RepManager r ac1 1521 r on_1 - sys_passwor d qwer 5 - act i on cr eat e - r epos_user
sysman

Page 585 Oracle DBA Code Examples

Installing Oracle 10g R5 (10.2) Enterprise Manager
Grid Control for Linux x86
Following are the basic installation steps to install Oracle 10.2.0.5 Enterprise Manager Grid
Control on Linux on a new database.
Note: for any installation, you should check the Release Notes documenation before taking
any practical step.
Note: Since Enterprise Manager 10g Grid Control Release 4 or higher are patch sets, you need
to use the 'Installing Software-Only and Configuring Later' installation method as indicated
below. This method is not supported by the interactive OUI.
Installation Environment
Emulation software: VMWare Workstation 7 for Windows
OS: Redhat Enterprise Linux 5.2 for x86 32-bit
Required Software
Oracle Enterprise Manager Grid Control 10.2.0.1 for Linux x86 32-bit
Oracle Enterprise Manager Grid Control 10.2.0.5 for Linux x86 32-bit
The interim RDBMS patch# 4329444
Oracle Database Patch Set Notes 10g Release 1 (10.1.0.5) Patch Set for Linux x86
Used Hardware
In the VMWare: create one virtual machine with the following specs:
o 2 GB RAM
o One ethernet card configured as bridged or host-only in VMware
o CPU Count: 2
o Disk1: 40 GB on SCSI 0:0 used to install the OS and software
Installation Steps
1. Hardware ans Software Requirements
Note: A reference to the requirements is Note ID 419646.1.
# At l east 2 GB of physi cal memor y
gr ep MemTot al / pr oc/ memi nf o

# OS and Ker nel ver si on
Or acl e Ent er pr i se Manager Gr i d Cont r ol Cer t i f i cat i on Checker [ I D 412431. 1]
For OEM 10. 2. 0. 1 i n Li nux 5. 2, onl y sof t war e wi l l be i nst al l ed ( no conf i g)

# swap space: i f RAM=2G, swap=4GB
Page 586 Oracle DBA Code Examples

gr ep SwapTot al / pr oc/ memi nf o

# t o di spl ay swap and memor y i n one command:
f r ee

# i f you don' t have enought swap,
# you can add swap space by cr eat i ng a t empor ar y swap f i l e.
# l et ' s say about 500MB:
dd i f =/ dev/ zer o of =t empswap bs=1k count =500000
chmod 600 t empswap
mke2f s t empswap
mkswap t empswap
swapon t empswap


# r equi r ed packs
r pm- q - - qf ' %{NAME}- %{VERSI ON}- %{RELEASE} ( %{ARCH}) \ n' bi nut i l s \
gl i bc- \
make- \
gcc- \
l i bai o- \
gl i bc- common- \
set ar ch- \
pdksh- \
openmot i f 22 \
sysst at - \
l i bst dc++- \
l i bst dc++- devel - \
compat - l i bst dc++- \
compat - db- \
cont r ol - cent er - \


# i nst al l mi ssed packages
r pm- Uvh l i bXp- 1. 0. 0- 8. 1. el 5. i 386. r pm
r pm- Uvh openmot i f 22- 2. 2. 3- 18. i 386. r pm
r pm- Uvh compat - db- 4. 2. 52- 5. 1. i 386. r pm
r pm- Uvh compat - gcc- 34- 3. 4. 6- 4. i 386. r pm
r pm- Uvh compat - gcc- 34- c++- 3. 4. 6- 4. i 386. r pm

Not e: f or pdksh- 5. 2. 14- 36. el 5. i 386. r pm, i t i sn' t used i n EL 5. 2
2. Configure kernel parameters and shell limits
vi / et c/ sysct l . conf
# mar k exi st i ng ones
ker nel . shmal l = 2097152
ker nel . shmmax = 536870912
ker nel . shmmni = 4096
# semaphor es: semmsl , semmns, semopm, semmni
ker nel . sem= 250 32000 100 128
# t he f ol l owi ng set t i ng i s r emoved because def aul t val ue i s hi gher
# f s. f i l e- max = 65536

# ol d val ues ( 1024 65000) not r ecommended
net . i pv4. i p_l ocal _por t _r ange = 9000 65500
net . cor e. r mem_def aul t = 4194304
net . cor e. r mem_max = 4194304
Page 587 Oracle DBA Code Examples

net . cor e. wmem_def aul t = 262144
net . cor e. wmem_max = 262144
net . i pv4. t cp_wmem= 262144 262144 262144
net . i pv4. t cp_r mem= 4194304 4194304 4194304

# t hen r un:
/ sbi n/ sysct l - p


vi / et c/ secur i t y/ l i mi t s. conf
* sof t npr oc 2047
* har d npr oc 16384
* sof t nof i l e 1024
* har d nof i l e 65536


vi / et c/ pam. d/ l ogi n
sessi on r equi r ed pam_l i mi t s. so

# i n Li nux 5. X r un:
l n - s / usr / l i b/ l i bgdbm. so. 2. 0. 0 / usr / l i b/ l i bdb. so. 2

# SELI NUX must be di sabl ed
cat / et c/ sel i nux/ conf i g | gr ep SELI NUX=
vi / et c/ sel i nux/ conf i g
SELI NUX=di sabl ed
shut down - h now - r
3. Create the required network configuration:
# / et c/ host s f i l e must cont ai n a f ul l y qual i f i ed name:
# <I P- addr ess> <f ul l y- qual i f i ed- machi ne- name> <machi ne- name>
vi / et c/ host s
127. 0. 0. 1 l ocal host . l ocal domai n l ocal host
192. 168. 4. 107 sr v107. l ocal domai n sr v107

pi ng sr v07

4. Create and configure the required OS users, groups and directories
gr oupadd - g 501 oi nst al l
gr oupadd - g 502 dba
# or acl e sof t war e owner user
/ usr / sbi n/ user add - u 200 - g oi nst al l - G dba or acl e
passwd or acl e

# or acl e par ent di r ecot r y
# Or acl e homes wi l l be cr eat ed as subdi r ect or i es under t hi s par ent di r ect or y
mkdi r - p / u01/ app
mkdi r / u01/ st age
chown - R or acl e: oi nst al l / u01
chmod 775 / u01/ app
chmod 775 / u01/ st age

# wi l l be used i nst ead of / t mp by or acl e
mkdi r / home/ or acl e/ or at emp
chown - R or acl e: oi nst al l / home/ or acl e/ or at emp

Page 588 Oracle DBA Code Examples


vi / home/ or acl e/ . bash_pr of i l e
TMP=/ home/ or acl e/ or at emp; expor t TMP
TMPDI R=$TMP; expor t TMPDI R
ORACLE_BASE=/ u01/ app/ or acl e; expor t ORACLE_BASE
ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db10g; expor t ORACLE_HOME
AGENT_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g; expor t AGENT_HOME
OMS_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g; expor t OMS_HOME
ORACLE_HOSTNAME=sr v107. l ocal domai n; expor t ORACLE_HOSTNAME
ORACLE_SI D=oemdb; expor t ORACLE_SI D
ORACLE_TERM=xt er m; expor t ORACLE_TERM
PATH=/ usr / sbi n: $PATH; expor t PATH
PATH=$ORACLE_HOME/ bi n: $PATH; expor t PATH
LD_LI BRARY_PATH=$ORACLE_HOME/ l i b: / l i b: / usr / l i b; expor t LD_LI BRARY_PATH
CLASSPATH=$ORACLE_HOME/ J RE: $ORACLE_HOME/ j l i b: $ORACLE_HOME/ r dbms/ j l i b; expor t
CLASSPATH


vi / et c/ pr of i l e
i f [ $USER = " or acl e" ] ; t hen
i f [ $SHELL = " / bi n/ ksh" ] ; t hen
ul i mi t - p 16384
ul i mi t - n 65536
el se
ul i mi t - u 16384 - n 65536
f i
f i
5. Install the Software
# edi t t he r esponse f i l e
vi / u01/ st age/ gc10. 0. 2. 1/ Di sk1/ r esponse/ em_wi t h_new_db. r sp

FROM_LOCATI ON=" . . / r dbms/ Di sk1/ st age/ pr oduct s. xml "
BASEDI R=" / u01/ app/ or acl e/ pr oduct / 10. 2. 0"
I NSTALLATI ON_NAME=" OEMGC 10. 2. 0. 5"
s_gdbName=" oemdb"
s_mount Poi nt =" / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ or adat a"
s_oper Gr oup=" dba"
s_admi nGr oup=" dba"
s_secur ePasswor d=" qwer 5"
s_secur ePasswor dConf i r m=" qwer 5"
b_l ockedSel ect ed=f al se
b_passwor dsDi f f er ent =f al se
b_passwor dsSame=t r ue
s_r eposPwd=" qwer 5"
s_r eposPwdConf i r m=" qwer 5"
UNI X_GROUP_NAME=" dba"


# i nvoke t he i nst al l er :
# Not e: i f t he f ol der exi st s and not empt y, add - f or ce swi t ch
cd / u01/ st age/ gc10. 0. 2. 1/ Di sk1
. / r unI nst al l er - noconf i g - si l ent - r esponseFi l e
/ u01/ st age/ gc10. 0. 2. 1/ Di sk1/ r esponse/ em_wi t h_new_db. r sp | t ee out put . t xt


# as a root user i n a new t er mi nal :
Page 589 Oracle DBA Code Examples

# ( i f t hi s i s t he f i r st Or acl e pr oduct you j ust i nst al l ed on t he host ) :
/ u01/ app/ or aI nvent or y/ or ai nst Root . sh
# execut e ( answer n t o y/ n quest i ons) :
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db10g/ al l r oot . sh


# st op al l t he OPMN pr ocesses:
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ opmn/ bi n/ opmnct l st opal l

# ver i f y t he pr ocesses wer e st opped:
ps - ef | gr ep opmn
6. Apply the patches on the repository database home
# Appl y t he i nt er i mRDBMS pat ch# 4329444 t o t he Or acl e home of t he dat abase
expor t ORACLE_HOME=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db10g
cd / u01/ st age/ 4329444
expor t OBJ ECT_MODE=32_64
expor t PATH=$PATH: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db10g/ OPat ch
opat ch appl y


# Appl y 10. 1. 0. 5 Pat ch Set
cd / u01/ st age/ db10. 1. 0. 5/ Di sk1
. / r unI nst al l er - i gnor eSysPr er eqs
>sel ect db10g home
>next , next t i l l you f i ni sh appl yi ng t he pat ch set
7. Apply the patch set 10.2.0.5 on OMS and Agent homes
# as r oot : r un t he f ol l owi ng command:
l n - s / usr / l i b/ l i bgdbm. so. 2. 0. 0 / usr / l i b/ l i bdb. so. 2

/ * Appl y t he pat ch on oms */
# edi t t he r esponse f i l e:
vi / u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1/ r esponse/ pat chset . r sp
UNI X_GROUP_NAME=" dba"
b_sof t war eonl y=t r ue
s_sysPasswor d=" qwer 5"
sl _pwdI nf o={ " qwer 5" }
ORACLE_HOME=" / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g"
or acl e. i appser ver . st _mi dt i er : szl _I nst anceI nf or mat i on={" i as_passwor d" }
SHOW_SPLASH_SCREEN=f al se
SHOW_SUMMARY_PAGE=f al se
SHOW_I NSTALL_PROGRESS_PAGE=f al se
SHOW_REQUI RED_CONFI G_TOOL_PAGE=f al se
SHOW_CONFI G_TOOL_PAGE=f al se
SHOW_XML_PREREQ_PAGE=f al se
HOW_END_OF_I NSTALL_MSGS=f al se
SHOW_ROOTSH_CONFI RMATI ON=f al se
SHOW_END_SESSI ON_PAGE=f al se

# appl y t he pat ch set
cd / u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1
. / r unI nst al l er - noconf i g - si l ent - r esponseFi l e
/ u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1/ r esponse/ pat chset . r sp - f or ce | t ee
out put oms. t xt

Page 590 Oracle DBA Code Examples

# open t er mi nal as r oot and r un ( no out put expect ed) :
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ r oot . sh


/ * Appl y t he pat ch on agent */
# change onl y t he f ol l owi ng par amet er s i n t he f i l e:
vi / u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1/ r esponse/ pat chset . r sp
ORACLE_HOME=" / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g"

# appl y t he pat ch on agent :
cd / u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1
. / r unI nst al l er - noconf i g - si l ent - r esponseFi l e
/ u01/ st age/ gc10. 0. 2. 5/ 3731593/ Di sk1/ r esponse/ pat chset . r sp - f or ce | t ee
out put agent . t xt

# as r oot r un:
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g/ r oot . sh
8. Configure the Enterprise Manager Grid Control
expor t PERL5LI B=/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ per l / l i b/ 5. 6. 1

/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ per l / bi n/ per l
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ sysman/ i nst al l / Conf i gur eGC. pl
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0

# t o ver i f y t he conf i gur ed OEM r el ease:
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ bi n/ emct l st at us oms
/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g/ bi n/ emct l st at us agent
9. Running Enterprise Manager Grid Control 10.2.0.5
#f i nd t he EM por t :
cat / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ i nst al l / por t l i st . i ni | gr ep
" Ent er pr i se Manager Cent r al Consol e Por t "


# access t he URL:
ht t p: / / sr v107. l ocal domai n: 4889/ em/


# l ogi n as sysman
10. Deploy Management Agent on Target Machines and Add them to the Grid Control
To add a target host to OEM, you need to install Management Agent on the target
machine.
The steps below uses agentDownload Script method.
/ * I nst al l t he Agent Sof t war e on t he Tar get machi ne */
# Documenat i on of t he scr i pt can be vi ewed:
ht t p: / / <OMS_host >: <OMS_por t >/ agent _downl oad/ agent _i nst al l _r eadme. ht ml
ht t p: / / sr v107. l ocal domai n: 4889/ agent _downl oad/ agent _i nst al l _r eadme. ht ml
OR
<OMS_HOME>/ sysman/ agent _downl oad/ agent _i nst al l _r eadme. ht ml

# The agent Downl oad scr i pt i s l ocat ed at
OMS_HOME/ sysman/ agent _downl oad/ <ver si on>/ <pl at f or m>

Page 591 Oracle DBA Code Examples


# Downl oad t he Management Agent sof t war e
# f r omOTN OR t he " Downl oad Agent Sof t war e" f eat ur e i n t he Gr i d Cont r ol
# consol e
Li nux_Gr i d_Cont r ol _agent _downl oad_10_2_0_5_0. zi p


# I n OEM ser ver , copy t he Agent downl oaded f i l e t o:
<OMS_HOME>/ sysman/ agent _downl oad/ 10. 2. 0. 5. 0


# unzi p t he f i l e:
unzi p Li nux_Gr i d_Cont r ol _agent _downl oad_10_2_0_5_0. zi p


# Downl oad t he agent Downl oad scr i pt t o t he t ar get host f r omt he Management
Ser vi ce URL
ht t p: / / sr v107. l ocal domai n: 4889/ agent _downl oad/ 10. 2. 0. 2. 0/ <pl at f or m>/ agent Downl
oad. <OS>
ht t p: / / sr v107. l ocal domai n: 4889/ agent _downl oad/ 10. 2. 0. 5. 0/ l i nux/ agent Downl oad. l
i nux
OR
scp
or acl e@192. 168. 4. 107: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ oms10g/ sysman/ agent _downl o
ad/ 10. 2. 0. 5. 0/ l i nux/ agent Downl oad. l i nux agent Downl oad. l i nux

chmod 744 agent Downl oad. l i nux


# ensur e t he wget i s t her e and i ncl uded i n t he PATH
l s / usr / l ocal / bi n/ wget
echo $PATH | gr ep / usr / l ocal / bi n


# ensur e t he host names of t he OEM ser ver and t ar get ar e accessbi l e f r omeach
# ot her
pi ng sr v107
pi ng or adb1


# expor t t he r equi r ed env var i abl e
expor t ORACLE_HOSTNAME=or adb1

# RUN THE SCRI PT
# agent 10g wi l l be cr eat ed as a subdi r ect or y
. / agent Downl oad. l i nux - b / u01/ app/ or acl e/ pr oduct / 10. 2. 0 - msr v107 - r 4889


# r un t he scr i pt
su r oot

/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g/ r oot . sh
exi t


# I f t he agent you ar e i nst al l i ng i s not secur e,
# you must execut e t he f ol l owi ng command af t er t he i nst al l at i on i s compl et e:
<Agent _Home>/ bi n/ emct l secur e agent <passwor d>
Page 592 Oracle DBA Code Examples


# st at us of t he agent can be ver i f i ed by:
cd / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ agent 10g/ bi n
# Not e: i n t he out put of t he f ol l owi ng command, t he Agent URL shoul d not be
# ht t ps: / / l ocal host : 1830/ emd/ mai n/ . I f i t i s so, OEM won' t f i nd t he t ar get .
# You need t o r e- i nst al l t he Agent and make sur e you f ol l ow al l t he st eps
# above.
. / emct l st at us agent

# al so you can check:
ht t ps: / / or adb1: 3872/ emd/ mai n/

/ * Add t he Tar get t o OEM */
# l ogi n t o t he OEM and you' l l see t he t ar get al r eady added:
ht t p: / / sr v107. l ocal domai n: 4889/ em/
# cl i ck on Congi ur e but t on t o conf i gur e t he dat abase connect i on i nf o.
Page 593 Oracle DBA Code Examples

Remote Diagnostic Agent (RDA)
Using Remote Diagnostic Agent (RDA)
Refer to note 314422.1
Page 594 Oracle DBA Code Examples

Connect Oracle to SQL Server
Configuring and Using the Database Control

To connect t o SQL*Ser ver f r omOr acl e usi ng Het er geneous Ser vi ces:

1. I nst al l ODBC dr i ver s f or t he SQL*Ser ver dat abase on t he ser ver t hat
cont ai ns t he Or acl e code t r ee.

2. Set up t he ODBC connect i on t o t he SQL Ser ver

3. Test t he ODBC conect i on

4. Ensur e t he GLOBAL_NAMES par amet er i s set t o FALSE i n t he Or acl e dat abase.
show par amet er GLOBAL_NAMES

5. Conf i gur e t he Het er geneous ser vi ces. Thi s consi st s of cr eat i ng an
i ni t odbc. or a f i l e i n <ORACLE_HOME>\ hs\ admi n
For exampl e:
You may cr eat e a f i l e named as i ni t clveodbc. or a cont ai ni ng t he f ol l owi ng:
#
# HS i ni t par amet er s
#
HS_FDS_CONNECT_I NFO = cl ve
HS_FDS_TRACE_LEVEL = of f

#
# Envi r onment var i abl es r equi r ed f or t he non- Or acl e syst em
#
#set <envvar >=<val ue>

7. Modi f y t he Li st ener . or a f i l e :
SI D_LI ST_LI STENER =
( SI D_LI ST =
( SI D_DESC =
( SI D_NAME = PLSExt Pr oc)
( ORACLE_HOME = D: \ or acl e\ pr oduct \ 10. 1. 0\ db_1)
( PROGRAM = ext pr oc)
)
(SID_DESC =
(SID_NAME = CLVEODBC)
(ORACLE_HOME = D:\oracle\product\10.1.0\db_1)
(PROGRAM = HSODBC)
)
( SI D_DESC =
( SI D_NAME = HKCLVEODBC)
( ORACLE_HOME = D: \ or acl e\ pr oduct \ 10. 1. 0\ db_1)
( PROGRAM = HSODBC)
)
)

8. Modi f y t he TNSNAMES. ORA f i l e t o poi nt t o t he pr oper code t r ee.
CLVE. MYDOMAI N. LOCAL =
( DESCRI PTI ON =
Page 595 Oracle DBA Code Examples

( ADDRESS_LI ST =
( ADDRESS = ( PROTOCOL = TCP) ( HOST = au- syd- dw01) ( PORT = 15220) )
)
( CONNECT_DATA =
( SERVI CE_NAME = CLVEODBC)
)
( HS = OK)
)

9. Rel oad t he l i st ener
l snr ct l r el oad

10. Cr eat e a dat abase l i nk on t he Or acl e i nst al l at i on.
CREATE DATABASE LI NK " CLVE. MYDOMAI N. LOCAL"
CONNECT TO " sql user name"
I DENTI FI ED BY " sql user passwor d"
USI NG ' CLVE. MYDOMAI N. LOCAL' ;

11. Run a Sel ect st at ement f or t he Or acl e i nst al l at i on usi ng t he dat abase l i nk
sel ect sysdat e f r omdual @CLVE. MYDOMAI N. LOCAL ;

Page 596 Oracle DBA Code Examples

Part 12 PL/SQL Samples
Page 597 Oracle DBA Code Examples

PL/SQL Basics
PL/SQL Data Types
/ * char act er */
- - max l engt h i n 11g: 32767
DECLARE
v_st r i ng VARCHAR2( 10) ;

DECLARE
v_st r i ng VARCHAR2( 10 CHAR) ;
. . .



/ * number */
BI NARY_DOUBLE
BI NARY_FLOAT
BI NARY_I NTEGER
NUMBER
PLS_I NTEGER 2147483647 t o +2147483647



/ * dat a t i me */
- - TI MESTAMP
sel ect SYSTI MESTAMP f r omdual ;

- - TI MESTAMP WI TH TI ME ZONE
SET SERVEROUTPUT ON
DECLARE
v_dat et i me TI MESTAMP ( 3) WI TH TI ME ZONE : = SYSTI MESTAMP;
BEGI N
DBMS_OUTPUT. PUT_LI NE( v_dat et i me) ;
END;
/

- - TI MESTAMP WI TH LOCAL TI ME ZONE
SET SERVEROUTPUT ON
DECLARE
v_dat et i me TI MESTAMP ( 0) WI TH LOCAL TI ME ZONE : = SYSTI MESTAMP;
BEGI N
DBMS_OUTPUT. PUT_LI NE( v_dat et i me) ;
END;
/



/ * i ner val */
I NTERVAL YEAR TO MONTH
I NTERVAL DAY TO SECOND

DECLARE
v_col l ege_deadl i ne TI MESTAMP;
BEGI N
Page 598 Oracle DBA Code Examples

v_col l ege_deadl i ne : = TO_TI MESTAMP( ' 06/ 06/ 2004' , ' DD/ MM/ YYYY' )
+ I NTERVAL ' 12- 3' YEAR TO MONTH + I NTERVAL ' 19 9: 0: 0. 0' DAY TO SECOND;
DBMS_OUTPUT. PUT_LI NE( ' My daught er l eaves f or col l ege i n ' | |
v_col l ege_deadl i ne) ;
END;
/



/ * REF CURSOR */
- - a poi nt er t o a r esul t set
CREATE OR REPLACE PROCEDURE cust _sel
( cv_r esul t s I N OUT SYS_REFCURSOR)
I S
BEGI N
OPEN cv_r esul t s FOR
SELECT cust omer _i d, cust _l ast _name f r omcust omer s;
END;
/

VARI ABLE x REFCURSOR
EXEC cust _sel ( : x)
PRI NT x

/ * REF */
REF val ue si mpl y as a poi nt er t o an obj ect i nst ance i n an obj ect t abl e or
obj ect vi ew.
Controlling Compile-Time Displayed Warnings
PLSQL_WARNI NGS i s a syst emand sessi on l evel s.
={ ENABLE | DI SABLE | ERROR }:
{ ALL | SEVERE | I NFORMATI ONAL | PERFORMANCE | { i nt eger | ( i nt eger [ , i nt eger
] . . . ) }}

SHOWPARAMETER PLSQL_WARNI NGS
- - i t can t ake one val ue
PLSQL_WARNI NGS=' ENABLE: PERFORMANCE'

- - i t can t ake mul t i pl e val ues
PLSQL_WARNI NGS=' ENABLE: PERFORMANCE' , ' ENABLE: SEVERE'

- - mor e exampl es:
PLSQL_WARNI NGS = ' ENABLE: SEVERE' , ' DI SABLE: I NFORMATI ONAL' ;
PLSQL_WARNI NGS = ' DI SABLE: ALL' ;
PLSQL_WARNI NGS = ' DI SABLE: 5000' , ' ENABLE: 5001' ,
' ERROR: 5002' ;
PLSQL_WARNI NGS = ' ENABLE: ( 5000, 5001, 5002) ' ,
' DI SABLE: ( 6000, 6001) ' ;

- - set t i ng t he par amet er usi ng DBMS_WARNI NG
SELECT DBMS_WARNI NG. GET_WARNI NG_SETTI NG_STRI NG( ) WARNI NG_LEVEL FROM dual ;

CALL DBMS_WARNI NG. SET_WARNI NG_SETTI NG_STRI NG( ' ENABLE: ALL' , ' SESSI ON' ) ;
CALL DBMS_WARNI NG. SET_WARNI NG_SETTI NG_STRI NG( ' DI SABLE: ALL' , ' SESSI ON' ) ;
Page 599 Oracle DBA Code Examples

Catching Returned Errors
. .
EXCEPTI ON
WHEN OTHERS THEN
DBMS_OUTPUT. PUT_LI NE( ' Except i on: ' | | sql er r m) ;
. .
Hiding Code
wr ap i name=i nput _f i l e. sql oname=out put _f i l e. pl b
Controlling Program Flow
/ * I F */
I F condi t i on THEN
act i on
ELSI F condi t i on THEN
act i on
ELSE
act i on
END I F;

/ * CASE */
CASE expr essi on
WHEN t est 1 THEN act i on;
WHEN t est 2 THEN act i on;
. . .
ELSE
. . .
END CASE;

CASE v_cat egor y
WHEN ' Or acl e Basi cs'
THEN v_di scount : = . 15;
WHEN ' Or acl e Ser ver '
THEN v_di scount : = . 10;
ELSE v_di scount : = . 5;
END CASE;



/ * Sear ched CASE */
CASE
WHEN <exp> THEN
act i ons;
WHEN <exp> THEN
act i ons;
ELSE
act i ons;
END CASE;



/ * Case Expr essi ons */
Page 600 Oracle DBA Code Examples

appr ai sal : =
CASE gr ade
WHEN ' A' THEN ' Excel l ent '
WHEN ' B' THEN ' Ver y Good'
WHEN ' C' THEN ' Good'
ELSE ' No such gr ade'
END;

appr ai sal : =
CASE
WHEN gr ade = ' A' THEN ' Excel l ent '
WHEN gr ade I N ( ' B' , ' C' ) THEN ' Good'
ELSE ' No such gr ade'
END;


/ * Loop */
LOOP
. .
EXI T [ WHEN condi t i on]
END LOOP;

- - l oops and l abl el s
BEGI N
<<Out er _l oop>>
LOOP
count er : = count er +1;
EXI T WHEN count er >10;
<<I nner _l oop>>
LOOP
. . .
EXI T Out er _l oop WHEN t ot al _done = ' YES' ;
- - Leave bot h l oops
EXI T WHEN i nner _done = ' YES' ;
- - Leave i nner l oop onl y
. . .
END LOOP I nner _l oop;
. . .
END LOOP Out er _l oop;
END;
/



/ * Numer i c FOR Loop */
FOR count er I N [ r ever se] l ow_number . . hi gh_number LOOP
act i on;
END LOOP;

begi n
f or i i n r ever se 1. . 10 l oop
dbms_out put . put _l i ne( i ) ;
end l oop;
end;
/


Page 601 Oracle DBA Code Examples

/ * WHI LE Loop */
WHI LE condi t i on LOOP
. .
END LOOP;


/ * Got o and Label s */
BEGI N
DBMS_OUTPUT. PUT_LI NE( ' BEGI NNI NG OF BLOCK' ) ;
GOTO l _Last _Li ne;
DBMS_OUTPUT. PUT_LI NE( ' GOTO di dn' ' t wor k! ' ) ;
RETURN;
<<l _Last _Li ne>>
DBMS_OUTPUT. PUT_LI NE( ' Last Li ne' ) ;
END;
/
Page 602 Oracle DBA Code Examples

Using Cursors
CURSOR cur sor _name [ par amet er _l i st ]
[ RETURN r et ur n_t ype]
I S quer y [ FOR UPDATE [ OF ( col umn_l i st ) ] [ NOWAI T] ] ;

OPEN cur 1;
OPEN cur 1( 50) ;

FETCH cur sor _name I NTO var i abl e_name( s) | PL/ SQL_r ecor d;

CLOSE cur sor _name;

Cur sor At t r i but es:
%BULK_ROWCOUNT number of r ows changed dur i ng t he oper at i on
%ROWCOUNT number of r ows f et ched f r omt he cur sor at any gi ven t i me
%FOUND
%I SOPEN
%NOTFOUND
- - exampl e 1
SET SERVEROUTPUT ON
DECLARE
v_f i r st _name AUTHORS. FI RST_NAME%TYPE;
v_l ast _name AUTHORS. LAST_NAME%TYPE;
v_r ow_count PLS_I NTEGER : = 0;
v_book_count PLS_I NTEGER : = 0;
CURSOR aut h_cur I S
SELECT a. f i r st _name, a. l ast _name, count ( b. t i t l e)
FROM aut hor s a, books b
WHERE a. i d = b. aut hor 1
OR a. i d = b. aut hor 2
OR a. i d = b. aut hor 3
GROUP BY a. f i r st _name, a. l ast _name
HAVI NG count ( b. t i t l e) > 0
ORDER BY a. l ast _name;
BEGI N
DBMS_OUTPUT. ENABLE( 1000000) ;
OPEN aut h_cur ;
LOOP
FETCH aut h_cur I NTO v_f i r st _name, v_l ast _name, v_book_count ;
EXI T WHEN aut h_cur %NOTFOUND;
v_r ow_count : = aut h_cur %ROWCOUNT;
DBMS_OUTPUT. PUT_LI NE( v_r ow_count | | ' r ows pr ocessed so f ar ' ) ;
DBMS_OUTPUT. PUT_LI NE( v_l ast _name | | ' , ' | | v_f i r st _name | | ' wr ot e '
| | v_book_count | | ' book( s) . ' ) ;
END LOOP;
CLOSE aut h_cur ;
I F aut h_cur %I SOPEN = FALSE THEN
DBMS_OUTPUT. PUT_LI NE( ' Cur sor cl osed' ) ;
ELSE
DBMS_OUTPUT. PUT_LI NE( ' The cur sor i s st i l l open' ) ;
END I F;
EXCEPTI ON
Page 603 Oracle DBA Code Examples

WHEN OTHERS THEN
DBMS_OUTPUT. PUT_LI NE( SQLERRM) ;
END;
/


- - exampl e 2
. .
WHI LE aut h_cur %FOUND LOOP
DBMS_OUTPUT. PUT_LI NE( v_aut hor . l ast _name) ;
FETCH aut h_cur I NTO v_aut hor ;
END LOOP;
. .


- - exampl e 3
SET SERVEROUTPUT ON
DECLARE
CURSOR aut h_cur I S
SELECT * FROM aut hor s;
BEGI N
FOR v_aut hor I N aut h_cur LOOP
DBMS_OUTPUT. PUT_LI NE( v_aut hor . l ast _name) ;
END LOOP;
END;
/



/ * Cur sor Var i abl es */
SET SERVEROUTPUT ON
DECLARE
TYPE book_t yp I S REF CURSOR RETURN BOOKS%ROWTYPE;
cv_books book_t yp;
v_books BOOKS%ROWTYPE;
BEGI N
DBMS_OUTPUT. ENABLE( 1000000) ;
OPEN cv_books FOR
SELECT * FROM books WHERE i sbn = ' 78824389' ;
FETCH cv_books I NTO v_books;
DBMS_OUTPUT. PUT_LI NE( v_books. t i t l e| | ' i s ' | | v_books. pr i ce) ;
CLOSE cv_books;
END;
/


CREATE OR REPLACE PROCEDURE aut hor s_sel
( cv_r esul t s I N OUT SYS_REFCURSOR)
I S
BEGI N
OPEN cv_r esul t s FOR SELECT i d, f i r st _name, l ast _name
FROM aut hor s;
END;
/
VARI ABLE x REFCURSOR
EXEC aut hor s_sel ( : x)
PRI NT x
Page 604 Oracle DBA Code Examples




/ * Handl i ng I mpl i ci t Cur sor s */
SET SERVEROUTPUT ON
BEGI N
DBMS_OUTPUT. ENABLE( 1000000) ;
UPDATE books
SET pr i ce = pr i ce * . 90
WHERE i sbn = ' 78824389' ;
DBMS_OUTPUT. PUT_LI NE( SQL%ROWCOUNT| | ' r ows updat ed' ) ;
I F SQL%NOTFOUND THEN
DBMS_OUTPUT. PUT_LI NE( ' Unabl e t o updat e i sbn 78824389' ) ;
END I F;
COMMI T;
EXCEPTI ON
WHEN OTHERS
THEN
DBMS_OUTPUT. PUT_LI NE( SQLERRM) ;
END;
/


/ * Cur sor Subquer i es */
SET SERVEROUTPUT ON
DECLARE
cv_aut hor SYS_REFCURSOR;
v_t i t l e BOOKS. TI TLE%TYPE;
v_aut hor AUTHORS%ROWTYPE;
v_count er PLS_I NTEGER : = 0;
CURSOR book_cur I S
SELECT b. t i t l e,
CURSOR ( SELECT *
FROM aut hor s a
WHERE a. i d = b. aut hor 1
OR a. i d = b. aut hor 2
OR a. i d = b. aut hor 3)
FROM books b WHERE i sbn = ' 78824389' ;
BEGI N
OPEN book_cur ;
LOOP
FETCH book_cur I NTO v_t i t l e, cv_aut hor ;
EXI T WHEN book_cur %NOTFOUND;
DBMS_OUTPUT. PUT_LI NE( ' Ti t l e f r omt he mai n cur sor : ' | | v_t i t l e) ;
LOOP
FETCH cv_aut hor I NTO v_aut hor ;
EXI T WHEN cv_aut hor %NOTFOUND;
v_count er : = v_count er + 1;
DBMS_OUTPUT. PUT_LI NE( ' Aut hor ' | | v_count er | | ' : '
| | v_aut hor . f i r st _name| | ' ' | | v_aut hor . l ast _name) ;
END LOOP;
END LOOP;
CLOSE book_cur ;
END;
/


Page 605 Oracle DBA Code Examples

/ * Usi ng Wher e Cur r ent of */
SET SERVEROUTPUT ON
DECLARE
v_i sbn I NVENTORY. I SBN%TYPE;
v_amount I NVENTORY. AMOUNT%TYPE;
CURSOR i nvent or y_cur
I S
SELECT i sbn, amount
FROM i nvent or y
WHERE st at us = I N STOCK
AND i sbn I N ( SELECT i sbn
FROM books
WHERE pr i ce > 40)
FOR UPDATE OF amount ;
BEGI N
FOR y I N i nvent or y_cur
LOOP
FETCH i nvent or y_cur I NTO v_i sbn, v_amount ;
EXI T WHEN i nvent or y_cur %NOTFOUND;
DBMS_OUTPUT. PUT_LI NE( v_i sbn| | Amount I N STOCK bef or e: | | v_amount ) ;
v_amount : = v_amount + 250;
UPDATE i nvent or y
SET amount = v_amount
WHERE CURRENT OF i nvent or y_cur ;
DBMS_OUTPUT. PUT_LI NE( v_i sbn| | Amount I N STOCK af t er : | | v_amount ) ;
END LOOP;
COMMI T;
EXCEPTI ON
WHEN OTHERS THEN
DBMS_OUTPUT. PUT_LI NE( SQLERRM) ;
ROLLBACK;
END;
/
Page 606 Oracle DBA Code Examples

Using Records
DECLARE
TYPE i ndi vi dual _r ecor d I S RECORD
( i ndi vi dual _i d I NTEGER
, f i r st _name VARCHAR2( 30 CHAR)
, mi ddl e_i ni t i al i ndi vi dual s. mi ddl e_i ni t i al %TYPE
, l ast _name VARCHAR2( 30 CHAR) ) ;

- - Def i ne a var i abl e of t he r ecor d t ype.
i ndi vi dual I NDI VI DUAL_RECORD;
BEGI N
- - I ni t i al i ze t he f i el d val ues f or t he r ecor d.
i ndi vi dual . i ndi vi dual _i d : = 2;
i ndi vi dual . f i r st _name : = ' J ohn' ;
i ndi vi dual . mi ddl e_i ni t i al : = ' P' ;
i ndi vi dual . l ast _name : = ' Mor gan' ;

- - I nser t i nt o t he t abl e.
I NSERT
I NTO i ndi vi dual s
VALUES
( i ndi vi dual . i ndi vi dual _i d
, i ndi vi dual . f i r st _name
, i ndi vi dual . mi ddl e_i ni t i al
, i ndi vi dual . l ast _name) ;
- - Commi t t he wor k.
COMMI T;
END;
/


- - nest ed r ecor ds
DECLARE
- - Def i ne a r ecor d t ype.
TYPE i ndi vi dual _r ecor d I S RECORD
( i ndi vi dual _i d I NTEGER
, f i r st _name VARCHAR2( 30 CHAR)
, mi ddl e_i ni t i al VARCHAR2( 1 CHAR)
, l ast _name VARCHAR2( 30 CHAR) ) ;

- - Def i ne a r ecor d t ype.
TYPE addr ess_r ecor d I S RECORD
( addr ess_i d I NTEGER
, i ndi vi dual _i d I NTEGER
, st r eet _addr ess1 VARCHAR2( 30 CHAR)
, st r eet _addr ess2 VARCHAR2( 30 CHAR)
Page 607 Oracle DBA Code Examples

, st r eet _addr ess3 VARCHAR2( 30 CHAR) ) ;

- - Def i ne a r ecor d t ype of t wo user - def i ned r ecor d t ypes.
TYPE i ndi vi dual _addr ess_r ecor d I S RECORD
( i ndi vi dual I NDI VI DUAL_RECORD
, addr ess ADDRESS_RECORD) ;

- - Def i ne a user - def i ned compound r ecor d t ype.
i ndi vi dual _addr ess I NDI VI DUAL_ADDRESS_RECORD;

BEGI N
- - I ni t i al i ze t he f i el d val ues f or t he r ecor d.
i ndi vi dual _addr ess. i ndi vi dual . i ndi vi dual _i d : = 3;
i ndi vi dual _addr ess. i ndi vi dual . f i r st _name : = ' Ul ysses' ;
. . .


- - Recor d Types can be expl i ci t l y def i ned as Obj ect Type as wel l


- - Def i ni ng and Usi ng Recor d Types as Ret ur n Val ues
DECLARE
- - Def i ne a r ecor d t ype.
FUNCTI ON get _r ow ( i ndi vi dual _i d_i n I NTEGER)
RETURN I NDI VI DUAL_RECORD I S
- - Def i ne a cur sor t o r et ur n a r ow of i ndi vi dual s.
CURSOR c ( i ndi vi dual _i d_cur sor I NTEGER) I S
SELECT *
FROM i ndi vi dual s
WHERE i ndi vi dual _i d = i ndi vi dual _i d_cur sor ;
BEGI N
- - Loop t hr ough t he cur sor f or a si ngl e r ow.
FOR i I N c( i ndi vi dual _i d_i n) LOOP
- - Ret ur n a %ROWTYPE f r omt he I NDI VI DUALS t abl e.
RETURN i ;
END LOOP;
END get _r ow;
Page 608 Oracle DBA Code Examples

Using Table Functions
/* Table Function (not pipelined) */
- - not pi pel i ned: r ow set wi l l be r et ur ned when al l r ows ar e f et ched
/ * */
CREATE TYPE BookType AS OBJ ECT (
i sbn CHAR( 10) ,
t i t l e VARCHAR2( 100)
)
/

CREATE TYPE BookTypes AS TABLE OF BookType;
/

CREATE OR REPLACE FUNCTI ON SomeBooks( p_Cat egor y I N books. cat egor y%TYPE)
RETURN BookTypes AS
v_Resul t Set BookTypes : = BookTypes( ) ;
CURSOR c_SomeBooks I S
SELECT i sbn, t i t l e
FROM books
WHERE cat egor y = p_Cat egor y;

BEGI N
FOR v_Rec I N c_SomeBooks LOOP
v_Resul t Set . EXTEND;
v_Resul t Set ( v_Resul t Set . LAST) : = BookType( v_Rec. i sbn, v_Rec. t i t l e) ;
END LOOP;
RETURN v_Resul t Set ;
END SomeBooks;
/


SELECT SomeBooks( ' Or acl e Basi cs' ) FROM dual ;

COLUMN t i t l e FORMAT a60

SELECT *
FROM TABLE ( SomeBooks( ' Or acl e Basi cs' ) ) ;


- - Si nce SomeBooks wi l l al ways r et ur n t he same out put gi ven t he same
- - i nput , we can use t he DETERMI NI STI C keywor d.
- - i t s supposed posi t i ve i mpact i s not pr oved t hough
CREATE OR REPLACE FUNCTI ON SomeBooks( p_Cat egor y I N books. cat egor y%TYPE)
RETURN BookTypes DETERMI NI STI C AS



/* Example of using pipelined table functions in data transformation */
- - wi t h pi pel i ned t abl e f unct i ons, each r ow wi l l be r et ur ned as soon
- - - as i t i s cr eat ed

- - sampl e dest i nat i on t abl e
CREATE TABLE year l y_st or e_sal es
( st or e_name VARCHAR2( 25) ,
sal es_year NUMBER,
t ot al _sal es NUMBER) ;

- - ( 1) cr eat e t ype
CREATE TYPE year l y_st or e_sal es_r ow AS
OBJ ECT(
Page 609 Oracle DBA Code Examples

st or e_name var char 2( 25) ,
sal es_year number ,
t ot al _sal es number ) ;

- - ( 2) cr eat e PL/ SQL t abl e of t he t ype
CREATE TYPE year l y_st or e_sal es_t abl e
AS
TABLE OF year l y_st or e_sal es_r ow;

- - ( 3) cr eat e package, or f unct i on
CREATE OR REPLACE PACKAGE sal es_package
AS
TYPE sal es_cur sor _t ype I S REF CURSOR RETURN sal es_dat a%ROWTYPE;

FUNCTI ON modi f y_sal es_dat a ( I NPUTDATA I N sal es_cur sor _t ype)
RETURN year l y_st or e_sal es_t abl e PI PELI NED;

END;
/

CREATE OR REPLACE PACKAGE BODY sal es_package
AS
FUNCTI ON modi f y_sal es_dat a( i nput dat a I N sal es_cur sor _t ype)
RETURN year l y_st or e_sal es_t abl e PI PELI NED
I S
i nput r ec sal es_dat a%ROWTYPE;
out put r ow_2001 year l y_st or e_sal es_r ow : =
year l y_st or e_sal es_r ow( NULL, NULL, NULL) ;
out put r ow_2002 year l y_st or e_sal es_r ow : =
year l y_st or e_sal es_r ow( NULL, NULL, NULL) ;
BEGI N
LOOP
FETCH i nput dat a I NTO i nput r ec;
EXI T WHEN i nput dat a%NOTFOUND;
I F I NPUTREC. SALES_2001 I S NOT NULL THEN
out put r ow_2001. st or e_name : = i nput r ec. st or e_name;
out put r ow_2001. sal es_year : = 2001;
out put r ow_2001. t ot al _sal es: = i nput r ec. sal es_2001;
pi pe r ow ( out put r ow_2001) ;
END I F;
I F I NPUTREC. SALES_2002 I S NOT NULL THEN
out put r ow_2002. st or e_name : = i nput r ec. st or e_name;
out put r ow_2002. sal es_year : = 2002;
out put r ow_2002. t ot al _sal es: = i nput r ec. sal es_2002;
pi pe r ow ( out put r ow_2002) ;
END I F;
END LOOP;
RETURN;
END;
END sal es_package;
/

- - ( 4) usage
SELECT *
FROM
TABLE( sal es_package. modi f y_sal es_dat a( CURSOR( sel ect
st or e_name, sal es_2001, sal es_2002 FROM sal es_dat a) ) ) ;
Page 610 Oracle DBA Code Examples

Using Collections
Varrays Fixed: may not be used in tables
Nested tables Fixed: may be used in tables
Associative arrays (index-by PL/SQL tables) Dynamic

Multiset Operator Its Equivalent in SQL
MULTISET EXCEPT MINUS
MULTISET INTERSECT INTERSECT
MULTISET UNION UNION ALL
SET DISTINCT
Using VARRAYS
Although VARRAYS can be stored as part of a table, it is best suited for PL/SQL
proccessing.
TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit)
OF element_type [ NOT NULL ];
- - i ni t i al i zed i n t he decl ar at i on sect i on
DECLARE
TYPE i nt eger _var r ay I S VARRAY( 3) OF I NTEGER;
Decl ar e and i ni t i al i ze a var r ay t hat al l ows nul l s.
var r ay_i nt eger I NTEGER_VARRAY : = i nt eger _var r ay( NULL, NULL, NULL) ;
BEGI N
Assi gn val ues t o subscr i pt ed member s of t he var r ay.
var r ay_i nt eger ( 1) : = 11;
var r ay_i nt eger ( 2) : = 12;
var r ay_i nt eger ( 3) : = 13;
FOR i I N 1. . 3 LOOP
dbms_out put . put _l i ne( ' I nt eger Var r ay [ ' | | i | | ' ] ' | |
' [ ' | | var r ay_i nt eger ( i ) | | ' ] ' ) ;
END LOOP;
END;
/

- - i ni t i al i zed wi t h zer o r ows i n t he decl ar at i on
- - t hen dynami c i ni t i al i zat i on i n t he execut i on
DECLARE
Def i ne a var r ay of i nt eger wi t h 3 r ows.
TYPE i nt eger _var r ay I S VARRAY( 3) OF I NTEGER;
Decl ar e and i ni t i al i ze a nul l set of r ows.
var r ay_i nt eger I NTEGER_VARRAY : = i nt eger _var r ay( ) ;
BEGI N
Loop t hr ough t he t hr ee r ecor ds.
FOR i I N 1. . 3 LOOP
Page 611 Oracle DBA Code Examples

I ni t i al i ze r ow.
var r ay_i nt eger . EXTEND;
Assi gn val ues t o subscr i pt ed member s of t he var r ay.
var r ay_i nt eger ( i ) : = 10 + i ;
END LOOP;
Loop t hr ough t he r ecor ds t o pr i nt t he var r ays.
FOR i I N 1. . 3 LOOP
Pr i nt t he cont ent s.
dbms_out put . put ( ' I nt eger Var r ay [ ' | | i | | ' ] ' ) ;
dbms_out put . put _l i ne( ' [ ' | | var r ay_i nt eger ( i ) | | ' ] ' ) ;
END LOOP;
END;
/


- - Var r ays as Obj ect Types
CREATE OR REPLACE TYPE i nt eger _var r ay
AS VARRAY( 3) OF I NTEGER;


- - i ni t i al i zi ng by Col l ect i on API
CREATE OR REPLACE TYPE i nt eger _var r ay
AS VARRAY( 100) OF I NTEGER NOT NULL;
/
DECLARE
Decl ar e and i ni t i al i ze a nul l set of r ows.
var r ay_i nt eger I NTEGER_VARRAY : = i nt eger _var r ay( ) ;
BEGI N
Loop t hr ough al l r ecor ds.
FOR i I N 1. . var r ay_i nt eger . LI MI T LOOP
I ni t i al i ze r ow.
var r ay_i nt eger . EXTEND;
END LOOP;

dbms_out put . put ( ' I nt eger Var r ay I ni t i al i zed ' ) ;
dbms_out put . put _l i ne( ' [ ' | | var r ay_i nt eger . COUNT| | ' ] ' ) ;
END;
/


- - Usi ng Var r ays as Col umn Dat a Types i n Tabl es
- - i t doesn' t pr oduce meani ngf ul out put
CREATE OR REPLACE TYPE addr ess_var r ay
AS VARRAY( 3) OF VARCHAR2( 30 CHAR) ;
/
CREATE TABLE addr esses
( addr ess_i d I NTEGER NOT NULL
. .
, st r eet _addr ess ADDRESS_VARRAY NOT NULL
Page 612 Oracle DBA Code Examples

. .
) ;

I NSERT I NTO addr esses
VALUES
( . . , addr ess_var r ay( ' MyAddr ess' , ' 450 West Paseo Redondo' , ' Sui t e 200' ) , . . ) ;

- - you can i nser t onl y one el ement of t he var r ay
I NSERT
I NTO addr esses
VALUES ( 12 , 12 , addr ess_var r ay( ' Of f i ce of Senat or Kennedy' ) , . . ) ;

- - i t gi ves t hough unmeani ngf ul out put
SELECT st r eet _addr ess FROM addr esses;
STREET_ADDRESS
-
ADDRESS_VARRAY( ' MyAddr ess' , ' 450 West Paseo . . .

UPDATE addr esses
SET st r eet _addr ess =
addr ess_var r ay( ' Your Addr ess' , ' 2400 E. Ar i zona Bi l t mor e Ci r . '
, ' Sui t e 1150' )
WHERE addr ess_i d = 11;

- - t o updat e a por t i on of a var r ay col umn, you must use pl / sql
DECLARE
Def i ne a r ecor d t ype f or a r ow of t he addr esses t abl e.
TYPE addr ess_t ype I S RECORD . . ;
Def i ne a var i abl e of t he addr esses t abl e r ecor d t ype.
addr ess ADDRESS_TYPE;
Def i ne a cur sor t o r et ur n t he %ROWTYPE val ue.
CURSOR get _st r eet _addr ess
( addr ess_i d_i n I NTEGER) I S
SELECT *
FROM addr esses
WHERE addr ess_i d = addr ess_i d_i n;
BEGI N
Open t he cur sor .
OPEN get _st r eet _addr ess( 11) ;
Fet ch a i nt o t he r ecor d t ype var i abl e.
FETCH get _st r eet _addr ess
I NTO addr ess;
Cl ose t he cur sor .
CLOSE get _st r eet _addr ess;
Reset t he f i r st el ement of t he var r ay t ype var i abl e.
addr ess. st r eet _addr ess( 1) : =
' Of f i ce of Senat or J ohn McCai n' ;
Updat e t he var r ay col umn val ue.
UPDATE addr esses
Page 613 Oracle DBA Code Examples

SET st r eet _addr ess = addr ess. st r eet _addr ess
WHERE addr ess_i d = 11;
END;
Using Nested Tables
Nested tables may be used in table, record, and object definitions. They may be accessed
in SQL and PL/SQL.
CREATE OR REPLACE TYPE type_name
AS TABLE OF element_type [ NOT NULL ];
- - basi c exampl e
DECLARE
- - Def i ne a nest ed t abl e of var i abl e l engt h st r i ngs.
TYPE car d_t abl e I S TABLE OF VARCHAR2( 5 CHAR) ;

- - Decl ar e and i ni t i al i ze a nest ed t abl e wi t h t hr ee r ows.
car ds CARD_TABLE : = car d_t abl e( NULL, NULL, NULL) ;
BEGI N
- - Assi gn val ues t o subscr i pt ed member s of t he var r ay.
car ds( 1) : = ' Ace' ;
car ds( 2) : = ' Two' ;
car ds( 3) : = ' Thr ee' ;
END;
/


- - dynami c i ni t i al i zat i on and assi gnment i n t he execut i on sect i on
DECLARE
- - Def i ne a nest ed t abl e of var i abl e l engt h st r i ngs.
TYPE car d_sui t I S TABLE OF VARCHAR2( 5 CHAR) ;

- - Decl ar e and i ni t i al i ze a nul l set of r ows.
car ds CARD_SUI T : = car d_sui t ( ) ;
BEGI N
- - Loop t hr ough t he t hr ee r ecor ds.
FOR i I N 1. . 3 LOOP
- - I ni t i al i ze r ow.
car ds. EXTEND;
- - Assi gn val ues t o subscr i pt ed member s of t he var r ay.
I F i = 1 THEN
car ds( i ) : = ' Ace' ;
ELSI F i = 2 THEN
car ds( i ) : = ' Two' ;
ELSI F i = 3 THEN
car ds( i ) : = ' Thr ee' ;
END I F;
END LOOP;
END;
/



- - Nest ed Tabl es as Col umn Dat a Types i n Tabl es
CREATE OR REPLACE TYPE addr ess_t abl e
AS TABLE OF VARCHAR2( 30 CHAR) NOT NULL;
Page 614 Oracle DBA Code Examples

/

CREATE TABLE addr esses
( . .
, st r eet _addr ess ADDRESS_TABLE
. . . )
NESTED TABLE st r eet _addr ess
STORE AS nest ed_st r eet _addr ess;

- - any number of el ement s can be i nser t ed
I NSERT I NTO addr esses
VALUES
( . . , addr ess_t abl e( ' Of f i ce of Senat or McCai n'
, ' 450 West Paseo Redondo' , ' Sui t e 200' ) , . . . ) ;


- - ar r ange gener at ed out put
- - t he nor mal out put :
SELECT st r eet _addr ess FROM addr esses;
ADDRESS_TABLE( ' Of f i ce of Senat or McCai n' , ' 450 West Paseo . . .
- - t o ar r ange i t :
SELECT col umn_val ue
FROM THE ( SELECT st r eet _addr ess FROM addr esses WHERE i d = 1) ;


- - updat i ng a nest ed- t abl e usi ng pl / sql
CREATE OR REPLACE FUNCTI ON many_t o_one
( st r eet _addr ess_i n ADDRESS_TABLE) RETURN VARCHAR2 I S
Def i ne a r et ur n var i abl e and i ni t i al i t .
r et val VARCHAR2( 4000) : = ' ' ;
BEGI N
Loop f r omt he begi nni ng t o end of t he nest ed t abl e.
FOR i I N 1. . st r eet _addr ess_i n. COUNT LOOP
Append t he next val ue and a l i ne br eak.
r et val : = r et val | | st r eet _addr ess_i n( i ) | | CHR( 10) ;
END LOOP;
RETURN r et val ;
END many_t o_one;
/


- - You can updat e a por t i on of a nest ed t abl e col umn di r ect l y i n SQL:
UPDATE THE ( SELECT st r eet _addr ess
FROM addr esses
WHERE addr ess_i d = 21)
SET col umn_val ue = ' Of f i ce of Senat or J ohn McCai n'
WHERE col umn_val ue = ' Of f i ce of Senat or McCai n' ;
Using Associative Arrays
Associative arrays cannot be used in tables. They are the key to using the FORALL
statement or BULK COLLECT clause.
This collection provides faster and simpler lookups
CREATE OR REPLACE TYPE type_name
Page 615 Oracle DBA Code Examples

AS TABLE OF element_type [ NOT NULL ] INDEX BY [ PLS_INTEGER | BINARY_INTEGER |
VARCHAR2(size) ]
- - i ndex by i nt eger
DECLARE
- - Def i ne an associ at i ve ar r ay of st r i ngs.
TYPE car d_t abl e I S TABLE OF VARCHAR2( 5 CHAR) I NDEX BY BI NARY_I NTEGER;
car ds CARD_TABLE;
BEGI N
car ds( 2) : = ' t est ' ;
car ds( 10) : = ' t est ' ;
car ds( 1) : = ' t est ' ;
DBMS_OUTPUT. PUT_LI NE( car ds. f i r st ) ;
DBMS_OUTPUT. PUT_LI NE( car ds. l ast ) ;
DBMS_OUTPUT. PUT_LI NE( car ds. count ) ;
END;
/



- - i ndex by st r i ng
. .
- - Loop t hr ough al l t he associ at i ve ar r ay el ement s.
FOR i I N 1. . cal endar . COUNT LOOP
- - Check i f t he f i r st el ement i n t he l oop.
I F i = 1 THEN
- - Assi gn t he f i r st char act er i ndex t o a var i abl e.
cur r ent : = cal endar . FI RST;
- - Use t he der i ved i ndex t o f i nd t he next i ndex.
el ement : = cal endar ( cur r ent ) ;
ELSE
- - Check i f next i ndex val ue exi st s.
I F cal endar . NEXT( cur r ent ) I S NOT NULL THEN
- - Assi gn t he char act er i ndex t o a var i abl e.
cur r ent : = cal endar . NEXT( cur r ent ) ;
- - Use t he der i ved i ndex t o f i nd t he next i ndex.
el ement : = cal endar ( cur r ent ) ;
ELSE
- - Exi t l oop si nce l ast i ndex val ue i s r ead.
EXI T;
END I F;
END I F;
END LOOP;
. .



- - Usi ng Associ at i ve Ar r ays wi t h BULK COLLECT and FORALL
- - BULK COLLECT t o r et r i eve a r ecor d set i nt o associ at i ve ar r ays or nest ed
t abl es
- - FORALL t o send DML st at ement s i n bat ches

- - usi ng FORALL
CREATE TABLE bul k_number s
( number _i d NUMBER
, CONSTRAI NT number _i d_pk PRI MARY KEY ( number _i d) ) ;

DECLARE
Page 616 Oracle DBA Code Examples

TYPE number _t abl e I S TABLE OF bul k_number s. number _i d%TYPE
I NDEX BY BI NARY_I NTEGER;
number _l i st NUMBER_TABLE;
BEGI N

FOR i I N 1. . 10000 LOOP
- - Assi gn number val ue.
number _l i st ( i ) : = i ;
END LOOP;

- - Loop t hr ough al l t o do a bul k i nser t .
FORALL i I N 1. . number _l i st . COUNT
I NSERT
I NTO bul k_number s
VALUES ( number _l i st ( i ) ) ;

COMMI T;
END;
/

- - Usi ng a BULK COLLECT
DECLARE
TYPE number _t abl e I S TABLE OF bul k_number s. number _i d%TYPE
I NDEX BY BI NARY_I NTEGER;
number _l i st NUMBER_TABLE;
BEGI N
- - Check i f cal endar has no el ement s.
SELECT number _i d
BULK COLLECT
I NTO number _l i st
FROM bul k_number s
ORDER BY 1;

FOR i I N number _l i st . FI RST. . number _l i st . LAST LOOP
- - pr i nt onl y t he f i r st and l ast t wo
I F i <= 2 OR i >= 9999 THEN
DBMS_OUTPUT. PUT_LI NE( ' Number [ ' | | number _l i st ( i ) | | ' ] ' ) ;
END I F;
END LOOP;
END;
/
Using Collection API
API Function
or Procedure
Notes Return Type
COUNT
PLS_INTEGER
DELETE( n)
NONE
DELETE( n, m)
n= minimum m=maximum NONE
EXI STS( n)
TRUE or FALSE
EXTEND
not in Associative Tables NONE
EXTEND( n)
n = number of elements to add NONE
Page 617 Oracle DBA Code Examples

EXTEND( n, i )
i= number of replicated elements NONE
FI RST
the lowest
subscript
INTEGER or VARCHAR2
LAST
the highest
subscript
INTEGER or VARCHAR2
LI MI T

INTEGER
NEXT( n)
If there is no next element, it will return null.
INTEGER or VARCHAR2
PRI OR( n)
If there is no previous element, it will return
null.
INTEGER or VARCHAR2
TRI M
removes the highest
subscripted value from a collection
NONE
TRI M( n)
removes the
number or elements passed
NONE
Errors returned by Collections:
COLLECTION_IS_NULL An attempt to use a null collection.
NO_DATA_FOUND An attempt to use a subscript that has
been deleted or is a nonexistent unique
string index value in an associative
array.
SUBSCRIPT_BEYOND_COUNT This error applies only to varrays and
nested tables.
SUBSCRIPT_OUTSIDE_LIMIT

- - usi ng DELETE met hod
DECLARE
- - Def i ne a nest ed t abl e t ype of I NTEGER.
TYPE number _t abl e I S TABLE OF I NTEGER;
- - Def i ne a var i abl e of t he nest ed t abl e t ype.
number _l i st NUMBER_TABLE;
- - Def i ne a l ocal pr ocedur e t o check and pr i nt el ement s.
PROCEDURE pr i nt _l i st
( l i st _i n NUMBER_TABLE) I S
BEGI N
- - Loop t hr ough t he possi bl e i ndex val ues of t he l i st .
FOR i I N l i st _i n. FI RST. . l i st _i n. LAST LOOP
- - Check i f t he subscr i pt ed el ement i s t her e.
I F l i st _i n. EXI STS( i ) THEN
- - Pr i nt t he el ement .
DBMS_OUTPUT. PUT_LI NE( ' Li st [ ' | | l i st _i n( i ) | | ' ] ' ) ;
END I F;
END LOOP;
END pr i nt _l i st ;
BEGI N
- - Check i f a subscr i pt el ement of one does not exi st s.
I F NOT number _l i st . EXI STS( 1) THEN
- - Const r uct t he col l ect i on.
number _l i st : = number _t abl e( 1, 2, 3, 4, 5) ;
END I F;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( ' Nest ed t abl e bef or e a del et i on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
Page 618 Oracle DBA Code Examples

pr i nt _l i st ( number _l i st ) ;
- - Del et e an el ement .
number _l i st . DELETE( 2, 4) ;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( CHR( 10) | |
' Nest ed t abl e af t er a del et i on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
END;
/


- - usi ng EXTEND
SET SERVEROUTPUT ON SI ZE 1000000
DECLARE
- - Def i ne a nest ed t abl e t ype of I NTEGER.
TYPE number _t abl e I S TABLE OF I NTEGER;
- - Def i ne a var i abl e of t he nest ed t abl e t ype.
number _l i st NUMBER_TABLE : = number _t abl e( 1, 2) ;
- - Def i ne a l ocal pr ocedur e t o check and pr i nt el ement s.
PROCEDURE pr i nt _l i st
( l i st _i n NUMBER_TABLE) I S
BEGI N
- - Loop t hr ough t he possi bl e i ndex val ues of t he l i st .
FOR i I N l i st _i n. FI RST. . l i st _i n. LAST LOOP
- - Check i f t he subscr i pt ed el ement i s t her e.
I F l i st _i n. EXI STS( i ) THEN
- - Pr i nt t he el ement .
DBMS_OUTPUT. PUT_LI NE( ' Li st [ ' | | l i st _i n( i ) | | ' ] ' ) ;
END I F;
END LOOP;
END pr i nt _l i st ;
BEGI N
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( ' Nest ed t abl e bef or e ext ensi on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
- - Al l ocat e t wo nul l el ement s.
number _l i st . EXTEND( 2) ;
- - Al l ocat e t hr ee el ement s and copy el ement t wo
number _l i st . EXTEND( 3, 2) ;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( CHR( 10) | |
' Nest ed t abl e af t er ext ensi on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
END;
/


- - usi ng LI MI T Met hod ( f unct i on)
DECLARE
- - Def i ne a var r ay t ype of I NTEGER.
TYPE number _var r ay I S VARRAY( 5) OF I NTEGER;
Page 619 Oracle DBA Code Examples

- - Def i ne a var i abl e of t he var r ay t ype.
number _l i st NUMBER_VARRAY : = number _var r ay( 1, 2, 3) ;
- - Def i ne a l ocal pr ocedur e t o check and pr i nt el ement s.
PROCEDURE pr i nt _l i st
( l i st _i n NUMBER_VARRAY) I S
BEGI N
- - Loop t hr ough t he possi bl e i ndex val ues of t he l i st .
FOR i I N l i st _i n. FI RST. . l i st _i n. COUNT LOOP
- - Pr i nt t he el ement .
DBMS_OUTPUT. PUT_LI NE(
' Li st I ndex [ ' | | i | | ' ] ' | |
' Li st Val ue [ ' | | l i st _i n( i ) | | ' ] ' ) ;
END LOOP;
END pr i nt _l i st ;
BEGI N
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( ' Var r ay af t er i ni t i al i zat i on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
- - Ext end nul l el ement t o maxi muml i mi t .
number _l i st . EXTEND( number _l i st . LI MI T - number _l i st . LAST) ;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT( CHR( 10) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Var r ay af t er ext ensi on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
END;
/



- - usi ng TRI M Met hod
DECLARE
- - Def i ne a var r ay t ype of I NTEGER.
TYPE number _var r ay I S VARRAY( 5) OF I NTEGER;
- - Def i ne a var i abl e of t he var r ay t ype.
number _l i st NUMBER_VARRAY : = number _var r ay( 1, 2, 3, 4, 5) ;
- - Def i ne a l ocal pr ocedur e t o check and pr i nt el ement s.
PROCEDURE pr i nt _l i st
( l i st _i n NUMBER_VARRAY) I S
BEGI N
- - Loop t hr ough t he possi bl e i ndex val ues of t he l i st .
FOR i I N l i st _i n. FI RST. . l i st _i n. COUNT LOOP
- - Pr i nt t he el ement .
DBMS_OUTPUT. PUT_LI NE(
' Li st I ndex [ ' | | i | | ' ] ' | |
' Li st Val ue [ ' | | l i st _i n( i ) | | ' ] ' ) ;
END LOOP;
END pr i nt _l i st ;
BEGI N
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT_LI NE( ' Var r ay af t er i ni t i al i zat i on' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
Page 620 Oracle DBA Code Examples

- - Ext end nul l el ement t o maxi muml i mi t .
number _l i st . TRI M;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT( CHR( 10) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Var r ay af t er a si ngl e el ement t r i m' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
- - Ext end nul l el ement t o maxi muml i mi t .
number _l i st . TRI M( 3) ;
- - Pr i nt a t i t l e.
DBMS_OUTPUT. PUT( CHR( 10) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Var r ay af t er a t hr ee el ement t r i m' ) ;
DBMS_OUTPUT. PUT_LI NE( ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ' ) ;
- - Pr i nt t he l i st .
pr i nt _l i st ( number _l i st ) ;
END;
/
Page 621 Oracle DBA Code Examples

Handling Errors
Predefined Exceptions
Oracle Error Equivalent Exception Description
ORA- 0001 DUP_VAL_ON_I NDEX
Unique constraint violated.
ORA- 0051 TI MEOUT_ON_RESOURCE
Time-out occurred while waiting for resource.
ORA- 1001 I NVALI D_CURSOR
Illegal cursor operation.
ORA- 1012 NOT_LOGGED_ON
Not connected to Oracle.
ORA- 1017 LOGI N_DENI ED
Invalid user name/password.
ORA- 1403 NO_DATA_FOUND
No data found.
ORA- 1410 SYS_I NVALI D_ROWI D
Conversion to a universal rowid failed.
ORA- 1422 TOO_MANY_ROWS
A SELECT.INTO statement matches more than
one row.
ORA- 1476 ZERO_DI VI DE
Division by zero.
ORA- 1722 I NVALI D_NUMBER
Conversion to a number failed; for example,
'1A' is not valid.
ORA- 1725 USERENV_COMMI TSCN_ERROR
1
Incorrect usage of the USERENV('COMMITSCN')
function.
ORA- 6500 STORAGE_ERROR
Internal PL/SQL error raised if PL/SQL runs out
of memory.
ORA- 6501 PROGRAM_ERROR
Internal PL/SQL error.
ORA- 6502 VALUE_ERROR
Truncation, arithmetic, or conversion error.
ORA- 6504 ROWTYPE_MI SMATCH
Host cursor variable and PL/SQL cursor variable
have incompatible row types.
ORA- 6511 CURSOR_ALREADY_OPEN
Attempt to open a cursor that is already open.
ORA- 6530 ACCESS_I NTO_NULL
Attempt to assign values to the attributes of a
NULL object.
ORA- 6531 COLLECTI ON_I S_NULL
Attempt to apply collection methods other than
EXISTS to a NULL PL/SQL table or varray.
ORA- 6532 SUBSCRI PT_OUTSI DE_LI MI T
Reference to a nested table or varray index
outside the declared range (such as 1).
ORA- 6533 SUBSCRI PT_BEYOND_COUNT
Reference to a nested table or varray index
higher than the number of elements in the
collection.
ORA- 6548 NO_DATA_NEEDED1
Caller of a pipelined function does not need
more rows.
ORA- 6592 CASE_NOT_FOUND2
No matching WHEN clause in a CASE statement
is found.
ORA- 30625 SELF_I S_NULL
Attempt to call a method on a null object
instance.
Using User-Defined Exceptions
It is impossible for an exception handler to be defined for more than one exception
simultaneously; i.e.: WHEN except i on1 AND except i on2 will raise a compilation error.
Examining the Error Stack: Use SQLCODE and SQLERRM OR:
DBMS_UTILITY.FORMAT_ERROR_STACK provides a function FORMAT_ERROR_STACK that
returns the same information as SQLERRM, also limited to 2000 bytes.
Page 622 Oracle DBA Code Examples

DECLARE
- - Except i on t o i ndi cat e an er r or condi t i on
e_Dupl i cat eAut hor s EXCEPTI ON;
- - I Ds f or t hr ee aut hor s
v_Aut hor 1 books. aut hor 1%TYPE;
v_Aut hor 2 books. aut hor 2%TYPE;
v_Aut hor 3 books. aut hor 3%TYPE;

BEGI N
/ * Fi nd t he I Ds f or t he 3 aut hor s of ' Or acl e9i DBA 101' */
SELECT aut hor 1, aut hor 2, aut hor 3
I NTO v_Aut hor 1, v_Aut hor 2, v_Aut hor 3
FROM books
WHERE t i t l e = ' Or acl e9i DBA 101' ;

/ * Ensur e t hat t her e ar e no dupl i cat es */
I F ( v_Aut hor 1 = v_Aut hor 2) OR ( v_Aut hor 1 = v_Aut hor 3) OR
( v_Aut hor 2 = v_Aut hor 3) THEN
RAI SE e_Dupl i cat eAut hor s;
END I F;
EXCEPTI ON
WHEN e_Dupl i cat eAut hor s THEN
I NSERT I NTO l og_t abl e ( i nf o)
VALUES ( ' Or acl e9i DBA 101 has dupl i cat e aut hor s' ) ;
WHEN OTHERS THEN
I NSERT I NTO l og_t abl e ( code, message, i nf o) VALUES
( NULL, SUBSTR( DBMS_UTI LI TY. FORMAT_ERROR_STACK, 1, 200) , ' Or acl e er r or
occur r ed' ) ;
END;
/



/ * The EXCEPTI ON_I NI T Pr agma */
DECLARE
e_Mi ssi ngNul l EXCEPTI ON;
PRAGMA EXCEPTI ON_I NI T( e_Mi ssi ngNul l , - 1400) ;
BEGI N
I NSERT I NTO aut hor s ( i d) VALUES ( NULL) ;
EXCEPTI ON
WHEN e_Mi ssi ngNul l t hen
I NSERT I NTO l og_t abl e ( i nf o) VALUES ( ' ORA- 1400 occur r ed' ) ;
END;
/
Using RAISE_APPLICATION_ERROR
RAI SE_APPLI CATI ON_ERROR( er r or _number , er r or _message, [ keep_er r or s] ) ;
error_number is a value between 20,000 and 20,999
The error_message must be fewer than 512 characters
If keep_errors is TRUE, the new error is added to the list of errors already raised (if one
exists). If it is FALSE, which is the default, the new error will replace the current list of
errors.
. .
Page 623 Oracle DBA Code Examples

I F v_Aut hor Count = 0 THEN
RAI SE_APPLI CATI ON_ERROR( - 20001,
' Aut hor 1 ' | | p_Aut hor 1 | | ' does not exi st ' ) ;
. .
Page 624 Oracle DBA Code Examples

Autonomous Transactions
Autonomous transactions are started by a parent, or main, transaction but operate
independently of the parent for transaction control. If a commit or rollback is used in the
autonomous or main transaction, or if a failure occurs for any reason, it does not impact
the other transaction.
CREATE OR REPLACE PROCEDURE l oggi ng_i ns (
i _user name I N VARCHAR2, i _dat et i me I N TI MESTAMP)
I S
PRAGMA AUTONOMOUS_TRANSACTI ON;
BEGI N
I NSERT I NTO l oggi ng ( user name, dat et i me)
VALUES ( i _user name, i _dat et i me) ;
commi t ; - - commi t i s a must her e i n Aut onomous pr oc ot hewi se ORA- 06519
r et ur ned
END;
/
Page 625 Oracle DBA Code Examples

Some Stored Subprobrams Concepts
Serially Reusable Packages
Serially Reusable Packages NonSerially Reusable Packages
Run-time state is kept in shared memory
and is freed after every database call.
Run-time state is kept in process memory and
lasts for the life of the database session.
The maximum memory used is proportional
to the number of concurrent users of the
package.
The maximum memory used is proportional
to the number of concurrently logged-on
users, which is typically much higher.

CREATE OR REPLACE PACKAGE TEST_PCK
I S
- - di spl ay number of r ows passed
PROCEDURE DI SPLAY_ROWS( P_N I N NUMBER) ;

END;
/


CREATE OR REPLACE PACKAGE BODY TEST_PCK
I S
- - t hi s cur sor keeps openi ng i n t he sessi on l i f e
CURSOR CR I S SELECT CUSTOMER_I D FROM CUSTOMERS ORDER BY CUSTOMER_I D;

PROCEDURE DI SPLAY_ROWS( P_N I N NUMBER)
I S
V_I D NUMBER;
I NUMBER : = 0;
V_DONE BOOLEAN : = FALSE;
BEGI N
I F NOT CR%I SOPEN THEN
OPEN CR;
END I F;
- - di spl ay onl y passed number of r ows
WHI LE NOT V_DONE LOOP
FETCH CR I NTO V_I D;
I F CR%NOTFOUND THEN
CLOSE CR;
V_DONE : = TRUE;
ELSE
I : = I + 1;
DBMS_OUTPUT. PUT_LI NE( V_I D) ;
I F I >= P_N THEN
V_DONE : = TRUE;
END I F;
END I F;
END LOOP;
END DI SPLAY_ROWS;
END TEST_PCK;
/


- - i f you add PRAGMA SERI ALLY_REUSABLE, CR wi l l at r eset ever y cal l
Page 626 Oracle DBA Code Examples

CREATE OR REPLACE PACKAGE TEST_PCK
I S
PRAGMA SERI ALLY_REUSABLE;
. .

CREATE OR REPLACE PACKAGE BODY TEST_PCK
I S
PRAGMA SERI ALLY_REUSABLE;
. .
Stored Subprograms and Roles
If a stored subprogram refers to an object in another schema, that object should be
granted directly to the subprogram owner, not via a role.
CONN SA/ s

CREATE ROLE R1;

GRANT SELECT ON CUSTOMERS TO R1;

GRANT R1 TO USER1;

CONN USER1/ U

CREATE OR REPLACE PACKAGE USER1. TEST_PCK
I S
PROCEDURE DI SPLAY_ROW;
END;
/

- - t he f ol l owi ng wi l l not compi l e because CUSTOMERS gr ant ed
- - t o USER1 vi a r ol e ( not di r ect l y)
CREATE OR REPLACE PACKAGE BODY USER1. TEST_PCK
I S
PROCEDURE DI SPLAY_ROW
I S
N NUMBER;
BEGI N
SELECT CUSTOMER_I D I NTO N
FROM SA. CUSTOMERS
WHERE CUSTOMER_I D=101;
END DI SPLAY_ROW;
END TEST_PCK;
/
Invokers vs. Definers Rights
CREATE [ OR REPLACE] FUNCTI ON f unct i on_name
[ par amet er _l i st ] RETURN r et ur n_t ype
[ AUTHI D {CURRENT_USER | DEFI NER}] {I S | AS}
Page 627 Oracle DBA Code Examples

Pinning an Programunit in the Shared Pool
To pin an object:
DBMS_SHARED_POOL. KEEP( name VARCHAR2, f l ag CHAR DEFAULT ' P' )
f l ag Det er mi nes t he t ype of t he obj ect :
P Package, f unct i on, or pr ocedur e
Q Sequence
R Tr i gger
T Obj ect t ype ( Or acl e8 and hi gher )
J S J ava sour ce ( Or acl e8i and hi gher )
J C J ava cl ass ( Or acl e8i and hi gher )
J R J ava r esour ce ( Or acl e8i and hi gher )
J D J ava shar ed dat a ( Or acl e8i and hi gher )
C SQL cur sor

To echo the contents of the shared pool of objects greater than minisize to the screen:
DBMS_SHARED_POOL. SI ZES( mi nsi ze NUMBER)
Page 628 Oracle DBA Code Examples

Using Triggers
General Syntax of creating any trigger:
CREATE [ OR REPLACE] TRI GGER t r i gger _name
{BEFORE | AFTER | I NSTEAD OF} t r i gger i ng_event
[ r ef er enci ng_cl ause]
[ WHEN t r i gger _condi t i on]
[ FOR EACH ROW]
t r i gger _body
Restrictions on Triggers
A trigger may not issue any transaction control statementsCOMMIT, ROLLBACK,
SAVEPOINT, or SET TRANSACTION.
The trigger body cannot declare any LONG or LONG RAW variables.
Code in a trigger body may reference and use LOB (Large OBject) columns, but it may not
modify the values of the columns. This is also true for object columns.
Using DML Triggers
CREATE OR REPLACE TRI GGER Updat eCat egor ySt at s
AFTER I NSERT OR DELETE OR UPDATE ON books
DECLARE
CURSOR c_St at i st i cs I S
SELECT cat egor y,
COUNT( *) t ot al _books,
AVG( pr i ce) aver age_pr i ce
FROM books
GROUP BY cat egor y;
BEGI N
DELETE FROM cat egor y_st at s;

FOR v_St at sRecor d i n c_St at i st i cs LOOP
I NSERT I NTO cat egor y_st at s ( cat egor y, t ot al _books, aver age_pr i ce)
VALUES ( v_St at sRecor d. cat egor y, v_St at sRecor d. t ot al _books,
v_St at sRecor d. aver age_pr i ce) ;
END LOOP;
END Updat eCat egor ySt at s;
/


CREATE OR REPLACE TRI GGER Gener at eAut hor I D
BEFORE I NSERT OR UPDATE ON aut hor s
REFERENCI NG new AS new_aut hor
FOR EACH ROW
BEGI N
/ * Fi l l i n t he I D f i el d of aut hor s wi t h t he next val ue f r om
aut hor _sequence. Si nce I D i s a col umn i n aut hor s, : new. I D
i s a val i d r ef er ence. */
SELECT aut hor _sequence. NEXTVAL
I NTO : new_aut hor . I D
Page 629 Oracle DBA Code Examples

FROM dual ;
END Gener at eAut hor I D;
/


- - usi ng WHEN keywor d
CREATE OR REPLACE TRI GGER CheckPr i ce
BEFORE I NSERT OR UPDATE OF pr i ce ON books
FOR EACH ROW
WHEN ( new. pr i ce > 49. 99)
BEGI N
. .
END;
/


- - usi ng Tr i gger Pr edi cat es
CREATE OR REPLACE TRI GGER LogI nvent or yChanges
BEFORE I NSERT OR DELETE OR UPDATE ON i nvent or y
FOR EACH ROW
DECLARE
v_ChangeType CHAR( 1) ;
BEGI N
/ * Use ' I ' f or an I NSERT, ' D' f or DELETE, and ' U' f or UPDATE. */
I F I NSERTI NG THEN
v_ChangeType : = ' I ' ;
ELSI F UPDATI NG THEN
v_ChangeType : = ' U' ;
ELSE
v_ChangeType : = ' D' ;
END I F;
. .
END LogI nvent or yChanges;
/
Using Instead-of Triggers
All instead-of triggers are row level, whether or not the FOR EACH ROW clause is present.
CREATE OR REPLACE TRI GGER I nser t BooksAut hor s
I NSTEAD OF I NSERT ON books_aut hor s
DECLARE
v_Book books%ROWTYPE;
v_Aut hor I D aut hor s. i d%TYPE;
BEGI N
- - Fi gur e out t he I D of t he new aut hor
BEGI N
SELECT i d
I NTO v_Aut hor I D
FROM aut hor s
WHERE f i r st _name = : new. f i r st _name
AND l ast _name = : new. l ast _name;
EXCEPTI ON
WHEN NO_DATA_FOUND THEN
- - No aut hor f ound, cr eat e a new one
I NSERT I NTO aut hor s ( i d, f i r st _name, l ast _name)
Page 630 Oracle DBA Code Examples

VALUES ( aut hor _sequence. NEXTVAL, : new. f i r st _name, : new. l ast _name)
RETURNI NG I D I NTO v_Aut hor I D;
END;
SELECT *
I NTO v_Book
FROM books
WHERE i sbn = : new. i sbn;
- - Fi gur e out whet her t he book al r eady has 1 or 2 aut hor s, and updat e
- - accor di ngl y
I F v_Book. aut hor 2 I S NULL THEN
UPDATE books
SET aut hor 2 = v_Aut hor I D
WHERE i sbn = : new. i sbn;
ELSE
UPDATE books
SET aut hor 3 = v_Aut hor I D
WHERE i sbn = : new. i sbn;
END I F;
END I nser t BooksAut hor s;
/
Using System Triggers
System trigger fires on two different kinds of events: DDL or database.
Because system triggers are generally committed anyway, declaring them as autonomous
will not have any effect.
Required privilege on database triggers: ADMINISTER DATABASE TRIGGER
CREATE [ OR REPLACE] TRI GGER [ schema. ] t r i gger _name
{BEFORE | AFTER}
{ddl _event _l i st | dat abase_event _l i st }
ON {DATABASE | [ schema. ] SCHEMA}
[ when_cl ause]
t r i gger _body;

Database Events:
Event When Trigger Fires Conditions Restrictions Transaction
Attribute
Functions
STARTUP
When the database is
opened.
None
allowed
No database
operations
allowed in the
trigger.
Return status
ignored.
Starts a
separate
transaction
and commits it
after firing the
triggers.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
SHUTDOWN
Just before the server
starts the shutdown of
an instance.
This lets the cartridge
shutdown completely.
For abnormal instance
shutdown, this triiger
None
allowed
No database
operations
allowed in the
trigger.
Return status
ignored.
Starts a
separate
transaction
and commits it
after firing the
triggers.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
Page 631 Oracle DBA Code Examples

Event When Trigger Fires Conditions Restrictions Transaction
Attribute
Functions
might not fire.
DB_ROLE_CH
ANGE
When the database is
opened for the first time
after a role change.
None
allowed
Return status
ignored.
Starts a
separate
transaction
and commits it
after firing the
triggers.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
SERVERERRO
R
When the error eno
occurs. If no condition is
given, then this trigger
fires whenever an error
occurs.
The trigger does not fire
on ORA-1034, ORA-
1403, ORA-1422, ORA-
1423, and ORA-4030
because they are not
true errors or are too
serious to continue
processing. It also fails
to fire on ORA-18 and
ORA-20 because a
process is not available
to connect to the
database to record the
error.
ERRNO =
eno
Depends on
the error.
Return status
ignored.
Starts a
separate
transaction
and commits it
after firing the
triggers.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_server_error
ora_is_servererror
space_error_info

Schema or Client Events:
Event When Trigger Fires Attribute Functions
BEFORE ALTER

AFTER ALTER
When a catalog object is altered. ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_type
ora_dict_obj_name
ora_dict_obj_owner
ora_des_encrypted_password
(for ALTER USER events)
ora_is_alter_column
(for ALTER TABLE events)
ora_is_drop_column
(for ALTER TABLE events)
BEFORE DROP

AFTER DROP
When a catalog object is dropped. ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_type
ora_dict_obj_name
ora_dict_obj_owner
BEFORE ANALYZE

AFTER ANALYZE
When an analyze statement is issued ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
Page 632 Oracle DBA Code Examples

Event When Trigger Fires Attribute Functions
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
BEFORE
ASSOCI ATE
STATI STI CS

AFTER
ASSOCI ATE
STATI STI CS
When an associate statistics statement is
issued
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
ora_dict_obj_name_list
ora_dict_obj_owner_list
BEFORE AUDI T
AFTER AUDI T

BEFORE NOAUDI T
AFTER NOAUDI T
When an audit or noaudit statement is
issued
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
BEFORE COMMENT

AFTER COMMENT
When an object is commented ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
BEFORE CREATE

AFTER CREATE
When a catalog object is created. ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_type
ora_dict_obj_name
ora_dict_obj_owner
ora_is_creating_nested_table
(for CREATE TABLE events)
BEFORE DDL

AFTER DDL
When most SQL DDL statements are issued.
Not fired for ALTER DATABASE, CREATE
CONTROLFILE, CREATE DATABASE, and DDL
issued through the PL/SQL subprogram
interface, such as creating an advanced
queue.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
BEFORE
DI SASSOCI ATE
STATI STI CS

AFTER
DI SASSOCI ATE
STATI STI CS
When a disassociate statistics statement is
issued
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
ora_dict_obj_name_list
ora_dict_obj_owner_list
BEFORE GRANT

AFTER GRANT
When a grant statement is issued ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
Page 633 Oracle DBA Code Examples

Event When Trigger Fires Attribute Functions
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
ora_grantee
ora_with_grant_option
ora_privileges
BEFORE LOGOFF
At the start of a user logoff ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
AFTER LOGON
After a successful logon of a user. ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_client_ip_address
BEFORE RENAME

AFTER RENAME
When a rename statement is issued. ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_owner
ora_dict_obj_type
BEFORE REVOKE

AFTER REVOKE
When a revoke statement is issued ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner
ora_revokee
ora_privileges
AFTER SUSPEND
After a SQL statement is suspended because
of an out-of-space condition. The trigger
must correct the condition so the statement
can be resumed.
ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_server_error
ora_is_servererror
space_error_info
BEFORE
TRUNCATE

AFTER TRUNCATE
When an object is truncated ora_sysevent
ora_login_user
ora_instance_num
ora_database_name
ora_dict_obj_name
ora_dict_obj_type
ora_dict_obj_owner

CREATE OR REPLACE TRI GGER LogCr eat i ons
AFTER CREATE ON SCHEMA
BEGI N
I NSERT I NTO ddl _cr eat i ons ( user _i d, obj ect _t ype, obj ect _name,
obj ect _owner , cr eat i on_dat e)
VALUES ( USER, ORA_DI CT_OBJ _TYPE, ORA_DI CT_OBJ _NAME,
Page 634 Oracle DBA Code Examples

ORA_DI CT_OBJ _OWNER, SYSDATE) ;
END LogCr eat i ons;
Handling Mutating Tables in Triggers
SQL statements in a trigger body may not:
o Read from or modify any mutating table of the triggering statement. This includes the
triggering table itself.
o Read from or modify the primary-, unique-, or foreign-key columns of a constraining
table of the triggering table. They may, however, modify the other columns if desired.
o These restrictions apply to all row-level triggers. They apply for statement triggers
only when the statement trigger would be fired as a result of a DELETE CASCADE
operation.
If an INSERT statement affects only one row, the before- and after-row triggers for that
row do not treat the triggering table as mutating. This is the only case where a row-level
trigger may read from or modify the triggering table. Statements such as INSERT INTO
table SELECT ... always treat the triggering table as mutating, even if the subquery
returns only one row.
- - t he f ol l owi ng t r i gger wi l l r et ur n ORA- 4091
CREATE OR REPLACE TRI GGER Li mi t Maj or s
BEFORE I NSERT OR UPDATE OF maj or ON st udent s
FOR EACH ROW
DECLARE
v_MaxSt udent s CONSTANT NUMBER : = 5;
v_Cur r ent St udent s NUMBER;
BEGI N
SELECT COUNT( *)
I NTO v_Cur r ent St udent s
FROM st udent s
WHERE maj or = : new. maj or ;

- - I f t her e i sn' t r oom, r ai se an er r or .
I F v_Cur r ent St udent s + 1 > v_MaxSt udent s THEN
RAI SE_APPLI CATI ON_ERROR( - 20000,
' Too many st udent s i n maj or ' | | : new. maj or ) ;
END I F;
END Li mi t Maj or s;
/



To wor kar ound: cr eat e t wo t r i gger s: one st at ement l evel and t he ot her r ow
l evel . The st at ement t r i gger st or e t he SELECT r esul t i nt o a PL/ SQL t abl e i n a
package. The r ow- l evel t r i gger wi l l r ead t hat dat a f r omt he package.

CREATE OR REPLACE PACKAGE St udent Dat a AS
TYPE t _Maj or s I S TABLE OF st udent s. maj or %TYPE I NDEX BY BI NARY_I NTEGER;
TYPE t _I Ds I S TABLE OF st udent s. I D%TYPE I NDEX BY BI NARY_I NTEGER;

v_St udent Maj or s t _Maj or s;
v_St udent I Ds t _I Ds;
v_NumEnt r i es BI NARY_I NTEGER : = 0;
END St udent Dat a;
/
Page 635 Oracle DBA Code Examples



CREATE OR REPLACE TRI GGER RLi mi t Maj or s
BEFORE I NSERT OR UPDATE OF maj or ON st udent s
FOR EACH ROW
BEGI N
St udent Dat a. v_NumEnt r i es : = St udent Dat a. v_NumEnt r i es + 1;
St udent Dat a. v_St udent Maj or s( St udent Dat a. v_NumEnt r i es) : = : new. maj or ;
St udent Dat a. v_St udent I Ds( St udent Dat a. v_NumEnt r i es) : = : new. i d;
END RLi mi t Maj or s;
/

CREATE OR REPLACE TRI GGER SLi mi t Maj or s
AFTER I NSERT OR UPDATE OF maj or ON st udent s
DECLARE
v_MaxSt udent s CONSTANT NUMBER : = 2;
v_Cur r ent St udent s NUMBER;
v_St udent I D st udent s. I D%TYPE;
v_Maj or st udent s. maj or %TYPE;
BEGI N
/ * Loop t hr ough each st udent i nser t ed or updat ed, and ver i f y
t hat we ar e st i l l wi t hi n t he l i mi t . */
FOR v_LoopI ndex I N 1. . St udent Dat a. v_NumEnt r i es LOOP
v_St udent I D : = St udent Dat a. v_St udent I Ds( v_LoopI ndex) ;
v_Maj or : = St udent Dat a. v_St udent Maj or s( v_LoopI ndex) ;

- - Det er mi ne t he cur r ent number of st udent s i n t hi s maj or .
SELECT COUNT( *)
I NTO v_Cur r ent St udent s
FROM st udent s
WHERE maj or = v_Maj or ;

- - I f t her e i sn' t r oom, r ai se an er r or .
I F v_Cur r ent St udent s > v_MaxSt udent s THEN
RAI SE_APPLI CATI ON_ERROR( - 20000,
' Too many st udent s f or maj or ' | | v_Maj or | |
' because of st udent ' | | v_St udent I D) ;
END I F;
END LOOP;

- - Reset t he count er so t he next execut i on wi l l use new dat a.
St udent Dat a. v_NumEnt r i es : = 0;
END SLi mi t Maj or s;
Dropping and Disabling Triggers
DROP TRI GGER <t r i gger name>;
ALTER TRI GGER t r i gger name {DI SABLE | ENABLE};
ALTER TABLE aut hor s {DI SABLE | ENABLE} ALL TRI GGERS;
Page 636 Oracle DBA Code Examples

Using Dynamic SQL
Working with Native Dynamic SQL
Using Dynamic SQL
Working with Native Dynamic SQL

- - DDL
st at ement : = ' CREATE SEQUENCE ' | | sequence_name| | CHR( 10)
| | ' I NCREMENT BY 1' | | CHR( 10)
| | ' START WI TH 1' | | CHR( 10)
| | ' CACHE 20' | | CHR( 10)
| | ' ORDER' ;



-- encapsulates a PL/SQL block SELECT-INTO
PROCEDURE i ncr ement _sequence
( sequence_name I N VARCHAR2,
sequence_val ue I N OUT NUMBER ) I S
- - Def i ne l ocal nat i ve dynami c SQL var i abl es.
st at ement VARCHAR2( 2000) ;
BEGI N

- - Bui l d dynami c SQL st at ement as anonymous bl ock PL/ SQL uni t .
st at ement : = ' BEGI N' | | CHR( 10)
| | ' SELECT hr . ' | | sequence_name| | ' . next val ' | | CHR( 10)
| | ' I NTO : r et val ' | | CHR( 10)
| | ' FROM DUAL; ' | | CHR( 10)
| | ' END; ' ;

- - Execut e dynami c SQL st at ement .
EXECUTE I MMEDI ATE st at ement
USI NG OUT sequence_val ue;
END i ncr ement _sequence;


-- DML without bind variables (less performance)
PROCEDURE i nser t _i nt o_t abl e
( t abl e_name I N VARCHAR2
, t abl e_col umn_val ue1 I N NUMBER
, t abl e_col umn_val ue2 I N VARCHAR2
, t abl e_col umn_val ue3 I N VARCHAR2) I S
- - Def i ne l ocal var i abl es.
st at ement VARCHAR2( 2000) ;
BEGI N

- - Bui l d dynami c SQL st at ement .
st at ement : = ' I NSERT '
| | ' I NTO ' | | t abl e_name| | ' '
| | ' VALUES ( '
| | ' ' ' ' | | t abl e_col umn_val ue1| | ' ' ' , '
| | ' ' ' ' | | t abl e_col umn_val ue2| | ' ' ' , '
| | ' ' ' ' | | t abl e_col umn_val ue3| | ' ' ' ) ' ;

Page 637 Oracle DBA Code Examples

- - Execut e t he NDS st at ement .
EXECUTE I MMEDI ATE st at ement ;

- - Commi t t he r ecor ds.
commi t ;
END i nser t _i nt o_t abl e;


-- a DML with ordered bind variables
PROCEDURE i nser t s_i nt o_t abl e
( t abl e_name I N VARCHAR2
, t abl e_col umn_val ue1 I N NUMBER
, t abl e_col umn_val ue2 I N VARCHAR2
, t abl e_col umn_val ue3 I N VARCHAR2) I S
- - Def i ne l ocal var i abl es.
st at ement VARCHAR2( 2000) ;
BEGI N
- - Bui l d dynami c SQL st at ement .
st at ement : = ' I NSERT '
| | ' I NTO ' | | t abl e_name| | ' '
| | ' VALUES ( : col _one, : col _t wo, : col _t hr ee) ' ;

- - Execut e t he NDS st at ement .
EXECUTE I MMEDI ATE st at ement
USI NG t abl e_col umn_val ue1
, t abl e_col umn_val ue2
, t abl e_col umn_val ue3;

- - Commi t t he r ecor ds.
commi t ;
END i nser t s_i nt o_t abl e;


-- select single row , single col (DQL)
PROCEDURE si ngl e_r ow_r et ur n I S
- - Def i ne l ocal var i abl es.
st at ement VARCHAR2( 2000) ;
val ue_out VARCHAR2( 1) ;
BEGI N
- - Bui l d dynami c SQL st at ement .
st at ement : = ' SELECT ' ' A' ' FROM DUAL' ;

- - Use NDS t o quer y a st at i c st r i ng.
EXECUTE I MMEDI ATE st at ement
I NTO val ue_out ;
END si ngl e_r ow_r et ur n;



-- select single row, mutiple col (DQL)
PROCEDURE si ngl e_r ow_r et ur n
( t abl e_name VARCHAR2
, col umn_name1 VARCHAR2
, col umn_name2 VARCHAR2
, col umn_name3 VARCHAR2 ) I S

- - Def i ne l ocal var i abl es.
Page 638 Oracle DBA Code Examples

st at ement VARCHAR2( 2000) ;
cval ue_out 1 VARCHAR2( 20) ;
cval ue_out 2 VARCHAR2( 30) ;
nval ue_out NUMBER;
BEGI N
- - Bui l d dynami c SQL st at ement .
st at ement : = ' SELECT '
| | col umn_name1 | | ' , '
| | col umn_name2 | | ' , '
| | col umn_name3 | | ' '
| | ' FROM ' | | t abl e_name;

EXECUTE I MMEDI ATE st at ement
I NTO nval ue_out , cval ue_out 1, cval ue_out 2;
END si ngl e_r ow_r et ur n;



-- SELECT multiple row of single col (DQL)
-- Create a Varray of a one character string
- - i t can al so be a l ocal t ype def i ned i n t he pr ocedur e
- - i t can al so be any PL/ SQL Col l ect i on l i ke PL/ SQL t abl e
CREATE OR REPLACE TYPE var char 2_t abl e1 I S
VARRAY( 100) OF VARCHAR2( 1) ;
/

PROCEDURE mul t i pl e_r ow_r et ur n I S
- - Def i ne l ocal var i abl es.
st at ement VARCHAR2( 2000) ;
val ue_out VARCHAR2_TABLE1;
BEGI N
- - usi ng an anonymous bl ock i s mandat or y, ot her wi se ORA- 03001
st at ement : = ' BEGI N '
| | ' SELECT ' ' A' ' '
| | ' BULK COLLECT I NTO : col _val '
| | ' FROM DUAL; '
| | ' END; ' ;

- - Use Bul k NDS t o quer y a st at i c st r i ng.
EXECUTE I MMEDI ATE st at ement
USI NG OUT val ue_out ;

- - Use a r ange l oop t o r ead t he val ues.
FOR i I N 1. . val ue_out . COUNT LOOP
- - Pr i nt out put message.
dbms_out put . put _l i ne( val ue_out ( i ) ) ;
END LOOP;
END mul t i pl e_r ow_r et ur n;



-- multiple row with columns (DQL)
- - NDS can use bul k col l ect i ons onl y f r omwi t hi n an anonymous- bl ock
CREATE OR REPLACE TYPE car d_number _var r ay I S VARRAY( 100) OF NUMBER;
CREATE OR REPLACE TYPE car d_name_var r ay I S VARRAY( 100) OF VARCHAR2( 2000) ;
CREATE OR REPLACE TYPE car d_sui t _var r ay I S VARRAY( 100) OF VARCHAR2( 2000) ;

Page 639 Oracle DBA Code Examples

PROCEDURE mul t i pl e_r ow_r et ur n
( t abl e_name VARCHAR2
, col umn_name1 VARCHAR2
, col umn_name2 VARCHAR2
, col umn_name3 VARCHAR2 ) I S
- - Def i ne l ocal Nat i ve Dynami c SQL var i abl es.
st at ement VARCHAR2( 2000) ;
cval ue_out 1 CARD_NAME_VARRAY;
cval ue_out 2 CARD_SUI T_VARRAY;
nval ue_out CARD_NUMBER_VARRAY;
BEGI N
st at ement : = ' BEGI N '
| | ' SELECT '
| | col umn_name1 | | ' , '
| | col umn_name2 | | ' , '
| | col umn_name3 | | ' '
| | ' BULK COLLECT I NTO : col 1, : col 2, : col 3 '
| | ' FROM ' | | t abl e_name | | ' ; '
| | ' END; ' ;

- - Execut e nat i ve dynami c SQL.
EXECUTE I MMEDI ATE st at ement
USI NG OUT nval ue_out , OUT cval ue_out 1, OUT cval ue_out 2;

FOR i I N 1. . nval ue_out . COUNT LOOP
dbms_out put . put _l i ne( ' Val ue f r om[ ' | | col umn_name1| | ' ] ' | | ' i s:
[ ' | | nval ue_out ( i ) | | ' ] ' ) ;
dbms_out put . put _l i ne( ' Val ue f r om[ ' | | col umn_name1| | ' ] ' | | ' i s:
[ ' | | SUBSTR( cval ue_out 1( i ) , 1, 20) | | ' ] ' ) ;
dbms_out put . put _l i ne( ' Val ue f r om[ ' | | col umn_name1| | ' ] ' | | ' i s:
[ ' | | SUBSTR( cval ue_out 2( i ) , 1, 30) | | ' ] ' ) ;
END LOOP;
END mul t i pl e_r ow_r et ur n;
Using DBMS_SQL
DBMS_SQL still has a major feature that is not delivered in NDS. It does not need to know
beforehand the number and types of arguments it will receive and process.
To use dbms_sql :
GRANT EXECUTE ON dbms_sys_sql TO SYSTEM WI TH GRANT OPTI ON;
GRANT EXECUTE ON dbms_sql TO SYSTEM WI TH GRANT OPTI ON;


- - Wor ki ng wi t h DDL and DML Wi t hout Bi nd Var i abl es
- - Pr ocedur e t o cl ose DBMS_SQL open cur sor .
PROCEDURE cl ose_open_cur sor ( c I N OUT I NTEGER) I S
BEGI N
I F dbms_sql . i s_open( c) THEN
dbms_sql . cl ose_cur sor ( c) ;
END I F;
END cl ose_open_cur sor ;

PROCEDURE cr eat e_sequence
( sequence_name I N VARCHAR2) I S
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
Page 640 Oracle DBA Code Examples

st at ement VARCHAR2( 2000) ;
BEGI N
- - Bui l d dynami c SQL st at ement .
st at ement : = ' CREATE SEQUENCE ' | | sequence_name| | CHR( 10)
| | ' I NCREMENT BY 1' | | CHR( 10)
| | ' START WI TH 1' | | CHR( 10)
| | ' CACHE 20' | | CHR( 10)
| | ' ORDER' ;

- - Par se and execut e t he st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;
f dbk : = dbms_sql . execut e( c) ;
- - Cl ose t he open cur sor .
dbms_sql . cl ose_cur sor ( c) ;
END cr eat e_sequence;


- - encapsul at es a PL/ SQL bl ock SELECT- I NTO.
PROCEDURE i ncr ement _sequence
( sequence_name I N VARCHAR2
, sequence_val ue I N OUT NUMBER ) I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;

BEGI N
/ *
| | Debuggi ng Ti p:
| | =============
| | When you ar e usi ng a SELECT- I NTO- FROM wi t hi n DBMS_SQL, whi ch i s a
| | r eser ved PLSQL synt ax not di r ect l y suppor t ed by DBMS_SQL. You
| | need t o encapsul at e i t i n a PLSQL wr apper . When you use a PLSQL
| | wr apper , t he semi col ons must be used i n t he st at ement and t he
| | PLSQL bl ock because DBMS_SQL adds a si ngl e semi col on t o execut e
| | t he PLSQL bl ock. I f you f or get t o encapsul at e t he SQL i n a
| | PLSQL wr apper , you wi l l r ai se t he f ol l owi ng er r or message.
| | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| | ORA- 01006: bi nd var i abl e does not exi st
*/

- - Bui l d dynami c SQL st at ement as anonymous bl ock PL/ SQL uni t .
st at ement : = ' BEGI N' | | CHR( 10)
| | ' SELECT PLSQL. ' | | sequence_name| | ' . next val ' | | CHR( 10)
| | ' I NTO : r et val ' | | CHR( 10)
| | ' FROM DUAL; ' | | CHR( 10)
| | ' END; ' ;

- - Par se t he st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

/ *
| | Techni cal Not e:
| | ==============
| | The BI ND_VARI ABLE pr ocedur e i s r et ur ni ng a NUMBER
| | and does not r equi r e par amet er f our .
Page 641 Oracle DBA Code Examples

*/

- - Bi nd var i abl e r et val t o an out put sequence val ue.
dbms_sql . bi nd_var i abl e( c, ' r et val ' , sequence_val ue) ;

- - Execut e t he dynami c cur sor .
f dbk : = dbms_sql . execut e( c) ;

- - Copy t he var i abl e val ue f r omt he bi nd var i abl e.
dbms_sql . var i abl e_val ue( c, ' r et val ' , sequence_val ue) ;

dbms_sql . cl ose_cur sor ( c) ;

dbms_out put . put ( ' Sequence <' | | sequence_name| | ' > ' ) ;

dbms_out put . put _l i ne( ' Val ue <' | | sequence_val ue| | ' >' ) ;
END i ncr ement _sequence;



- - a DML wi t h or der ed bi nd var i abl es
PROCEDURE i nser t _i nt o_t abl e
( t abl e_name I N VARCHAR2
, t abl e_col umn_val ue1 I N NUMBER
, t abl e_col umn_val ue2 I N VARCHAR2
, t abl e_col umn_val ue3 I N VARCHAR2) I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;
BEGI N
/ *
| | Debuggi ng Ti p:
| | =============
| | St at ement st r i ngs ar e t er mi nat ed by a l i ne r et ur n CHR( 10) t o
| | ensur e t hat a space i s not mi ssi ng bet ween concat enat ed segment s.
| | Usi ng a BI ND var i abl e pr ovi des ef f i ci enci es i n SQL st at ement s
| | because i t avoi ds t he r epar si ng of t he st at ement . Ther ef or e,
| | t hey shoul d be used as f ol l ows f or per f or mance gai ns:
| |
| | SQL STATEMENTS PREDI CATES
| | - - - - - - - - - - - - - - - - - - - - - - - -
| | SELECT WHERE
| | UPDATE SET
| | WHERE
| | DELETE WHERE
| |
| | Er r or Expl anat i ons:
| | - - - - - - - - - - - - - - - - - -
| | 1. An expl i ci t si ze i s al ways r equi r ed f or a VARCHAR2 var i abl e
| | and t he over l oaded pr ocedur e has an out put si ze var i abl e i n t he
| | f our t h posi t i on t hat you may need t o use. The out put l engt h i s
| | pr ovi ded bel ow t o demonst r at e i t .
| | 2. A bad bi nd var i abl e message t ypi cal l y means t he i dent i f i er i s
| | out si de of t he VARCHAR2 st r i ng and t r eat ed as a sessi on l evel
| | undef i ned bi nd var i abl e.
Page 642 Oracle DBA Code Examples

| | 3. A " mi ssi ng SELECT keywor d" can occur on an i nser t st at ement
| | i f you put bi nd var i abl es i nt o t he I NTO cl ause f or col umn
| | names.
| | 4. I f you have quot e mar ks ar ound VARCHAR2 bi nd var i abl es, you
| | may r ai se t he " bi nd var i abl e does not exi st " er r or . I f you
| | need t o use t hat synt ax, you can encapsul at e t he DML i n a
| | PLSQL wr apper .
| | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| | 1. ORA- 06502: PL/ SQL: numer i c or val ue er r or
| | 2. PLS- 00049: bad bi nd var i abl e
| | 3. ORA- 00928: mi ssi ng SELECT keywor d
| | 4. ORA- 01006: bi nd var i abl e does not exi st
*/

- - Bui l d dynami c SQL st at ement .
st at ement : = ' I NSERT '
| | ' I NTO ' | | t abl e_name| | ' '
| | ' VALUES '
| | ' ( : t abl e_col umn_val ue1'
| | ' , : t abl e_col umn_val ue2'
| | ' , : t abl e_col umn_val ue3) ' ;

- - Par se t he st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

- - Bi nd each bi nd var i abl e.
dbms_sql . bi nd_var i abl e( c, ' t abl e_col umn_val ue1' , t abl e_col umn_val ue1) ;
dbms_sql . bi nd_var i abl e( c, ' t abl e_col umn_val ue2' , t abl e_col umn_val ue2) ;
dbms_sql . bi nd_var i abl e( c, ' t abl e_col umn_val ue3' , t abl e_col umn_val ue3) ;

f dbk : = dbms_sql . execut e( c) ;

dbms_sql . cl ose_cur sor ( c) ;

commi t ;
dbms_out put . put _l i ne( ' Val ue i nser t ed <' | | t abl e_col umn_val ue1| | ' >' ) ;
dbms_out put . put _l i ne( ' Val ue i nser t ed <' | | t abl e_col umn_val ue2| | ' >' ) ;
dbms_out put . put _l i ne( ' Val ue i nser t ed <' | | t abl e_col umn_val ue3| | ' >' ) ;
END i nser t _i nt o_t abl e;


- - a DML wi t h or der ed bi nd var i abl es.
PROCEDURE i nser t s_i nt o_t abl e
( t abl e_name I N VARCHAR2
, t abl e_col umn_val ues1 I N DBMS_SQL. NUMBER_TABLE
, t abl e_col umn_val ues2 I N DBMS_SQL. VARCHAR2_TABLE
, t abl e_col umn_val ues3 I N DBMS_SQL. VARCHAR2_TABLE) I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;

BEGI N
- - Bui l d dynami c SQL st at ement .
st at ement : = ' I NSERT '
| | ' I NTO ' | | t abl e_name| | ' '
Page 643 Oracle DBA Code Examples

| | ' ( car d_number '
| | ' , car d_name '
| | ' , car d_sui t ) '
| | ' VALUES '
| | ' ( : car d_number '
| | ' , : car d_name'
| | ' , : car d_sui t ) ' ;

- - Par se t he st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

- - Bi nd each bi nd var i abl e.
dbms_sql . bi nd_ar r ay( c, ' car d_number ' , t abl e_col umn_val ues1) ;
dbms_sql . bi nd_ar r ay( c, ' car d_name' , t abl e_col umn_val ues2) ;
dbms_sql . bi nd_ar r ay( c, ' car d_sui t ' , t abl e_col umn_val ues3) ;

f dbk : = dbms_sql . execut e( c) ;

dbms_sql . cl ose_cur sor ( c) ;

commi t ;

- - Use a f or - l oop t o pr i nt val ues.
FOR i I N 1. . t abl e_col umn_val ues1. COUNT LOOP
dbms_out put . put _l i ne(
' Val ue i nser t ed <' | | t abl e_col umn_val ues1( i ) | | ' >' ) ;
dbms_out put . put _l i ne(
' Val ue i nser t ed <' | | t abl e_col umn_val ues2( i ) | | ' >' ) ;
dbms_out put . put _l i ne(
' Val ue i nser t ed <' | | t abl e_col umn_val ues3( i ) | | ' >' ) ;
END LOOP;
END i nser t s_i nt o_t abl e;


- - mul t i pl e r ow DQL
PROCEDURE mul t i pl e_r ow_r et ur n I S
- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;
val ue_out VARCHAR2( 1) ;
BEGI N
st at ement : = ' SELECT ' ' A' ' FROM DUAL' ;

dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

- - Def i ne t he col umn mappi ng t o t he val ue_out var i abl e.
dbms_sql . def i ne_col umn( c, 1, val ue_out , 1) ;

f dbk : = dbms_sql . execut e( c) ;
LOOP
- - Exi t when no mor e r ows t o f et ch.
EXI T WHEN dbms_sql . f et ch_r ows( c) = 0;
- - Copy t he cont ent s of col umn #1 t o t he val ue_out var i abl e.
dbms_sql . col umn_val ue( c, 1, val ue_out ) ;
dbms_out put . put _l i ne( ' Val ue f r omCOLUMN_VALUE <' | | val ue_out | | ' >' ) ;
END LOOP;
Page 644 Oracle DBA Code Examples

- - Cl ose t he open cur sor .
dbms_sql . cl ose_cur sor ( c) ;
END mul t i pl e_r ow_r et ur n;


- - mul t i pl e r ow wi t h col umns DQL.
PROCEDURE mul t i pl e_r ow_r et ur n
( t abl e_name VARCHAR2
, col umn_name1 VARCHAR2
, col umn_name2 VARCHAR2
, col umn_name3 VARCHAR2 ) I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;
cval ue_out 1 VARCHAR2( 2000) ;
cval ue_out 2 VARCHAR2( 2000) ;
nval ue_out NUMBER;

BEGI N

- - Bui l d dynami c SQL st at ement .
st at ement : = ' SELECT '
| | col umn_name1 | | ' , '
| | col umn_name2 | | ' , '
| | col umn_name3 | | ' '
| | ' FROM ' | | t abl e_name;

- - Par se dynami c SQL st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

/ *
| | Debuggi ng Ti p:
| | =============
| | Def i ne t he col umn val ues and DO NOT f or get t o assi gn a si ze
| | par amet er f or a st r i ng dat at ype, l i ke VARCHAR2; however , i f you
| | f or get , t he er r or message i s:
| | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| | PLS- 00307: t oo many decl ar at i ons of ' DEFI NE_COLUMN' mat ch t hi s cal l
*/

- - Def i ne t he col umn mappi ng t o t he val ue_out var i abl e.
dbms_sql . def i ne_col umn( c, 1, nval ue_out ) ;
dbms_sql . def i ne_col umn( c, 2, cval ue_out 1, 2000) ;
dbms_sql . def i ne_col umn( c, 3, cval ue_out 2, 2000) ;

- - Execut e dynami c SQL st at ement .
f dbk : = dbms_sql . execut e( c) ;

- - Use a l oop t o r ead al l r ows.
LOOP
- - Exi t when no mor e r ows t o f et ch.
EXI T WHEN dbms_sql . f et ch_r ows( c) = 0;

- - Copy t he cont ent s of col umn #1 t o t he val ue_out var i abl e.
dbms_sql . col umn_val ue( c, 1, nval ue_out ) ;
Page 645 Oracle DBA Code Examples

dbms_sql . col umn_val ue( c, 2, cval ue_out 1) ;
dbms_sql . col umn_val ue( c, 3, cval ue_out 2) ;

dbms_out put . put _l i ne(
' Val ue f r om[ ' | | col umn_name1| | ' ] ' | |
' i s: [ ' | | nval ue_out | | ' ] ' ) ;
dbms_out put . put _l i ne(
' Val ue f r om[ ' | | col umn_name1| | ' ] ' | |
' i s: [ ' | | SUBSTR( cval ue_out 1, 1, 5) | | ' ] ' ) ;
dbms_out put . put _l i ne(
' Val ue f r om[ ' | | col umn_name1| | ' ] ' | |
' i s: [ ' | | SUBSTR( cval ue_out 2, 1, 8) | | ' ] ' ) ;
END LOOP;
dbms_sql . cl ose_cur sor ( c) ;
END mul t i pl e_r ow_r et ur n;


- - si ngl e r ow DQL.
/ *
| | Demonst r at e a si ngl e r ow r et ur n usi ng t he DEFI NE_COLUMN and COLUMN_VALUE
| | pr ogr amuni t , as you woul d i n an expl i ci t cur sor .
*/
PROCEDURE si ngl e_r ow_r et ur n I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;
val ue_out VARCHAR2( 1) ;

BEGI N

- - Bui l d dynami c SQL st at ement .
st at ement : = ' SELECT ' ' A' ' FROM DUAL' ;

- - Par se t he dynami c SQL st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

/ *
| | Debuggi ng Ti p:
| | =============
| | Def i ne t he col umn val ues and DO NOT f or get t o assi gn a si ze
| | par amet er f or a st r i ng dat at ype, l i ke VARCHAR2; however , i f you
| | f or get , t he er r or message i s:
| | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| | PLS- 00307: t oo many decl ar at i ons of ' DEFI NE_COLUMN' mat ch t hi s cal l
| |
| | Thi s i s t he message r et ur ned because t he DEFI NE_COLUMN pr ocedur e
| | i s over l oaded and i t doesn' t know how t o i mpl i ci t l y cast wi t hout
| | t he OUT_VALUE_SI ZE ar gument . Onl y CHAR, RAWand VARCHAR2 suppor t
| | a f our t h ar gument .
*/

- - Def i ne t he col umn mappi ng t o t he val ue_out var i abl e.
dbms_sql . def i ne_col umn( c, 1, val ue_out , 1) ;

f dbk : = dbms_sql . execut e_and_f et ch( c) ;
Page 646 Oracle DBA Code Examples


- - Copy t he cont ent s of col umn #1 t o t he val ue_out var i abl e.
dbms_sql . col umn_val ue( c, 1, val ue_out ) ;

dbms_out put . put _l i ne(
' Val ue f r omCOLUMN_VALUE <' | | val ue_out | | ' >' ) ;

- - Cl ose t he open cur sor .
dbms_sql . cl ose_cur sor ( c) ;

END si ngl e_r ow_r et ur n;



- - si ngl e r ow DQL.
PROCEDURE si ngl e_r ow_r et ur n
( t abl e_name VARCHAR2
, col umn_name1 VARCHAR2
, col umn_name2 VARCHAR2
, col umn_name3 VARCHAR2 ) I S

- - Def i ne l ocal DBMS_SQL var i abl es.
c I NTEGER : = dbms_sql . open_cur sor ;
f dbk I NTEGER;
st at ement VARCHAR2( 2000) ;
cval ue_out 1 VARCHAR2( 20) ;
cval ue_out 2 VARCHAR2( 30) ;
nval ue_out NUMBER;

BEGI N

- - Bui l d dynami c SQL st at ement .
st at ement : = ' SELECT '
| | col umn_name1 | | ' , '
| | col umn_name2 | | ' , '
| | col umn_name3 | | ' '
| | ' FROM ' | | t abl e_name;

- - Par se t he dynami c SQL st at ement .
dbms_sql . par se( c, st at ement , dbms_sql . nat i ve) ;

/ *
| | Debuggi ng Ti p:
| | =============
| | Def i ne t he col umn val ues and DO NOT f or get t o assi gn a si ze
| | par amet er f or a st r i ng dat at ype, l i ke VARCHAR2; however , i f you
| | f or get , t he er r or message i s:
| | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| | PLS- 00307: t oo many decl ar at i ons of ' DEFI NE_COLUMN' mat ch t hi s cal l
| |
| | Thi s i s t he message r et ur ned because t he DEFI NE_COLUMN pr ocedur e
| | i s over l oaded and i t doesn' t know how t o i mpl i ci t l y cast wi t hout
| | t he OUT_VALUE_SI ZE ar gument . Onl y CHAR, RAWand VARCHAR2 suppor t
| | a f our t h ar gument .
*/

- - Def i ne t he col umn mappi ng t o t he val ue_out var i abl e.
Page 647 Oracle DBA Code Examples

dbms_sql . def i ne_col umn( c, 1, nval ue_out ) ;
dbms_sql . def i ne_col umn( c, 2, cval ue_out 1, 20) ;
dbms_sql . def i ne_col umn( c, 3, cval ue_out 2, 30) ;

- - Execut e dynami c SQL st at ement .
f dbk : = dbms_sql . execut e_and_f et ch( c) ;

- - Copy t he cont ent s of col umn #1 t o t he val ue_out var i abl e.
dbms_sql . col umn_val ue( c, 1, nval ue_out ) ;
dbms_sql . col umn_val ue( c, 2, cval ue_out 1) ;
dbms_sql . col umn_val ue( c, 3, cval ue_out 2) ;

- - Pr i nt out put message.
dbms_out put . put _l i ne( ' Val ue f r omCOLUMN_VALUE <' | | nval ue_out | | ' >' ) ;
dbms_out put . put _l i ne( ' Val ue f r omCOLUMN_VALUE <' | | cval ue_out 1| | ' >' ) ;
dbms_out put . put _l i ne( ' Val ue f r omCOLUMN_VALUE <' | | cval ue_out 2| | ' >' ) ;

dbms_sql . cl ose_cur sor ( c) ;
END si ngl e_r ow_r et ur n;
Page 648 Oracle DBA Code Examples

Calling Java from PL/SQL
Pre-requisits:
o set CLASSPATH should contain:
. current directory
Oracle 11g: %ORACLE_HOME%/jdbc/lib/ojdbc5.jar (or 6 but not both)
ORACLE_HOME/jlib/orai18n.jar
Oracle 10g: %ORACLE_HOME%/jdbc/lib/classes12.zip
Java JDK or J2SE 5.n or 6.n
In Oracle 11g, the oracle.jdbc.driver.* classes, the ojdbc4.jar file, and the
OracleConnectionCacheImpl class are no longer supported or available.
o Make sure PATH points to JDK home.
/ * t o cr eat e a Thi ck J ava cl i ent pr ogr amt o Or acl e 11g */
- - J DBCExampl e. j ava
i mpor t j ava. sql . *;
i mpor t or acl e. j dbc. pool . Or acl eDat aSour ce;

publ i c cl ass J DBCExampl e {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows SQLExcept i on
/ * Decl ar e t he t ype of Or acl e Dr i ver you ar e usi ng */
{ Dr i ver Manager . r egi st er Dr i ver ( new or acl e. j dbc. dr i ver . Or acl eDr i ver ( ) ) ;

/ * Cr eat e a dat abase connect i on f or t he J DBC pr ogr am*/
Connect i on conn=
Dr i ver Manager . get Connect i on( " j dbc: or acl e: t hi n: @sr v01: 1521: or a11g" , " HR" , " h" ) ;
St at ement st mt = conn. cr eat eSt at ement ( ) ;

/ * Pass a quer y t o SQL and st or e t he r esul t s i n t he r esul t set r s */
Resul t Set r s = st mt . execut eQuer y( " sel ect empl oyee_i d, l ast _name f r om
empl oyees" ) ;

/ * Usi ng t he whi l e l oop, r esul t set r s i s accessed r ow by r ow */
whi l e( r s. next ( ) ) {
i nt number = r s. get I nt ( 1) ;
St r i ng name= r s. get St r i ng( 2) ;
Syst em. out . pr i nt l n( number +" " +name) ;
}

/ * Cl ose t he J DBC r esul t set and cl ose t he dat abase connect i on */
r s. cl ose( ) ;
conn. cl ose( ) ;
}
}


- - l oad t hat i nt o t he dat abase :
l oadj ava - r - f - o - user HR/ h J DBCExampl e. cl ass
Page 649 Oracle DBA Code Examples

Configuring Oracle Database to Use External Routines
o For further details refer to the documentation or Oracle Database 10g PL/SQL
Programming by Ron Hardman, Michael McLaughlin and Scott Urman, Oracle Press.
Conf i gur e one l i st ener f or t he dat abase and one f or t he t he ext pr oc agent
#( 1) I n l i st ener . or a
# r emove t he I PC pr ot ocol f r omt he st andar d set t i ngs
LI STENER =
( DESCRI PTI ON_LI ST =
( DESCRI PTI ON =
( ADDRESS_LI ST =
( ADDRESS =
( PROTOCOL = TCP)
( HOST = sr v01)
( PORT = 1521)
)
)
)
)

SI D_LI ST_LI STENER =
( SI D_LI ST =
( SI D_DESC =
( SI D_NAME = or a11g)
( ORACLE_HOME = E: \ or acl e\ Or aDB11g)
)
)


# anot her l i st ener . " ext pr oc" l ower case
CALLOUT_LI STENER =
( DESCRI PTI ON_LI ST =
( DESCRI PTI ON =
( ADDRESS_LI ST =
( ADDRESS =
( PROTOCOL = I PC)
( KEY = ext pr oc)
)
)
)
)


# " PLSExt Pr oc" case sensi t i ve
# ( ENV =
" EXTPROC_DLLS=ONLY: <cust om_dl l _di r ect or y>/ <cust om_shar ed_l i br ar y>, LD_LI BRARY_P
ATH=E: \ or acl e\ Or aDB11g\ LI B" )
SI D_LI ST_CALLOUT_LI STENER =
( SI D_LI ST =
( SI D_DESC =
( SI D_NAME = PLSExt Pr oc)
( ORACLE_HOME = E: \ or acl e\ Or aDB11g)
( PROGRAM = ext pr oc)
( ENV =
" EXTPROC_DLLS=ONLY: C: \ myf i l es\ dl l / C: \ myf i l es\ l i b, LD_LI BRARY_PATH=E: \ or acl e\ Or a
Page 650 Oracle DBA Code Examples

DB11g\ LI B" )
)
)

# i f t her e i s an ASM i nst ance
( SI D_DESC =
( GLOBAL_DBNAME = or a11g. sr v01)
( ORACLE_HOME=E: \ or acl e\ Or aDB11g\ dat abase)
( SI D_NAME = +ASM)
)



#( 2) Add t he f ol l owi ng i n t o t he t nsnames. or a
EXTPROC_CONNECTI ON_DATA =
( DESCRI PTI ON =
( ADDRESS_LI ST =
( ADDRESS = ( PROTOCOL = I PC)
( KEY = ext pr oc) )
)
( CONNECT_DATA =
( SI D = PLSExt Pr oc)
( PRESENTATI ON = RO)
)
)


#( 3) r ebui l d t he or i gi nal l i st ener ser vi ce and cr eat e new one
# I n Wi ndows
l snr ct l st op
# use NETCA t o del et e t he or i gi nal ser vi ce and t hen r e- cr eat e i t .
# bui l d a new ser vi ce f or t he second l i st ener CALLOUT_LI STENER. A new
l i nst ener . or a wi l l
# be cr eat ed so past e agai n t he code above i n t he f i l e.

# I n Uni x
l snr ct l st op LI STENER
# backup t he or i gi nal l i nst ener . or a and t nsnames f i l es
# copy t he new ones
l snr ct l st ar t LI STENER
l snr ct l st ar t CALLOUT_LI STENER
# ver i f y
ps ef | gr ep v gr ep | gr ep t nsl snr

#( 4) ver i f y t he conf i gur at i on
t nspi ng EXTPROC_CONNECTI ON_DATA
I f you get a TNS- 12541 er r or when usi ng t nspi ng, t he l i kel i hood i s t hat t her e
i s a mi smat ch bet ween t he ADDRESS par amet er val ues i n t he l i st ener . or a and
t nsnames. or a f i l es.

# t he f ol l owi ng command shoul d r et ur n t he f ol l owi ng er r or :
sql pl us pl sql / pl sql @EXTPROC_CONNECTI ON_DATA
ORA- 28547: connect i on t o ser ver f ai l ed, pr obabl e Or acl e Net admi n er r or



Wor ki ng wi t h a C Shar ed Li br ar y
Def i ne a C shar ed l i br ar y:
Page 651 Oracle DBA Code Examples

#i ncl ude <st di o. h>

/ * Decl ar e a wr i t est r f unct i on. */
voi d wr i t est r 1( char *pat h, char *message)
{
/ * Decl ar e a FI LE var i abl e. */
FI LE *f i l e_name;

/ * Open t he Fi l e. */
f i l e_name = f open( pat h, " w" ) ;

/ * Wr i t e t o f i l e t he message r ecei ved. */
f pr i nt f ( f i l e_name, " %s\ n" , message) ;

/ * Cl ose t he f i l e. */
f cl ose( f i l e_name) ;

}


Uni x C Compi l er t hat suppor t s t he G opt i on
cc G o wr i t est r 1. so wr i t est r 1. c
Uni x C Compi l er t hat suppor t s t he shar ed opt i on
cc shar ed o wr i t est r 1. so wr i t est r 1. c
- OR -
gcc shar ed o wr i t est r 1. so wr i t est r 1. c


# Def i ni ng and Cal l i ng t he PL/ SQL Li br ar y Wr apper
CREATE OR REPLACE LI BRARY l i br ar y_wr i t e_st r i ng AS
' <or acl e_home_di r ect or y>/ <cust om_l i br ar y>/ <f i l e_name>. <f i l e_ext >' ;
/

CREATE OR REPLACE PROCEDURE wr i t e_st r i ng
( pat h VARCHAR2 , message VARCHAR2) AS EXTERNAL
LI BRARY l i br ar y_wr i t e_st r i ng
NAME " wr i t est r "
PARAMETERS ( pat h STRI NG , message STRI NG) ;
/

- - Avai l abl e onl i ne as par t of cr eat e_l i br ar y1. sql
BEGI N
- - Cal l t he ext er nal pr ocedur e.
wr i t e_st r i ng( ' / t mp/ f i l e. t xt ' , ' Hel l o Wor l d! ' ) ;
END;
/
Page 652 Oracle DBA Code Examples

Using Large Objects (LOBs)
Creating LOB
To specify different storage options, use the following syntax in your create table
statement:
CREATE TABLE t abl e_name ( . . l ob_col umn l ob_dat at ype )
LOB ( l ob_col umn, . . ) STORE AS [ l ob_segment _name]
[ ( TABLESPACE t abl espace
{ENABLE| DI SABLE} STORAGE I N ROW
STORAGE st or age_cl ause
CHUNK i nt
PCTVERSI ON i nt
CACHE
CACHE READS [ [ NO] LOGGI NG]
NOCACHE [ [ NO] LOGGI NG] )
PCTVERSION defaults to 10
NOCACHE is the default
ENABLE STORAGE IN ROW, which is the default setting, says that if the LOB value is less
than 4K (including control information), store it inline.
CREATE TABLE book_sampl es (
book_sampl e_i d NUMBER ( 10) PRI MARY KEY,
i sbn CHAR( 10 CHAR) ,
descr i pt i on CLOB,
nl s_descr i pt i on NCLOB,
book_cover BLOB,
chapt er _t i t l e VARCHAR2( 30 CHAR) ,
chapt er BFI LE
)
LOB ( book_cover )
STORE AS bl ob_seg ( TABLESPACE bl ob_t s
CHUNK 8192
PCTVERSI ON 0
NOCACHE
NOLOGGI NG
DI SABLE STORAGE I N ROW)
LOB ( descr i pt i on, nl s_descr i pt i on)
STORE AS ( TABLESPACE cl ob_t s
CHUNK 8192
PCTVERSI ON 10
NOCACHE
LOGGI NG
ENABLE STORAGE I N ROW) ;
Using SQL with Internal LOBs
With SQL, you can insert, update, and delete internal LOBs.
SQL does not yet support piecewise manipulation of LOBs.
SET LONG 64000
Page 653 Oracle DBA Code Examples

SELECT descr i pt i on FROM book_sampl es;

- - empt y_cl ob( ) cr eat es a l ocat or
I NSERT I NTO book_sampl es (
book_sampl e_i d,
i sbn,
descr i pt i on,
nl s_descr i pt i on,
book_cover ,
chapt er )
VALUES (
1,
' 72230665' ,
' The . . . ' ,
EMPTY_CLOB(),
EMPTY_BLOB(),
BFILENAME( ' BOOK_SAMPLES_LOC' , ' 72230665. j pg' ) ) ;

UPDATE book_sampl es SET descr i pt i on = EMPTY_CLOB( ) WHERE descr i pt i on I S NOT
NULL;
Using LOBs in PL/SQL
A opened BFILE should be closed after handling it.
SESSION_MAX_OPEN_FILES controls the number of BFILEs that can be open at any one
time.
/ * APPEND */
CREATE OR REPLACE PROCEDURE LOBAPPEND (
i o_l ob_sour ce I N OUT NCLOB,
i o_l ob_dest i nat i on I N OUT NCLOB)
AS
BEGI N
DBMS_LOB. OPEN( i o_l ob_sour ce, DBMS_LOB. LOB_READONLY) ;
DBMS_LOB. OPEN( i o_l ob_dest i nat i on, DBMS_LOB. LOB_READWRI TE) ;

DBMS_LOB. APPEND( i o_l ob_dest i nat i on, i o_l ob_sour ce) ;

- - al ways cl ose l ob af t er handl i ng t hem
DBMS_LOB. CLOSE( i o_l ob_sour ce) ;
DBMS_LOB. CLOSE( i o_l ob_dest i nat i on) ;
END;
/

SET SERVEROUTPUT ON

DECLARE
v_sour ce_l ob_l oc NCLOB;
v_dest i nat i on_l ob_l oc NCLOB;
v_combi ned_l ob NCLOB;
BEGI N
- - f or updat e i s a must her e
SELECT nl s_descr i pt i on
I NTO v_sour ce_l ob_l oc
FROM book_sampl es_nl s
FOR UPDATE;
Page 654 Oracle DBA Code Examples


SELECT nl s_descr i pt i on
I NTO v_dest i nat i on_l ob_l oc
FROM book_sampl es
FOR UPDATE;

LOBAPPEND( v_sour ce_l ob_l oc, v_dest i nat i on_l ob_l oc) ;

SELECT nl s_descr i pt i on
I NTO v_combi ned_l ob
f r ombook_sampl es;

DBMS_OUTPUT. PUT_LI NE( SUBSTR( v_combi ned_l ob, 1, 150) ) ;
DBMS_OUTPUT. PUT_LI NE( SUBSTR( v_combi ned_l ob, 151, 300) ) ;
END;
/



/ * COMPARE */
I f 0 i s r et ur ned, t hen t he LOBs ar e t he same. I f 1 i s r et ur ned, t hen t hey ar e
di f f er ent .
FUNCTI ON COMPARE RETURNS NUMBER( 38)
Ar gument Name Type I n/ Out Def aul t ?
-
LOB_1 CLOB I N
LOB_2 CLOB I N
AMOUNT NUMBER( 38) I N DEFAULT
OFFSET_1 NUMBER( 38) I N DEFAULT
OFFSET_2 NUMBER( 38) I N DEFAULT

CREATE OR REPLACE PROCEDURE CLOB_COMPARE (
v_l ob1 I N OUT CLOB,
v_l ob2 I N OUT CLOB)
AS
v_compar e PLS_I NTEGER : = 0;
BEGI N
DBMS_LOB. OPEN( v_l ob1, DBMS_LOB. LOB_READONLY) ;
DBMS_LOB. OPEN( v_l ob2, DBMS_LOB. LOB_READONLY) ;
- - buf f er si ze used 32K ( t he max)
v_compar e : = DBMS_LOB. COMPARE( v_l ob1, v_l ob2, 32768, 1, 1) ;

DBMS_OUTPUT. PUT_LI NE( ' The val ue r et ur ned by COMPARE i s: ' | | v_compar e) ;

DBMS_LOB. CLOSE( v_l ob1) ;
DBMS_LOB. CLOSE( v_l ob2) ;
END;
/
DECLARE
v_l ob1 CLOB;
v_l ob2 CLOB;
v_l ob3 CLOB;
BEGI N
SELECT descr i pt i on
I NTO v_l ob1
FROM book_sampl es
WHERE book_sampl e_i d = 1;
Page 655 Oracle DBA Code Examples


SELECT descr i pt i on
I NTO v_l ob2
FROM book_sampl es
WHERE book_sampl e_i d = 2;

SELECT descr i pt i on
I NTO v_l ob3
FROM book_sampl es
WHERE book_sampl e_i d = 3;

CLOB_COMPARE( v_l ob1, v_l ob2) ;

CLOB_COMPARE( v_l ob1, v_l ob3) ;
END;
/



/ * CONVERTTO. . LOB */
PROCEDURE CONVERTTOBLOB
DEST_LOB BLOB I N/ OUT
# i n CONVERTTOCLOB t he f ol l owi ng i s SRC_BLOB
SRC_CLOB CLOB I N
AMOUNT NUMBER( 38) I N
DEST_OFFSET NUMBER( 38) I N/ OUT
SRC_OFFSET NUMBER( 38) I N/ OUT
BLOB_CSI D NUMBER I N
LANG_CONTEXT NUMBER( 38) I N/ OUT
WARNI NG NUMBER( 38) OUT

CREATE OR REPLACE PROCEDURE CONVERT_ME (
v_bl ob_or _cl ob I N NUMBER, - - i f 0 TOBLOB, i f 1 TOCLOB
v_bl ob I N OUT BLOB,
v_cl ob I N OUT CLOB,
v_amount I N OUT NUMBER,
v_bl ob_of f set I N OUT NUMBER,
v_cl ob_of f set I N OUT NUMBER,
v_l ang_cont ext I N OUT NUMBER,
v_war ni ng OUT NUMBER)
AS
BEGI N

DBMS_LOB. OPEN( v_bl ob, DBMS_LOB. LOB_READWRI TE) ;
DBMS_LOB. OPEN( v_cl ob, DBMS_LOB. LOB_READWRI TE) ;

I F v_bl ob_or _cl ob = 0
THEN
DBMS_LOB. CONVERTTOBLOB( v_bl ob,
v_cl ob,
v_amount ,
v_bl ob_of f set ,
v_cl ob_of f set ,
1,
v_l ang_cont ext ,
v_war ni ng) ;
ELSE
Page 656 Oracle DBA Code Examples

DBMS_LOB. CONVERTTOCLOB( v_cl ob,
v_bl ob,
v_amount ,
v_cl ob_of f set ,
v_bl ob_of f set ,
1,
v_l ang_cont ext ,
v_war ni ng) ;
END I F;

DBMS_LOB. CLOSE( v_bl ob) ;
DBMS_LOB. CLOSE( v_cl ob) ;

END;
/


DECLARE
v_cl ob_or _bl ob NUMBER;
v_bl ob_l ocat or BLOB;
v_cl ob_l ocat or CLOB;
v_bl ob_of f set NUMBER;
v_cl ob_of f set NUMBER;
v_l ang_cont ext NUMBER : = DBMS_LOB. DEFAULT_LANG_CTX;
v_war ni ng NUMBER;
v_st r i ng_l engt h NUMBER( 10) ;
v_sour ce_l ocat or BLOB;
v_dest i nat i on_l ocat or BLOB;
v_amount PLS_I NTEGER;
v_st r i ng CLOB;
BEGI N

- - CONVERT CLOB TO BLOB

SELECT descr i pt i on
I NTO v_cl ob_l ocat or
FROM book_sampl es
WHERE book_sampl e_i d = 1
FOR UPDATE;

SELECT mi sc
I NTO v_bl ob_l ocat or
FROM book_sampl es
WHERE book_sampl e_i d = 1
FOR UPDATE;

v_st r i ng_l engt h : = DBMS_LOB. GETLENGTH( v_bl ob_l ocat or ) ;
v_amount : = DBMS_LOB. GETLENGTH( v_cl ob_l ocat or ) ;

DBMS_OUTPUT. PUT_LI NE( ' The i ni t i al l engt h of t he BLOB i s:
' | | v_st r i ng_l engt h) ;

v_cl ob_or _bl ob : = 0; - - Conver t cl ob t o bl ob
v_cl ob_of f set : = 1;
v_bl ob_of f set : = 1;

CONVERT_ME( v_cl ob_or _bl ob,
Page 657 Oracle DBA Code Examples

v_bl ob_l ocat or ,
v_cl ob_l ocat or ,
v_amount ,
v_bl ob_of f set ,
v_cl ob_of f set ,
v_l ang_cont ext ,
v_war ni ng) ;

v_st r i ng_l engt h : = DBMS_LOB. GETLENGTH( v_bl ob_l ocat or ) ;

DBMS_OUTPUT. PUT_LI NE( ' The l engt h of t he BLOB post - conver si on i s:
' | | v_st r i ng_l engt h) ;

- - COPY BLOB FOR ONE ROWTO BLOB I N ANOTHER
v_sour ce_l ocat or : = v_bl ob_l ocat or ;

SELECT mi sc
I NTO v_dest i nat i on_l ocat or
FROM book_sampl es
WHERE book_sampl e_i d = 2
FOR UPDATE;

DBMS_LOB. COPY( v_dest i nat i on_l ocat or , v_sour ce_l ocat or , 32768, 1, 1) ;

v_st r i ng_l engt h : = DBMS_LOB. GETLENGTH( v_dest i nat i on_l ocat or ) ;

DBMS_OUTPUT. PUT_LI NE( ' The l engt h of t he BLOB post - copy i s:
' | | v_st r i ng_l engt h) ;

- - COPY BLOB FOR RECORD 2 BACK TO A CLOB

SELECT descr i pt i on
I NTO v_cl ob_l ocat or
FROM book_sampl es
WHERE book_sampl e_i d = 2
FOR UPDATE;

SELECT mi sc
I NTO v_bl ob_l ocat or
FROM book_sampl es
WHERE book_sampl e_i d = 2
FOR UPDATE;

v_st r i ng_l engt h : = DBMS_LOB. GETLENGTH( v_cl ob_l ocat or ) ;
- - v_ammount must equal t o BLOB si ze, ot her wi se ORA-22993 will return
v_amount : = DBMS_LOB. GETLENGTH( v_bl ob_l ocat or ) ;

DBMS_OUTPUT. PUT_LI NE( ' The i ni t i al l engt h of t he CLOB ( r ecor d 2) i s:
' | | v_st r i ng_l engt h) ;

v_cl ob_or _bl ob : = 1; - - Conver t bl ob t o cl ob
- - must be r eset t o 1 because i t s val ue changed by t he
- - pr evi ous cal l of CONVERT_ME
v_cl ob_of f set : = 1;
v_bl ob_of f set : = 1;

CONVERT_ME( v_cl ob_or _bl ob,
v_bl ob_l ocat or ,
Page 658 Oracle DBA Code Examples

v_cl ob_l ocat or ,
v_amount ,
v_cl ob_of f set ,
v_bl ob_of f set ,
v_l ang_cont ext ,
v_war ni ng) ;

v_st r i ng_l engt h : = DBMS_LOB. GETLENGTH( v_cl ob_l ocat or ) ;

SELECT descr i pt i on
I NTO v_st r i ng
FROM book_sampl es
WHERE book_sampl e_i d = 2;

DBMS_OUTPUT. PUT_LI NE( ' The l engt h of t he CLOB post - conver si on i s:
' | | v_st r i ng_l engt h) ;

DBMS_OUTPUT. PUT_LI NE( ' The conver t ed CLOB' ) ;
DBMS_OUTPUT. PUT_LI NE( ' ==================' ) ;
DBMS_OUTPUT. PUT_LI NE( SUBSTR( v_st r i ng, 1, 150) ) ;
DBMS_OUTPUT. PUT_LI NE( SUBSTR( v_st r i ng, 151, 300) ) ;
END;
/



/ * BFI LE FI LEEXI STS */
- - Thi s f unct i on t est s whet her a f i l e exi st s by t he name speci f i ed i n t he
i nser t st at ement

I NSERT I NTO book_sampl es (
book_sampl e_i d,
i sbn,
descr i pt i on,
nl s_descr i pt i on,
mi sc,
bf i l e_descr i pt i on)
VALUES (
1,
' 72230665' ,
EMPTY_CLOB( ) ,
EMPTY_CLOB( ) ,
EMPTY_BLOB( ) ,
BFI LENAME( ' BOOK_SAMPLES_LOC' , ' bf i l e_exampl e. pdf ' ) ) ;

CREATE OR REPLACE PROCEDURE CHECK_FI LE ( v_bf i l e I N BFI LE)
AS
v_exi st s PLS_I NTEGER : = 0;
BEGI N

v_exi st s : = DBMS_LOB. FI LEEXI STS( v_bf i l e) ;

I F v_exi st s = 0
THEN
DBMS_OUTPUT. PUT_LI NE ( ' The f i l e does not exi st s i n t he di r ect or y
speci f i ed' ) ;
ELSE
DBMS_OUTPUT. PUT_LI NE ( ' The f i l e exi st s and t he di r ect or y val i d! ' ) ;
Page 659 Oracle DBA Code Examples

END I F;
END;
/

DECLARE
v_bf i l e BFI LE;
BEGI N
SELECT bf i l e_descr i pt i on
I NTO v_bf i l e
FROM book_sampl es
WHERE book_sampl e_i d = 1;

CHECK_FI LE( v_bf i l e) ;
END;
/


/ * BFI LE FI LEOPEN/ OPEN */
- - Or acl e r ecommends t hat OPEN be used i nst ead of FI LEOPEN.
PROCEDURE OPEN
Ar gument Name Type I n/ Out Def aul t ?
-
FI LE_LOC BI NARY FI LE LOB I N/ OUT
OPEN_MODE BI NARY_I NTEGER I N DEFAULT

OPEN_MODE: DBMS_LOB. LOB_READONLY or DBMS_LOB. LOB_READWRI TE



/ * BFI LE FI LEI SOPEN/ I SOPEN */
- - I SOPEN shoul d be used i n pl ace of FI LEI SOPEN when possi bl e.
CREATE OR REPLACE PROCEDURE CHECK_STATUS (
v_bf i l e I N BFI LE)
AS
v_i sopen PLS_I NTEGER : = 0;
BEGI N
v_i sopen : = DBMS_LOB. I SOPEN( v_bf i l e) ;
I F v_i sopen = 0
THEN
DBMS_OUTPUT. PUT_LI NE ( ' The f i l e i s not open. You must open t he' ) ;
ELSE
DBMS_OUTPUT. PUT_LI NE ( ' The f i l e i s open al r eady. ' ) ;
END I F;
END;
/
DECLARE
v_bf i l e BFI LE;
BEGI N
SELECT bf i l e_descr i pt i on
I NTO v_bf i l e
FROM book_sampl es
WHERE book_sampl e_i d = 1;

CHECK_STATUS( v_bf i l e) ;
END;
/

Page 660 Oracle DBA Code Examples



/ * BFI LE FI LECLOSE/ CLOSE/ FI LECLOSEALL */
FI LECLOSE and CLOSE bot h cl ose one BFI LE at a t i me, whi l e FI LECLOSEALL cl oses
al l open BFI LEs. I t i s r ecommended by Or acl e t hat CLOSE be used r at her t han
FI LECLOSE f or al l new devel opment . CLOSE can be used wi t h al l LOB t ypes, not
j ust BFI LEs.

CREATE OR REPLACE PROCEDURE CLOSE_ALL_FI LES
AS
v_i sopen PLS_I NTEGER : = 0;
v_count er PLS_I NTEGER : = 0;
v_bf i l e BFI LE;

CURSOR cur _bf i l e I S
SELECT bf i l e_descr i pt i on
FROM book_sampl es;
BEGI N
DBMS_OUTPUT. PUT_LI NE( ' Open al l BFI LEs i n t he t abl e' ) ;
OPEN cur _bf i l e;
LOOP
FETCH cur _bf i l e I NTO v_bf i l e;
EXI T WHEN cur _bf i l e%NOTFOUND;
BEGI N
v_count er : = v_count er + 1;
DBMS_LOB. OPEN( v_bf i l e) ;
v_i sopen : = DBMS_LOB. I SOPEN( v_bf i l e) ;
I F v_i sopen = 0
THEN
DBMS_OUTPUT. PUT_LI NE ( ' Fi l e number ' | | v_count er | | ' i s cl osed' ) ;
ELSE
DBMS_OUTPUT. PUT_LI NE ( ' Fi l e number ' | | v_count er | | ' i s open' ) ;
END I F;
END;
END LOOP;

CLOSE cur _bf i l e;

DBMS_LOB. FI LECLOSEALL( ) ;
DBMS_OUTPUT. PUT_LI NE( ' DONE ' ) ;
END;
/



/ * LOADFROMFI LE/ LOADCLOBFROMFI LE/ LOADBLOBFROMFI LE */
l oad f i l e cont ent s t o CLOB and BLOB col umns. I t i s
r ecommended t hat LOADCLOBFROMFI LE and LOADBLOBFROMFI LE be used f or
t hei r speci f i c dat at ypes r at her t han usi ng t he gener i c over l oaded
LOADFROMFI LE.

PROCEDURE LOADBLOBFROMFI LE
Ar gument Name Type I n/ Out Def aul t ?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEST_LOB BLOB I N/ OUT
SRC_BFI LE BI NARY FI LE LOB I N
AMOUNT NUMBER( 38) I N
Page 661 Oracle DBA Code Examples

DEST_OFFSET NUMBER( 38) I N/ OUT
SRC_OFFSET NUMBER( 38) I N/ OUT
PROCEDURE LOADCLOBFROMFI LE
Ar gument Name Type I n/ Out Def aul t ?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEST_LOB CLOB I N/ OUT
SRC_BFI LE BI NARY FI LE LOB I N
AMOUNT NUMBER( 38) I N
DEST_OFFSET NUMBER( 38) I N/ OUT
SRC_OFFSET NUMBER( 38) I N/ OUT
BFI LE_CSI D NUMBER I N
LANG_CONTEXT NUMBER( 38) I N/ OUT
WARNI NG NUMBER( 38) OUT

set ser ver out put on

DECLARE
v_dest _bl ob BLOB;
v_dest _cl ob CLOB;
v_sour ce_l ocat or 1 BFI LE : = BFI LENAME( ' BOOK_SAMPLES_LOC' ,
' bf i l e_exampl e. pdf ' ) ;
v_sour ce_l ocat or 2 BFI LE : = BFI LENAME( ' BOOK_SAMPLES_LOC' ,
' bf i l e_exampl e. t xt ' ) ;
v_sour ce_of f set NUMBER : = 1;
v_dest _of f set NUMBER : = 1;
v_l ang_cont ext NUMBER : = DBMS_LOB. DEFAULT_LANG_CTX;
v_war ni ng PLS_I NTEGER;
BEGI N
- - Empt y t he descr i pt i on and mi sc col umns
UPDATE book_sampl es
SET descr i pt i on = EMPTY_CLOB( ) , mi sc = EMPTY_BLOB( )
WHERE book_sampl e_i d = 1;

- - Ret r i eve t he l ocat or s f or t he t wo dest i nat i on col umns
SELECT descr i pt i on, mi sc
I NTO v_dest _cl ob, v_dest _bl ob
FROM book_sampl es
WHERE book_sampl e_i d = 1
FOR UPDATE;

- - Open t he BFI LEs and dest i nat i on LOBs
DBMS_LOB. OPEN( v_sour ce_l ocat or 1, DBMS_LOB. LOB_READONLY) ;
DBMS_LOB. OPEN( v_sour ce_l ocat or 2, DBMS_LOB. LOB_READONLY) ;
DBMS_LOB. OPEN( v_dest _bl ob, DBMS_LOB. LOB_READWRI TE) ;
DBMS_LOB. OPEN( v_dest _cl ob, DBMS_LOB. LOB_READWRI TE) ;

DBMS_OUTPUT. PUT_LI NE( ' Lengt h of t he BLOB f i l e i s:
' | | DBMS_LOB. GETLENGTH( v_sour ce_l ocat or 1) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Lengt h of t he CLOB f i l e i s:
' | | DBMS_LOB. GETLENGTH( v_sour ce_l ocat or 2) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Si ze of BLOB pr e- l oad:
' | | DBMS_LOB. GETLENGTH( v_dest _bl ob) ) ;
DBMS_OUTPUT. PUT_LI NE( ' Si ze of CLOB pr e- l oad:
' | | DBMS_LOB. GETLENGTH( v_dest _cl ob) ) ;

- - Load t he dest i nat i on col umns f r omt he sour ce
DBMS_LOB. LOADBLOBFROMFI LE( v_dest _bl ob, v_sour ce_l ocat or 1,
DBMS_LOB. LOBMAXSI ZE, v_dest _of f set , v_sour ce_of f set ) ;
Page 662 Oracle DBA Code Examples

DBMS_OUTPUT. PUT_LI NE( ' Si ze of BLOB post - l oad: ' | | ( v_dest _of f set - 1) ) ;

v_dest _of f set : = 1;
v_sour ce_of f set : = 1;

DBMS_LOB. LOADCLOBFROMFI LE( v_dest _cl ob,
v_sour ce_l ocat or 2,
DBMS_LOB. LOBMAXSI ZE,
v_dest _of f set ,
v_sour ce_of f set ,
DBMS_LOB. DEFAULT_CSI D,
v_l ang_cont ext ,
v_war ni ng) ;

DBMS_OUTPUT. PUT_LI NE( ' Si ze of CLOB post - l oad: ' | | ( v_dest _of f set - 1) ) ;

- - Cl ose t he LOBs t hat we opened
DBMS_LOB. CLOSE( v_sour ce_l ocat or 1) ;
DBMS_LOB. CLOSE( v_sour ce_l ocat or 2) ;
DBMS_LOB. CLOSE( v_dest _bl ob) ;
DBMS_LOB. CLOSE( v_dest _cl ob) ;

EXCEPTI ON
WHEN OTHERS
THEN
DBMS_OUTPUT. PUT_LI NE( SQLERRM) ;
DBMS_LOB. CLOSE( v_sour ce_l ocat or 1) ;
DBMS_LOB. CLOSE( v_sour ce_l ocat or 2) ;
DBMS_LOB. CLOSE( v_dest _bl ob) ;
DBMS_LOB. CLOSE( v_dest _cl ob) ;
END;
/

SET LONG 64000
SELECT descr i pt i on
FROM book_sampl es
WHERE book_sampl e_i d = 1;
Performance Considerations
Using Returning Clause
RETURNING is a keyword added to the end of the INSERT statement allowing you to work
with the LOB immediately, without any additional steps.
DECLARE
v_cl ob CLOB;
BEGI N
I NSERT I NTO book_sampl es (
book_sampl e_i d,
i sbn,
descr i pt i on,
nl s_descr i pt i on,
book_cover ,
chapt er )
VALUES (
Page 663 Oracle DBA Code Examples

1,
' 72230665' ,
' The . . . ' ,
EMPTY_CLOB( ) ,
EMPTY_BLOB( ) ,
BFI LENAME( ' BOOK_SAMPLES_LOC' , ' 72230665. j pg' ) )
RETURNI NG descr i pt i on I NTO v_cl ob;
COMMI T;
DBMS_OUTPUT. PUT_LI NE( v_cl ob) ;
END;
/
Using CONTEXT Index
You can apply many indexing types. The examples here show how to use CONTEXT index.
Using the CONTEXT index, we are able to perform the following types of queries:
o Boolean searches AND, OR, NOT.
o Exact matches Search for the exact word or phrase inside the text.
o Inexact matches Search using stemming (a search for mice finds mouse), wildcard,
soundex (one word sounds like another).
o Proximity A word is near another.
o Ranking A value is provided based on relevance to the keywords used in the query.
o Theme searches Search on what a document or text is about.
Refer to Oracle Text documentation for further details.
/ * Cr eat i ng CONTEXT I ndex */
- - 1) cr eat e named pr ef er ences
- - I f you want t o i ndex t ext i n anot her l anguage: eg J APANESE_LEXER and
J APANESE_VGRAM_LEXER
- - WORLD_LEXER t hat can det ect t he l anguage of t he t ext
BEGI N
ct x_ddl . cr eat e_pr ef er ence ( ' l ob_l exer ' , ' basi c_l exer ' ) ;
ct x_ddl . set _at t r i but e ( ' l ob_l exer ' , ' i ndex_t ext ' , ' t r ue' ) ;
ct x_ddl . set _at t r i but e ( ' l ob_l exer ' , ' i ndex_t hemes' , ' f al se' ) ;
END;
/

- - 2) cr eat e Wor dl i st
BEGI N
ct x_ddl . cr eat e_pr ef er ence ( ' l ob_wor dl i st ' , ' basi c_wor dl i st ' ) ;
ct x_ddl . set _at t r i but e ( ' l ob_wor dl i st ' , ' subst r i ng_i ndex' , ' t r ue' ) ;
END;
/

- - 3) Cr eat e t he i ndex on t he col umn
- - r ol e ct xapp and r esour ce must be gr ant ed f i r st
- - STOPLI ST r ef er s t o noi se wor ds. I t can al so t ake DEFAULT_STOPLI ST
CREATE I NDEX l ob_i ndx ON book_sampl es( descr i pt i on)
I NDEXTYPE I S CTXSYS. CONTEXT
PARAMETERS ( ' l exer l ob_l exer
wor dl i st l ob_wor dl i st
st opl i st ct xsys. empt y_st opl i st ' )
/


To exami ne t he t okens:
Page 664 Oracle DBA Code Examples

set pages 9999
SELECT t oken_t ext FROM DR$LOB_I NDX$I ;


/ * Usi ng t he I ndex */
SELECT SCORE( 1) , book_sampl e_i d
FROM book_sampl es
WHERE CONTAI NS( descr i pt i on, ' websi t e' , 1) > 0;
Migrating from LONGs to LOBs
ALTER TABLE l ong_t o_l ob MODI FY t ext CLOB;
Page 665 Oracle DBA Code Examples

PL/SQL Performance Tuning Tips
Use PL/SQL Profiler
It is DBMS_HPROF in 11g and DBMS_PROFILER in 10g.
Provides performance statistical information on an executed procedure.
/ * Requi r ed Pr i vs */
GRANT EXECUTE ON dbms_hpr of TO sa;
CREATE OR REPLACE DI RECTORY pr of i l er _di r AS ' / home/ or acl e/ t emp' ;
GRANT READ, WRI TE ON DI RECTORY pr of i l er _di r TO sa;



/ * Package Tabl es */
conn sa/ s
@?/ r dbms/ admi n/ dbmshpt ab. sql



/ * Usi ng t he package */
BEGI N
DBMS_HPROF. st ar t _pr of i l i ng (
l ocat i on => ' PROFI LER_DI R' ,
f i l ename => ' pr of i l er . t xt ' ) ;
- - cal l t he pr ocedur e t o pr of i l e
PROC3;
DBMS_HPROF. st op_pr of i l i ng;
END;
/


- - r un t he ANALYZE f unct i on t o anal yse t he
- - r aw dat a and f i l l t he Pr of i l er t abl es
SET SERVEROUTPUT ON
DECLARE
l _r uni d NUMBER;
BEGI N
l _r uni d : = DBMS_HPROF. anal yze (
l ocat i on => ' PROFI LER_DI R' ,
f i l ename => ' pr of i l er . t xt ' ,
r un_comment => ' Test r un. ' ) ;
DBMS_OUTPUT. put _l i ne( ' l _r uni d=' | | l _r uni d) ;
END;
/

l _r uni d=1


- - check t he i nf o:
SELECT r uni d, r un_t i mest amp, t ot al _el apsed_t i me, r un_comment
FROM dbmshp_r uns
WHERE r uni d=1;


Page 666 Oracle DBA Code Examples

- - t o l i st t he pr of i l i ng i nf o:
SELECT symbol i d, owner , modul e, t ype, f unct i on
FROM dbmshp_f unct i on_i nf o
WHERE r uni d = 1
ORDER BY symbol i d;


- - t o l i st t he pr of i l i ng i nf o i n hi er ar chy:
SELECT RPAD( ' ' , l evel *2, ' ' ) | | f i . owner | | ' . ' | | f i . modul e AS name,
f i . f unct i on,
pci . subt r ee_el apsed_t i me,
pci . f unct i on_el apsed_t i me,
pci . cal l s
FROM dbmshp_par ent _chi l d_i nf o pci
J OI N dbmshp_f unct i on_i nf o f i ON pci . r uni d = f i . r uni d AND
pci . chi l dsymi d = f i . symbol i d
WHERE pci . r uni d = 1
CONNECT BY PRI OR chi l dsymi d = par ent symi d
START WI TH pci . par ent symi d = 3;



/ * Usi ng pl shpr of Ut i l i t y */
- - pr of i l er . t xt gener at ed by t he package
pl shpr of - out put pl shpr of _out pr of i l er . t xt
Use BULK COLLECT Clause
More efficient than traditional loop through curoser records
/* loading ALL the returned recordset into one PL/SQL tables */
- - i f t he r et ur ned r ows ar e mor e t han 200000, make t he r ows
- - be r et ur ned i nt o bat ches usi ng LI MI T cl ause
DECLARE
- - Def i ne col l ect i on t ype and var i abl es t o be used by t he
- - BULK COLLECT cl ause
TYPE st udent _i d_t ype I S TABLE OF st udent . st udent _i d%TYPE;
TYPE f i r st _name_t ype I S TABLE OF st udent . f i r st _name%TYPE;
TYPE l ast _name_t ype I S TABLE OF st udent . l ast _name%TYPE;
st udent _i d_t ab st udent _i d_t ype;
f i r st _name_t ab f i r st _name_t ype;
l ast _name_t ab l ast _name_t ype;
BEGI N

- - Fet ch al l st udent dat a at once vi a BULK COLLECT cl ause
SELECT st udent _i d, f i r st _name, l ast _name
BULK COLLECT INTO st udent _i d_t ab, f i r st _name_t ab, l ast _name_t ab
FROM st udent ;
FOR i I N st udent _i d_t ab. FI RST. . st udent _i d_t ab. LAST

LOOP
DBMS_OUTPUT. PUT_LI NE ( ' st udent _i d: ' | | st udent _i d_t ab( i ) ) ;
DBMS_OUTPUT. PUT_LI NE ( ' f i r st _name: ' | | f i r st _name_t ab( i ) ) ;
DBMS_OUTPUT. PUT_LI NE ( ' l ast _name: ' | | l ast _name_t ab( i ) ) ;
END LOOP;

Page 667 Oracle DBA Code Examples

END;



/* Using the limit Option */
-- Note: l i mi t opt i on cannot be used di r ect l y wi t h SELECT st at emnet . Onl y on
- - cur sor s
- - bat ches ar e good f or bet t er per f or mance when
- - t he r et ur ned r owset i s ver y l ar ge ( r oughl y >500000)
DECLARE
- - t o be used by t he LI MI T ( bat ch si ze)
v_l i mi t PLS_I NTEGER : = 50;

CURSOR st udent _cur I S
SELECT st udent _i d, f i r st _name, l ast _name
FROM st udent ;

- - Def i ne col l ect i on t ype and var i abl es t o be used by t he
- - BULK COLLECT cl ause
TYPE st udent _i d_t ype I S TABLE OF st udent . st udent _i d%TYPE;
TYPE f i r st _name_t ype I S TABLE OF st udent . f i r st _name%TYPE;
TYPE l ast _name_t ype I S TABLE OF st udent . l ast _name%TYPE;

st udent _i d_t ab st udent _i d_t ype;
f i r st _name_t ab f i r st _name_t ype;
l ast _name_t ab l ast _name_t ype;

BEGI N
OPEN st udent _cur ;
LOOP
- - Fet ch 50 r ows at once
FETCH st udent _cur
BULK COLLECT I NTO st udent _i d_t ab, f i r st _name_t ab, l ast _name_t ab
LI MI T v_l i mi t ;

- - exi t i s based on t he t he number of r ecor ds i n t he col l ect i on
EXI T WHEN st udent _i d_t ab. COUNT = 0;

- - i t i s wr ong t o put i t af t er t he out er l oop
FOR i I N st udent _i d_t ab. FI RST. . st udent _i d_t ab. LAST
LOOP
DBMS_OUTPUT. PUT_LI NE ( ' st udent _i d: ' | | st udent _i d_t ab( i ) ) ;
DBMS_OUTPUT. PUT_LI NE ( ' f i r st _name: ' | | f i r st _name_t ab( i ) ) ;
DBMS_OUTPUT. PUT_LI NE ( ' l ast _name: ' | | l ast _name_t ab( i ) ) ;
END LOOP;
END LOOP;
CLOSE st udent _cur ;
END;


/* Loading into PL/SQL Multiple-Column Table */
- - good when t her e ar e so many col s t o r ead
- - Exampl e 1
DECLARE
CURSOR st udent _cur I S
SELECT st udent _i d, f i r st _name, l ast _name
FROM st udent ;
Page 668 Oracle DBA Code Examples


- - Def i ne r ecor d t ype
TYPE st udent _r ec I S RECORD
( st udent _i d st udent . st udent _i d%TYPE,
f i r st _name st udent . f i r st _name%TYPE,
l ast _name st udent . l ast _name%TYPE) ;
- - Def i ne col l ect i on t ype
TYPE st udent _t ype I S TABLE OF st udent _r ec;
- - Def i ne col l ect i on var i abl e
st udent _t ab st udent _t ype;
- - t o be used by t he LI MI T cl ause
v_l i mi t PLS_I NTEGER : = 50;

BEGI N
OPEN st udent _cur ;
LOOP
- - Fet ch 50 r ows at once
FETCH st udent _cur BULK COLLECT I NTO st udent _t ab LI MI T v_l i mi t ;
EXI T WHEN st udent _t ab. COUNT = 0;

FOR i I N st udent _t ab. FI RST. . st udent _t ab. LAST
LOOP
DBMS_OUTPUT. PUT_LI NE( ' st udent _i d: ' | | st udent _t ab( i ) . st udent _i d) ;
DBMS_OUTPUT. PUT_LI NE( ' f i r st _name: ' | | st udent _t ab( i ) . f i r st _name) ;
DBMS_OUTPUT. PUT_LI NE( ' l ast _name: ' | | st udent _t ab( i ) . l ast _name) ;
END LOOP;
END LOOP;
CLOSE st udent _cur ;
END;


- - Exampl e 2:
DECLARE
V_LI MI T PLS_I NTEGER : =50;
TYPE ORDERS_TYPE I S TABLE OF ORDERS%ROWTYPE;
ORDERS_TB ORDERS_TYPE;
CURSOR ORDERS_CRS I S SELECT * FROM ORDERS;
BEGI N
OPEN ORDERS_CRS;
LOOP
- - l oad 500 at once
FETCH ORDERS_CRS BULK COLLECT I NTO ORDERS_TB LI MI T V_LI MI T;

- - exi t when t he col l ect i on i s empt y
EXI T WHEN ORDERS_TB. COUNT=0;

- - pr ocess t he bat ch
FOR I I N ORDERS_TB. FI RST . . ORDERS_TB. LAST LOOP
NULL;
END LOOP;
END LOOP;
CLOSE ORDERS_CRS;
END;
/



Page 669 Oracle DBA Code Examples

/* Using BULK COLLECT with the DELETE */
DECLARE
- - Def i ne col l ect i on t ypes and var i abl es
TYPE r ow_num_t ype I S TABLE OF NUMBER I NDEX BY PLS_I NTEGER;
TYPE r ow_t ext _t ype I S TABLE OF VARCHAR2( 10) I NDEX BY PLS_I NTEGER;
r ow_num_t ab r ow_num_t ype;
r ow_t ext _t ab r ow_t ext _t ype;
BEGI N
DELETE FROM TEST
RETURNI NG r ow_num, r ow_t ext
BULK COLLECT I NTO r ow_num_t ab, r ow_t ext _t ab;

DBMS_OUTPUT. PUT_LI NE ( ' Del et ed ' | | SQL%ROWCOUNT | | ' r ows: ' ) ;

FOR i I N r ow_num_t ab. FI RST. . r ow_num_t ab. LAST
LOOP
DBMS_OUTPUT. PUT_LI NE ( ' r ow_num= ' | | r ow_num_t ab( i ) | |
' r ow_t ext = ' | | r ow_t ext _t ab( i ) ) ;
END LOOP;
COMMI T;
END;


Out put may l ook l i ke:
Del et ed 4 r ows:
r ow_num= 3 r ow_t ext = r ow 3
r ow_num= 4 r ow_t ext = r ow 4
r ow_num= 6 r ow_t ext = r ow 6
r ow_num= 8 r ow_t ext = r ow 8



/* Using BULK COLLECT with FORALL */
- - Exampl e 1: wi t h I nser t
DECLARE
- - Decl ar e col l ect i on t ypes
TYPE st r i ng_t ype I S TABLE OF VARCHAR2( 100) I NDEX BY PLS_I NTEGER;
TYPE dat e_t ype I S TABLE OF DATE I NDEX BY PLS_I NTEGER;

- - Decl ar e col l ect i on var i abl es t o be used by t he FORALL st at ement
zi p_t ab st r i ng_t ype;
ci t y_t ab st r i ng_t ype;
st at e_t ab st r i ng_t ype;
cr _by_t ab st r i ng_t ype;
cr _dat e_t ab dat e_t ype;
mod_by_t ab st r i ng_t ype;
mod_dat e_t ab dat e_t ype;

v_count er PLS_I NTEGER : = 0;
v_t ot al I NTEGER : = 0;
BEGI N
- - Popul at e i ndi vi dual col l ect i ons
SELECT *
BULK COLLECT I NTO zi p_t ab, ci t y_t ab, st at e_t ab, cr _by_t ab,
cr _dat e_t ab, mod_by_t ab, mod_dat e_t ab
FROM zi pcode
WHERE st at e = ' CT' ;
Page 670 Oracle DBA Code Examples


- - Popul at e MY_ZI PCODE t abl e
FORALL i i n 1. . zi p_t ab. COUNT
I NSERT I NTO my_zi pcode
( zi p, ci t y, st at e, cr eat ed_by, cr eat ed_dat e, modi f i ed_by,
modi f i ed_dat e)
VALUES
( zi p_t ab( i ) , ci t y_t ab( i ) , st at e_t ab( i ) , cr _by_t ab( i ) ,
cr _dat e_t ab( i ) , mod_by_t ab( i ) , mod_dat e_t ab( i ) ) ;
COMMI T;

- - Check how many r ecor ds wer e added t o MY_ZI PCODE t abl e
SELECT COUNT( *)
I NTO v_t ot al
FROM my_zi pcode
WHERE st at e = ' CT' ;

DBMS_OUTPUT. PUT_LI NE( v_t ot al | | ' r ecor ds wer e added t o MY_ZI PCODE t abl e' ) ;
END;


- - Exampl e 2: wi t h DELETE
SET SERVEROUTPUT ON
DECLARE
TYPE or der _i d_t ype I S TABLE OF or der s. or der _i d%TYPE;

oi _i n_t b or der _i d_t ype ;
oi _out _t b or der _i d_t ype ;
BEGI N
- - Popul at e col l ect i on use i n f or al l .
SELECT or der _i d
BULK COLLECT I NTO oi _i n_t b
FROM or der s
WHERE or der _i d bet ween 335332 and 335341;

FORALL i I N oi _i n_t b. f i r st . . oi _i n_t b. l ast
DELETE FROM or der s
WHERE or der _i d = oi _i n_t b( i )
RETURNI NG or der _i d BULK COLLECT I NTO oi _out _t b;

DBMS_OUTPUT. put _l i ne( ' Del et ed I Ds : ' | | oi _out _t b. count | | ' r ows' ) ;

ROLLBACK;
END;
Set PLSQL_OPTIMIZE_LEVEL and Subprogram Inlining
The parameter controls level of optimization performed by PL/SQL compiler. It ranges
from 0 (no optimization) to 3 (3 in 11g). Thed default (2) is generally acceptable.
The pragma INLINE compiler directive specifies that a subprogram call is, or is not, to be
inlined. It must appear immediately before the subprogram call.
SET SERVEROUTPUT ON
DECLARE

v_numPLS_I NTEGER : = 1;
Page 671 Oracle DBA Code Examples

v_r esul t PLS_I NTEGER;

- - Fol l owi ng ar e used f or el apsed t i me cal cul at i on
v_st ar t _t i me NUMBER;
v_end_t i me NUMBER;

- - Def i ne si mpl e f unct i on t o t est PRAGMA I NLI NE
FUNCTI ON t est _i nl i ne_pr agma
( i n_num1 I N PLS_I NTEGER, i n_num2 I N PLS_I NTEGER)
RETURN PLS_I NTEGER
I S
BEGI N
RETURN ( i n_num1 + i n_num2) ;
END t est _i nl i ne_pr agma;
BEGI N

- - Test f unct i on wi t h I NLI NE PRAGMA enabl ed
v_st ar t _t i me : = DBMS_UTI LI TY. GET_TI ME;
FOR i i n 1. . 10000000 LOOP
PRAGMA INLINE (test_inline_pragma, 'YES');
v_r esul t : = t est _i nl i ne_pr agma ( 1, i ) ;
END LOOP;
v_end_t i me : = DBMS_UTI LI TY. GET_TI ME;
DBMS_OUTPUT. PUT_LI NE ( ' El apsed t i me when PRAGMA I NLI NE enabl ed: ' | |
( v_end_t i me- v_st ar t _t i me) ) ;

- - Test f unct i on wi t h PRAGMA I NLI NE di sabl ed
v_st ar t _t i me : = DBMS_UTI LI TY. GET_TI ME;
FOR i i n 1. . 10000000 LOOP
PRAGMA INLINE (test_inline_pragma, 'NO');
v_r esul t : = t est _i nl i ne_pr agma ( 1, i ) ;
END LOOP;
v_end_t i me : = DBMS_UTI LI TY. GET_TI ME;
DBMS_OUTPUT. PUT_LI NE ( ' El apsed t i me when I NLI NE PRAGMA di sabl ed: ' | |
( v_end_t i me- v_st ar t _t i me) ) ;
END;


- - out put of t he code above:
El apsed t i me when PRAGMA I NLI NE enabl ed: 46
El apsed t i me when I NLI NE PRAGMA di sabl ed: 147

PL/ SQL pr ocedur e successf ul l y compl et ed.
Using Bind variables in Dynamic SQL
Using bind variables allows sharable SQL, reduces parse overhead and minimizes latch
contention.
- - l ess per f or mance exampl e:
EXECUTE I MMEDI ATE ' SELECT COUNT( *) FROM ' | | p_myt abl e | | ' WHERE ' | |
p_col umn | | ' =' | | p_val ue I NTO v_count

- - mor e ef f i ci ent
EXECUTE I MMEDI ATE ' SELECT COUNT( *) FROM ' | | p_myt abl e | | ' WHERE ' | |
p_col umn | | ' = : 1' I NTO v_count USI NG p_val ue
Page 672 Oracle DBA Code Examples

Use NOCOPY Keyword
The NOCOPY clause causes a parameter to be passed by reference rather than by
value. Use it, if possible, when the parameter is of a collection datatype.
FUNCTI ON myf unc (
p_i nput _t abl e I N OUT NOCOPY number _t ab_t ype,
p_r ow NUMBER, . . .
Use Associative arrays
Associative arrays profives faster and simpler lookup than other collections.
For further examples, see Using Associative arrays.
TYPE cust s_t ype I S TABLE OF NUMBER I NDEX BY VARCHAR2( 1000) ;
- - t he f ol l owi ng ar r ay shoul d be l oaded by some code
g_cust s cust s_t ype;

Funct i on get _cust _i d ( p_cust _name VARCHAR2)
RETURN NUMBER
I S
v_cust _i d sh. cust omer s. cust _i d%t ype;
BEGI N
- - si mpl e and f ast l ookup ( no l oops r equi r ed)
v_cust _i d : = g_cust s( p_cust _name) ;
RETURN ( v_cust _i d) ;
END;
Use Server Result Cache
It suits deterministic but expensive functions, such as expensive table lookups on non-
volatile tables.
For details, see Using Server Result Cache.
Page 673 Oracle DBA Code Examples

PL/SQL Miscellaneous Topics
Accessing V$ Views from PL/SQL
gr ant sel ect on V_$SESSI ON t o <user name> ;
gr ant sel ect on V_$PROCESS t o <user name>;

- - f ol l owi ng wi l l NOT wor k:
GRANT SELECT_CATALOG_ROLE TO <user name>;
GRANT SELECT_CATALOG_ROLE TO <user name>;

- - connect as <user name>
cr eat e pr ocedur e . .
sel ect . . f r omsys.V_$PROCESS p, sys.V_$SESSION s . .

Page 674 Oracle DBA Code Examples

Part 13 Appendixes
Page 675 Oracle DBA Code Examples

Program Units and Scripts Used in the Document
Return Parameter Value for Normal User
Used by normal user who do not have access on v$parameter.
CREATE OR REPLACE FUNCTI ON GET_PAR ( P_PARAMETER VARCHAR2)
RETURN VARCHAR2
I S
par namVARCHAR2( 256) ;
i nt val BI NARY_I NTEGER;
st r val VARCHAR2( 256) ;
par t ype BI NARY_I NTEGER;
V VARCHAR2( 1000) ;
BEGI N
par t ype : = dbms_ut i l i t y. get _par amet er _val ue( P_PARAMETER, i nt val , st r val ) ;
I F par t ype = 1 THEN
RETURN ' TYPE: STRI NG - Val ue: ' | | STRVAL;
ELSE
RETURN ' TYPE: I NTEGER - Val ue: ' | | TO_CHAR( i nt val ) ;
END I F;
END;
/

Page 676 Oracle DBA Code Examples

Applying Random Load on Database Sample 1
Scripts to apply loads on Oracle DB on a single table. Applicable on Unix and Windows.
Setup
Database Side
/ * Cr eat e Schema cot ai ni ng t ar get obj ect s */
cr eat e t abl espace hr st bs ;
cr eat e user hr s i dent i f i ed by h
def aul t t abl espace hr st bs
quot a unl i mi t ed on hr st bs ;
gr ant cr eat e t abl e, cr eat e vi ew, cr eat e pr ocedur e, cr eat e sessi on, cr eat e
sequence, pl ust r ace t o hr s;
gr ant execut e on DBMS_LOCK t o hr s;
gr ant execut e on DBMS_RANDOM t o hr s;


/ * Cr eat e Schema Obj ect s */
conn hr s/ h
CREATE TABLE NAMES
( I D NUMBER , NAME VARCHAR2( 50) , HDATE DATE, SAL NUMBER, REGI ON VARCHAR2( 1) ) ;

CREATE SEQUENCE S cache 1000;

/ * Cr eat e RandomLoad Package */
- - Gener at es var i ous di f f er ent l oads on t he t ar get dat abase
CREATE OR REPLACE PACKAGE LOAD_GENERATOR
I S
- - i nser t bat ch r ows i nt o NAMES t abl e
PROCEDURE I NSERT_NAMES ( P_ROWS I N NUMBER) ;
- - hi gh CPU cal l s
PROCEDURE Spi nCPUs( P_I TERATI ON I N NUMBER) ;
- - hi gh CPU+DB cal l s
PROCEDURE Spi nCycl es ( P_I TERATI ON I N NUMBER) ;
- - r andomquer y: f r omNAMES
PROCEDURE RandomQuer y( P_I TERATI ON I N NUMBER, P_MAX I N NUMBER) ;
- - r andomDML on NAMES
PROCEDURE RandomDML( P_I TERATI ON I N NUMBER, P_MAX I N NUMBER) ;
END l oad_gener at or ;
/

- - unmar k t he SLEEP f unct i on, i f you wi sh
CREATE OR REPLACE PACKAGE Body LOAD_GENERATOR
I S
- - gener at e r andomt ext : i t s l engnt h bet ween 4 and t he passed val ue
FUNCTI ON G_TEXT( P_SI ZE I N NUMBER) RETURN VARCHAR2
I S
V VARCHAR2( 2000) ;
BEGI N
FOR I I N 1. . DBMS_RANDOM. VALUE( 4, P_SI ZE) LOOP
V : = V | | CHR( ROUND( DBMS_RANDOM. VALUE( 65, 90) ) ) ; - - 122
END LOOP;
RETURN V;
END;
Page 677 Oracle DBA Code Examples


PROCEDURE I NSERT_NAMES ( P_ROWS I N NUMBER)
I S
V1 VARCHAR2( 15) ;
V2 VARCHAR2( 15) ;
BEGI N
FOR I I N 1. . P_ROWS LOOP
V1 : = G_TEXT( 15) ;
V2 : = G_TEXT( 15) ;
I NSERT I NTO NAMES VALUES ( S. NEXTVAL, - - I D
V1 | | ' ' | | V2, - - NAME
TRUNC( SYSDATE- DBMS_RANDOM. VALUE( 60, 1800) ) , - - HDATE
ROUND( DBMS_RANDOM. VALUE( 1000, 55000) ) , - - SAL
DECODE( TO_CHAR( ROUND( DBMS_RANDOM. VALUE( 1, 4) ) ) ,
' 1' , ' N' , ' 2' , ' W' , ' 3' , ' E' , ' 4' , ' S' ) ) ; - - REGI ON
I F MOD( I , 100) = 0 THEN
COMMI T;
END I F;
END LOOP;
COMMI T;
END I NSERT_NAMES;

PROCEDURE Spi nCPUs ( P_I TERATI ON I N NUMBER)
I S
N NUMBER;
BEGI N
FOR I I N 1. . P_I TERATI ON LOOP
- - pur e CPU pr ocessi ng ( no physi cal or l ogi cal r ead)
N : = SQRT( ROUND( DBMS_RANDOM. VALUE( 1, 1000) ) ) ;
- - DBMS_LOCK. SLEEP( r ound( DBMS_RANDOM. VALUE( 0. 01, 0. 05) , 2) ) ; - - i n seconds
END LOOP;
END Spi nCPUs;

PROCEDURE Spi nCycl es ( P_I TERATI ON I N NUMBER)
I S
N NUMBER;
BEGI N
FOR I I N 1. . P_I TERATI ON LOOP
FOR X I N 1. . ROUND( DBMS_RANDOM. VALUE( 1, 10) ) LOOP
N : = SQRT( ROUND( DBMS_RANDOM. VALUE( 1, 1000) ) ) ;
END LOOP;
SELECT COUNT( *) I NTO N FROM NAMES;
- - DBMS_LOCK. SLEEP( ROUND( DBMS_RANDOM. VALUE( 0. 01, 1) , 2) ) ; - - i n seconds
END LOOP;
END Spi nCycl es;

PROCEDURE RandomQuer y( P_I TERATI ON I N NUMBER, P_MAX I N NUMBER)
I S
V_START NUMBER;
V_END NUMBER;
N NUMBER;
BEGI N
V_END : = P_MAX;
V_START : = ROUND( DBMS_RANDOM. VALUE( 1, V_END) ) ;
FOR I I N 1. . P_I TERATI ON LOOP
SELECT COUNT( I D) I NTO N FROM NAMES
WHERE I D BETWEEN V_START AND V_END;
Page 678 Oracle DBA Code Examples

- - DBMS_LOCK. SLEEP( ROUND( DBMS_RANDOM. VALUE( 0. 01, 3) , 2) ) ;
END LOOP;
END RandomQuer y;

PROCEDURE RandomDML( P_I TERATI ON I N NUMBER, P_MAX I N NUMBER)
I S
N NUMBER;
M NUMBER;
V_NEW_SAL NUMBER;
V1 VARCHAR2( 15) ;
V2 VARCHAR2( 15) ;
BEGI N
FOR I I N 1. . P_I TERATI ON LOOP
N : = ROUND( DBMS_RANDOM. VALUE( 1, 3) ) ;
I F N=1 THEN
V1 : = G_TEXT( 15) ;
V2 : = G_TEXT( 15) ;
I NSERT I NTO NAMES VALUES ( S. NEXTVAL, - - I D
V1 | | ' ' | | V2, - - NAME
TRUNC( SYSDATE) - DBMS_RANDOM. VALUE( 60, 1800) , - - HDATE
ROUND( DBMS_RANDOM. VALUE( 1000, 55000) ) , - - SAL
DECODE( TO_CHAR( ROUND( DBMS_RANDOM. VALUE( 1, 4) ) ) ,
' 1' , ' N' , ' 2' , ' W' , ' 3' , ' E' , ' 4' , ' S' ) ) ; - - REGI ON
ELSI F N=2 THEN
M : = ROUND( DBMS_RANDOM. VALUE( 1, P_MAX) ) ;
V_NEW_SAL : = ROUND( DBMS_RANDOM. VALUE( 1000, 55000) ) ;
UPDATE NAMES SET SAL = V_NEW_SAL
WHERE I D = M;
ELSI F N=3 THEN
M : = ROUND( DBMS_RANDOM. VALUE( 1, P_MAX) ) ;
DELETE NAMES WHERE I D = M;
END I F;
- - DBMS_LOCK. SLEEP( ROUND( DBMS_RANDOM. VALUE( 0. 1, 2) , 2) ) ;
COMMI T;
END LOOP;
END RandomDML;
END l oad_gener at or ;
/


- - l oad some r ows i n names t abl e
execut e l oad_gener at or . i nser t _names( 10000) ;
OS side: Unix
- - i n a f ol der cr eat e t he f ol l owi ng scr i pt s
- - ( 1) l oadcpu1. sh
#! / bi n/ bash
# appl y CPU l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons
user s=$1
SRVC=" hr ser v"
UNPW=" hr s/ h"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oadcpu1. sql "
x=1
y=$user s
I TER=$2

Page 679 Oracle DBA Code Examples

whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER &
x=`expr $x + 1`
done

- - ( 2) l oadcpu1. sql
begi n
hr s. LOAD_GENERATOR. Spi nCPUs( &1) ;
end;
/
exi t

- - ( 3) l oadcpu2. sh
#! / bi n/ bash
# appl y CPU+DB Cal l s l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons
user s=$1
SRVC=" hr ser v"
UNPW=" hr s/ h"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oadcpu2. sql "
x=1
y=$user s
I TER=$2

whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER &
x=`expr $x + 1`
done

- - ( 4) l oadcpu2. sql
begi n
hr s. LOAD_GENERATOR. Spi nCycl es( &1) ;
end;
/
exi t

- - ( 5) l oadquer y. sh
#! / bi n/ bash
# appl y r andomquer i es l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names
user s=$1
SRVC=" hr ser v"
UNPW=" hr s/ h"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oadquer y. sql "
x=1
y=$user s
I TER=$2
MAX=$3

whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER $MAX &
x=`expr $x + 1`
done

Page 680 Oracle DBA Code Examples

- - ( 6) l oadquer y. sql
begi n
hr s. LOAD_GENERATOR. RANDOMQUERY ( &1, &2) ;
end;
/
exi t

- - ( 7) l oaddml . sh
#! / bi n/ bash
# appl y r andomDML l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names
user s=$1
SRVC=" hr ser v"
UNPW=" hr s/ h"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oaddml . sql "
x=1
y=$user s
I TER=$2
MAX=$3

whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER $MAX &
x=`expr $x + 1`
done

- - ( 8) l oaddml . sql
begi n
hr s. LOAD_GENERATOR. RANDOMDML ( &1, &2) ;
end;
/
exi t
OS side: Windows
- - i n a f ol der cr eat e t he f ol l owi ng scr i pt s
- - ( 1) l oadcpu1. bat
REM appl y CPU l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons

set user s=%1
set SRVC=hr ser v
set UNPW=hr s/ h
set SQLCMD=C: \ TEMP\ l oad\ l oadcpu1. sql
set x=1
set y=%user s%
set I TER=%2

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%)



- - ( 2) l oadcpu1. sql
begi n
hr s. LOAD_GENERATOR. Spi nCPUs( &1) ;
end;
/
Page 681 Oracle DBA Code Examples

exi t


- - ( 3) l oadcpu2. bat
REM appl y CPU+DB Cal l s l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons

set user s=%1
set SRVC=hr ser v
set UNPW=hr s/ h
set SQLCMD=C: \ TEMP\ l oad\ l oadcpu2. sql
set x=1
set y=%user s%
set I TER=%2

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%)


- - ( 4) l oadcpu2. sql
begi n
hr s. LOAD_GENERATOR. Spi nCycl es( &1) ;
end;
/
exi t



- - ( 5) l oadquer y. bat
REM appl y r andomquer i es l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names

set user s=%1
set SRVC=hr ser v
set UNPW=hr s/ h
set SQLCMD=C: \ TEMP\ l oad\ l oadquer y. sql
set x=1
set y=%user s%
set I TER=%2
set MAX=%3

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%%MAX%)

- - ( 6) l oadquer y. sql
begi n
hr s. LOAD_GENERATOR. RANDOMQUERY ( &1, &2) ;
end;
/
exi t


- - ( 7) l oaddml . bat
REM appl y r andomDML l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names
set user s=%1
set SRVC=hr ser v
Page 682 Oracle DBA Code Examples

set UNPW=hr s/ h
set SQLCMD=C: \ TEMP\ l oad\ l oaddml . sql
set x=1
set y=%user s%
set I TER=%2
set MAX=%3

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%%MAX%)


- - ( 8) l oaddml . sql
begi n
hr s. LOAD_GENERATOR. RANDOMDML ( &1, &2) ;
end;
/
exi t
Using the Load Generator Scripts
/ * i n Uni x and Wi ndows */
## Usi ng t he Load Gener at or #
# 5 connect i ons 1000 i t er at i ons 100000 number of r ows i n NAMES t abl e
l oadcpu1 5 1000
l oaddml 5 1000 100000

Page 683 Oracle DBA Code Examples

Applying Random Load on Database Sample 2
Scripts to apply loads on Oracle DB on a schema named as SA. Tables in this schema
taken from the default Oracle OE schema. Applicable on Unix and Windows. Following is
the ERD of the SA schema:

Setup
Database Side
/ * Cr eat e sa Schema ( i f not al r eady t her e) */
cr eat e t abl espace sat bs
dat af i l e ' C: \ ORACLE\ ORADATA\ ORA11G\ sat bs1. dbf ' si ze 100m
aut oext end on next 12mmaxsi ze 4g
ext ent management l ocal
segment space management aut o ;

- - i f ASM i s used:
CREATE TABLESPACE sat bs DATAFI LE ' +DATA' si ze 50m
aut oext end on next 12mmaxsi ze 1g;

cr eat e user sa i dent i f i ed by s
def aul t t abl espace sat bs
quot a unl i mi t ed on sat bs ;
gr ant cr eat e t abl e, cr eat e vi ew, cr eat e pr ocedur e, cr eat e sessi on, cr eat e
sequence t o sa;
gr ant execut e on DBMS_LOCK t o sa;
gr ant execut e on DBMS_RANDOM t o sa;
gr ant SELECT_CATALOG_ROLE t O sa;
gr ant al t er sessi on t o sa;
gr ant cr eat e r ol e t o sa;

Page 684 Oracle DBA Code Examples


gr ant pl ust r ace t o sa;
- - i f r ol e doesn' t exi st
@C: \ or acl e\ pr oduct \ 11. 1. 0\ db_1\ RDBMS\ ADMI N\ ut l xpl an. sql
@C: \ or acl e\ pr oduct \ 11. 1. 0\ db_1\ sql pl us\ admi n\ pl ust r ce. sql
# i n uni x:
@/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ r dbms/ admi n/ ut l xpl an. sql
@/ u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1/ sql pl us/ admi n/ pl ust r ce. sql


/ * Cr eat e Schema Obj ect s */
conn sa/ s
- - execut e code i n:
@ht t p: / / www. ahmedbar aka. com/ or acl e/ scr i pt s/ popul at esa. sql


- - t he package
/ * Cr eat e RandomLoad Package */
- - Gener at es var i ous di f f er ent l oads on t he t ar get dat abase
CREATE OR REPLACE PACKAGE sa. LOAD_GENERATOR
I S
- - gl obal var s
G_MAX_ORDER_I D NUMBER;
G_MI N_ORDER_I D NUMBER;

- - i ni t i al i ze t he package
PROCEDURE I NI TI ALI ZE;

- - i nser t bat ch r ows i nt o NAMES t abl e
PROCEDURE I NSERT_ORDERS ( P_ROWS I N NUMBER, P_DAYS I N NUMBER DEFAULT 30 ) ;

- - hi gh CPU cal l s
PROCEDURE Spi nCPUs( P_I TERATI ON I N NUMBER) ;

- - r andomquer y: f r omORDERS
PROCEDURE RandomQuer y( P_I TERATI ON I N NUMBER) ;

- - r andomDML on NAMES
PROCEDURE RandomDML( P_I TERATI ON I N NUMBER) ;
END l oad_gener at or ;
/


CREATE OR REPLACE PACKAGE Body sa. LOAD_GENERATOR
I S
PROCEDURE I NI TI ALI ZE
I S
BEGI N
SELECT MAX( ORDER_I D) , MI N( ORDER_I D) I NTO G_MAX_ORDER_I D, G_MI N_ORDER_I D
FROM ORDERS;
END I NI TI ALI ZE;
PROCEDURE I NSERT_ORDERS ( P_ROWS I N NUMBER, P_DAYS I N NUMBER DEFAULT 30 )
I S
V_ORDER_I D NUMBER;
V_ORDER_DATE DATE;
V_ORDER_MODE VARCHAR2( 8) ;
V_CUSTOMER_I D NUMBER;
Page 685 Oracle DBA Code Examples

V_ORDER_STATUS NUMBER;
V_SALES_REP_I D NUMBER;
V_PRODUCT_I D NUMBER;
V_PROD_PRI CE NUMBER;
V_CHANGE_PRI CE NUMBER;
V_QUANTI TY NUMBER;
V_ORDER_TOTAL NUMBER;
V_I TEMS_COUNT NUMBER;
N NUMBER;
M NUMBER;
- - 97 cust omer s
TYPE CUST_I D_TYPE I S VARRAY( 100) OF I NTEGER;
V_CUST_I DS CUST_I D_TYPE : = CUST_I D_TYPE
( 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 360, 361, 363, 378, 380, 447, 448, 4
49, 450, 451, 452, 453, 454, 458, 463, 466, 467, 468, 470, 473, 474, 475, 476, 477, 478, 479, 480
, 481, 482, 483, 487, 488, 492, 496, 605, 606, 607, 609, 615, 621, 627, 712, 713, 715, 717, 719, 7
21, 727, 729, 731, 754, 755, 756, 757, 766, 767, 768, 769, 770, 771, 772, 782, 825, 826, 827, 828
, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847) ;
- - 275 PRODUCTS
TYPE PROD_I D_TYPE I S VARRAY( 275) OF I NTEGER;
V_PROD_I DS PROD_I D_TYPE : = PROD_I D_TYPE
( 1750, 1755, 1761, 1763, 1768, 1769, 1770, 1772, 1774, 1775, 1778, 1779, 1780, 1781, 1782, 17
87, 1788, 1791, 1792, 1794, 1797, 1799, 1801, 1803, 1804, 1805, 1806, 1808, 1820, 1822, 1825,
1910, 1912, 1940, 1948, 2004, 2005, 2030, 2049, 2056, 2058, 2091, 2093, 2144, 2152, 2211, 223
1, 2236, 2243, 2245, 2252, 2253, 2254, 2255, 2257, 2259, 2260, 2261, 2262, 2264, 2266, 2268, 2
270, 2272, 2274, 2276, 2278, 2289, 2293, 2299, 2302, 2308, 2311, 2316, 2319, 2322, 2323, 2326
, 2330, 2334, 2335, 2336, 2337, 2339, 2340, 2350, 2351, 2359, 2365, 2370, 2371, 2373, 2374, 23
75, 2377, 2378, 2380, 2381, 2382, 2384, 2387, 2394, 2395, 2396, 2400, 2402, 2403, 2404, 2406,
2408, 2409, 2410, 2411, 2412, 2414, 2415, 2416, 2417, 2418, 2419, 2422, 2423, 2424, 2430, 243
9, 2449, 2452, 2453, 2457, 2459, 2462, 2464, 2467, 2468, 2470, 2471, 2492, 2493, 2494, 2496, 2
497, 2522, 2536, 2537, 2594, 2596, 2631, 2638, 2721, 2722, 2725, 2751, 2752, 2761, 2779, 2782
, 2783, 2808, 2810, 2870, 2878, 2879, 2944, 2976, 2982, 2986, 2995, 2999, 3000, 3001, 3003, 30
04, 3020, 3051, 3054, 3057, 3060, 3061, 3064, 3065, 3069, 3071, 3072, 3073, 3077, 3082, 3083,
3086, 3087, 3088, 3090, 3091, 3097, 3099, 3101, 3106, 3108, 3110, 3112, 3114, 3117, 3123, 312
4, 3127, 3129, 3133, 3134, 3139, 3140, 3143, 3150, 3155, 3163, 3165, 3167, 3170, 3171, 3172, 3
173, 3175, 3176, 3177, 3178, 3179, 3182, 3183, 3187, 3189, 3191, 3193, 3197, 3204, 3208, 3209
, 3216, 3220, 3224, 3225, 3234, 3245, 3246, 3247, 3248, 3250, 3251, 3252, 3253, 3255, 3256, 32
57, 3258, 3260, 3262, 3277, 3290, 3300, 3301, 3331, 3334, 3337, 3350, 3353, 3354, 3355, 3359,
3361, 3362, 3391, 3399, 3400, 3501, 3502, 3503, 3511, 3515) ;
BEGI N
FOR I I N 1. . P_ROWS LOOP
SELECT SEQ_ORDER_I D. NEXTVAL I NTO V_ORDER_I D FROM DUAL;
V_ORDER_DATE : = TRUNC( SYSDATE- P_DAYS ) ;
N : = ROUND( DBMS_RANDOM. VALUE( 1, 2) ) ;
I F N = 1 THEN
V_ORDER_MODE : = ' di r ect ' ;
ELSE
V_ORDER_MODE : = ' onl i ne' ;
END I F;
V_CUSTOMER_I D : = ROUND( DBMS_RANDOM. VALUE( 1, 96) ) ;
V_ORDER_STATUS: = ROUND( DBMS_RANDOM. VALUE( 1, 10) ) ;
V_SALES_REP_I D: = ROUND( DBMS_RANDOM. VALUE( 153, 163) ) ;
I NSERT I NTO ORDERS
( ORDER_I D, ORDER_DATE, ORDER_MODE, CUSTOMER_I D, ORDER_STATUS,
ORDER_TOTAL, SALES_REP_I D)
VALUES
( V_ORDER_I D,
V_ORDER_DATE,
V_ORDER_MODE,
Page 686 Oracle DBA Code Examples

V_CUST_I DS( V_CUSTOMER_I D) ,
V_ORDER_STATUS,
0,
V_SALES_REP_I D) ;
V_ORDER_TOTAL : = 0;
V_I TEMS_COUNT : = ROUND( DBMS_RANDOM. VALUE( 1, 10) ) ;
M : = 1;
FOR X I N 1. . V_I TEMS_COUNT LOOP
V_PRODUCT_I D: = ROUND( DBMS_RANDOM. VALUE( 1, 275) ) ;
SELECT LI ST_PRI CE I NTO V_PROD_PRI CE
FROM PRODUCT_I NFORMATI ON
WHERE PRODUCT_I D=V_PROD_I DS( V_PRODUCT_I D) ;
V_CHANGE_PRI CE : = ROUND( DBMS_RANDOM. VALUE( 1, 4) ) ;
- - di scount ( MAX 20%) may be gi ven t o 25%of ent er ed i t ems
I F V_CHANGE_PRI CE=4 THEN
V_PROD_PRI CE : = ROUND( V_PROD_PRI CE -
( ROUND( DBMS_RANDOM. VALUE( 1, 20) ) / 100) *V_PROD_PRI CE) ;
END I F;
V_QUANTI TY: =ROUND( DBMS_RANDOM. VALUE( 1, 20) ) ;
V_ORDER_TOTAL : = V_ORDER_TOTAL + V_QUANTI TY*V_PROD_PRI CE;
BEGI N
I NSERT I NTO
ORDER_I TEMS( ORDER_I D, LI NE_I TEM_I D, PRODUCT_I D, UNI T_PRI CE, QUANTI TY)

VALUES( V_ORDER_I D, M, V_PROD_I DS( V_PRODUCT_I D) , V_PROD_PRI CE, V_QUANTI TY ) ;
M : = M + 1 ;
EXCEPTI ON
WHEN OTHERS THEN
I F UPPER( SQLERRM) LI KE ' %ORDER_I TEMS_UK%' THEN
NULL;
ELSE
RAI SE;
END I F;
END ;
END LOOP; - - X l oop
UPDATE ORDERS SET ORDER_TOTAL = V_ORDER_TOTAL WHERE ORDER_I D =
V_ORDER_I D;
I F MOD( I , 100) = 0 THEN
COMMI T;
END I F;
END LOOP; - - I l oop
COMMI T;
END I NSERT_ORDERS;
PROCEDURE Spi nCPUs ( P_I TERATI ON I N NUMBER)
I S
N NUMBER;
BEGI N
FOR I I N 1. . P_I TERATI ON LOOP
- - pur e CPU pr ocessi ng ( no physi cal or l ogi cal r ead)
N : = SQRT( ROUND( DBMS_RANDOM. VALUE( 1, 1000) ) ) ;
- - DBMS_LOCK. SLEEP( r ound( DBMS_RANDOM. VALUE( 0. 01, 0. 05) , 2) ) ; - - i n seconds
END LOOP;
END Spi nCPUs;
PROCEDURE RandomQuer y( P_I TERATI ON I N NUMBER)
I S
V_START NUMBER;
V_END NUMBER;
N NUMBER;
Page 687 Oracle DBA Code Examples

BEGI N
V_END : = G_MAX_ORDER_I D;
V_START : = ROUND( DBMS_RANDOM. VALUE( G_MI N_ORDER_I D, G_MAX_ORDER_I D) ) ;
FOR I I N 1. . P_I TERATI ON LOOP
FOR R I N ( SELECT O. ORDER_I D, O. ORDER_DATE, C. CUST_LAST_NAME,
O. ORDER_TOTAL
FROM ORDERS O , CUSTOMERS C
WHERE O. CUSTOMER_I D = C. CUSTOMER_I D
AND ORDER_I D BETWEEN V_START AND V_END) LOOP - - j ust r et r ei ve dat a
NULL;
END LOOP;
- - DBMS_LOCK. SLEEP( ROUND( DBMS_RANDOM. VALUE( 0. 01, 3) , 2) ) ;
END LOOP;
END RandomQuer y;
PROCEDURE RandomDML( P_I TERATI ON I N NUMBER)
I S
V VARCHAR2( 1) ;
N NUMBER;
V_ORDER_I D NUMBER;
V_LI NE_I TEM_I D NUMBER ;
V_MAX_ORDERI _I D NUMBER;
V_MI N_ORDERI _I D NUMBER;
V_PRI CE NUMBER;
V_ORDER_LOCKED BOOLEAN : = FALSE;
BEGI N
FOR I I N 1. . P_I TERATI ON LOOP
N : = ROUND( DBMS_RANDOM. VALUE( 1, 3) ) ;
I F N=1 THEN
I NSERT_ORDERS( 1) ;
ELSI F N=2 THEN
- - pi ck up an or der and modi f y t he pr i ce of one of i t s i t ems
V_ORDER_I D : = ROUND( DBMS_RANDOM. VALUE( G_MI N_ORDER_I D, G_MAX_ORDER_I D) ) ;
V_ORDER_LOCKED : = FALSE;
- - make sur e t he or der i sn' t l ocked
BEGI N
SELECT ' X' I NTO V FROM ORDERS WHERE ORDER_I D = V_ORDER_I D FOR UPDATE
WAI T 3;
EXCEPTI ON
WHEN OTHERS THEN
I F SQLCODE=' - 30006' THEN - - t he r ow i s l ocked
V_ORDER_LOCKED : = TRUE;
ELSE
RAI SE; - - i f t her e i s anot her non- expect ed er r or , r ai se i t
END I F;
END;
I F V_ORDER_LOCKED THEN
NULL; - - no need t o make t he sessi on bl ocked
ELSE - - updat e t he i t em
BEGI N
SELECT MAX( LI NE_I TEM_I D) , MI N( LI NE_I TEM_I D)
I NTO V_MAX_ORDERI _I D, V_MI N_ORDERI _I D
FROM ORDER_I TEMS WHERE ORDER_I D=V_ORDER_I D;
V_LI NE_I TEM_I D : =
ROUND( DBMS_RANDOM. VALUE( V_MI N_ORDERI _I D, V_MAX_ORDERI _I D) ) ;
SELECT UNI T_PRI CE I NTO V_PRI CE FROM ORDER_I TEMS
WHERE ORDER_I D=V_ORDER_I D AND LI NE_I TEM_I D=V_LI NE_I TEM_I D;
V_PRI CE : = V_PRI CE + ( ROUND( DBMS_RANDOM. VALUE( - 20, 20) ) / 100) *V_PRI CE;
- - updat e i f t her e i s no l ock on t he i t em
Page 688 Oracle DBA Code Examples

BEGI N
SELECT ' X' I NTO V FROM ORDER_I TEMS WHERE ORDER_I D=V_ORDER_I D AND
LI NE_I TEM_I D=V_LI NE_I TEM_I D FOR UPDATE WAI T 3;
UPDATE ORDER_I TEMS SET UNI T_PRI CE=V_PRI CE
WHERE ORDER_I D=V_ORDER_I D AND LI NE_I TEM_I D=V_LI NE_I TEM_I D;
UPDATE ORDERS SET ORDER_TOTAL=ORDER_TOTAL+V_PRI CE
WHERE ORDER_I D=V_ORDER_I D;
EXCEPTI ON
WHEN OTHERS THEN
I F SQLCODE=' - 30006' THEN - - t he r ow i s l ocked
NULL; - - do not hi ng
ELSE
RAI SE; - - i f t her e i s anot her non- expect ed er r or , r ai se i t
END I F;
END;
EXCEPTI ON
- - i f or der has no i t ems
WHEN NO_DATA_FOUND THEN
NULL;
END;
END I F; - - V_ORDER_LOCKED
ELSI F N=3 THEN
- - pi ck up an i t emt o del et e
V_ORDER_I D : = ROUND( DBMS_RANDOM. VALUE( G_MI N_ORDER_I D, G_MAX_ORDER_I D) ) ;
SELECT MAX( LI NE_I TEM_I D) , MI N( LI NE_I TEM_I D)
I NTO V_MAX_ORDERI _I D, V_MI N_ORDERI _I D
FROM ORDER_I TEMS WHERE ORDER_I D=V_ORDER_I D;
V_LI NE_I TEM_I D : =
ROUND( DBMS_RANDOM. VALUE( V_MI N_ORDERI _I D, V_MAX_ORDERI _I D) ) ;
DELETE ORDER_I TEMS WHERE ORDER_I D=V_ORDER_I D AND
LI NE_I TEM_I D=V_LI NE_I TEM_I D;
- - r e- or der t he i t mes i n t he or der
DECLARE
CURSOR CR I S SELECT LI NE_I TEM_I D FROM ORDER_I TEMS WHERE
ORDER_I D=V_ORDER_I D ORDER BY LI NE_I TEM_I D FOR UPDATE;
BEGI N
N: =1;
FOR R I N CR LOOP
UPDATE ORDER_I TEMS SET LI NE_I TEM_I D = N WHERE CURRENT OF CR;
N: =N+1;
END LOOP;
END ;
END I F;
- - DBMS_LOCK. SLEEP( ROUND( DBMS_RANDOM. VALUE( 0. 1, 2) , 2) ) ;
COMMI T;
END LOOP;
END RandomDML;
Begi n
I NI TI ALI ZE;
END l oad_gener at or ;
/

- - i ni t i al dat a
exec l oad_gener at or . i nser t _or der s( 100000) ;

exec dbms_st at s. gat her _schema_st at s( ' SA' ) ;
Page 689 Oracle DBA Code Examples

OS side: Unix
- - i n a f ol der cr eat e t he f ol l owi ng scr i pt s
mkdi r ~/ scr i pt s
cd ~/ scr i pt s
mkdi r l oad
cd l oad

- - ( 1) l oadcpu1. sh
vi l oadcpu. sh
#! / bi n/ bash
# appl y CPU l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons
user s=$1
SRVC=" or a11gr 2"
UNPW=" sa/ s"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oadcpu. sql "
x=1
y=$user s
I TER=$2
whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER &
x=`expr $x + 1`
done

- - ( 2) l oadcpu. sql
vi l oadcpu. sql
begi n
sa. LOAD_GENERATOR. Spi nCPUs( &1) ;
end;
/
exi t


- - ( 3) l oadquer y. sh
vi l oadquer y. sh
#! / bi n/ bash
# appl y r andomquer i es l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names
user s=$1
SRVC=" or a11gr 2"
UNPW=" sa/ s"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oadquer y. sql "
x=1
y=$user s
I TER=$2

whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER &
x=`expr $x + 1`
done

- - ( 4) l oadquer y. sql
vi l oadquer y. sql
begi n
sa. LOAD_GENERATOR. RANDOMQUERY ( &1) ;
Page 690 Oracle DBA Code Examples

end;
/
exi t


- - ( 5) l oaddml . sh
vi l oaddml . sh
#! / bi n/ bash
# appl y r andomDML l oad on Or acl e DB
# par amet er s: 1 connect i ons, 2 I t er at i ons
user s=$1
SRVC=" or a11gr 2"
UNPW=" sa/ s"
SQLCMD=" / home/ or acl e/ scr i pt s/ l oad/ l oaddml . sql "
x=1
y=$user s
I TER=$2
whi l e [ $x - l e $y ]
do
sql pl us - s $UNPW@$SRVC @$SQLCMD $I TER &
x=`expr $x + 1`
done

- - ( 6) l oaddml . sql
vi l oaddml . sql
begi n
sa. LOAD_GENERATOR. RANDOMDML( &1) ;
end;
/
exi t


# make al l sh f i l es i n cur r ent di r ect or y execut abl es
f or f i n *. sh; do chmod 744 $f ; done
OS side: Windows
- - i n a f ol der cr eat e t he f ol l owi ng scr i pt s
- - ( 1) l oadcpu. bat
REM appl y CPU l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons

set user s=%1
set SRVC=or a11g
set UNPW=sa/ s
set SQLCMD=C: \ TEMP\ l oad\ l oadcpu. sql
set x=1
set y=%user s%
set I TER=%2

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%)


- - ( 2) l oadcpu1. sql
begi n
hr s. LOAD_GENERATOR. Spi nCPU( &1) ;
end;
Page 691 Oracle DBA Code Examples

/
exi t


- - ( 3) l oadquer y. bat
REM appl y r andomquer i es l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons

set user s=%1
set SRVC=or a11g
set UNPW=sa/ s
set SQLCMD=C: \ TEMP\ l oad\ l oadquer y. sql
set x=1
set y=%user s%
set I TER=%2

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%)

- - ( 4) l oadquer y. sql
begi n
hr s. LOAD_GENERATOR. RANDOMQUERY( &1) ;
end;
/
exi t


- - ( 5) l oaddml . bat
REM appl y r andomDML l oad on Or acl e DB
REM par amet er s: 1 connect i ons, 2 I t er at i ons, 3 r ows i n names
set user s=%1
set SRVC=or a11g
set UNPW=sa/ s
set SQLCMD=C: \ TEMP\ l oad\ l oaddml . sql
set x=1
set y=%user s%
set I TER=%2

f or / L %%i i n ( 1, 1, %y%) do ( st ar t / d " E: \ or acl e\ Or aDB11g" sql pl us - S
%UNPW%@%SRVC%@%SQLCMD%%I TER%)


- - ( 6) l oaddml . sql
begi n
sa. LOAD_GENERATOR. RANDOMDML ( &1) ;
end;
/
exi t
Using the Load Generator Scripts
## Usi ng t he Load Gener at or #
# 5 connect i ons 1000 i t er at i ons 100000 number of r ows i n NAMES t abl e
# i n Wi ndows:
l oadcpu 5 1000
l oaddml 5 1000

# i n Uni x:
Page 692 Oracle DBA Code Examples

. / l oadcpu. sh 5 1000
Page 693 Oracle DBA Code Examples

SQL Usage Samples
Merge Command
/ * Mar ge Command */
MERGE I NTO pr oduct s p / * Dest i nat i on t abl e
USI NG pr oduct _changes s / * Sour ce t abl e
ON ( p. pr od_i d = s. pr od_i d) / * Sear ch/ j oi n condi t i on
WHEN MATCHED THEN UPDATE / * Updat e i f j oi n
SET p. pr od_l i st _pr i ce = s. pr od_new_pr i ce
WHERE p. pr od_st at us <> ' EXPI RED' / * Condi t i onal updat e
WHEN NOT MATCHED THEN
I NSERT / * I nser t i f not j oi n
SET p. pr od_l i st _pr i ce = s. pr od_new_pr i ce
WHERE s. pr od_st at us <> ' EXPI RED' / * Condi t i onal i nser t

- - usi ng del et e keywor d wi t h Mer ge command
- - onl y r ows t o updat e wi l l be consi der ed by t he del et e cl ause
MERGE I NTO pr oduct s p
USI NG pr oduct _changes s ON ( p. pr od_i d = s. pr od_i d)
WHEN MATCHED THEN UPDATE
SET p. pr od_l i st _pr i ce = s. pr od_new_pr i ce,
p. pr od_st at us = s. pr od_new_st at us
DELETE WHERE ( p. pr od_st at us = ' OLD_I TEM' ) - - i t par t of updat e
WHEN NOT MATCHED THEN I NSERT
( pr od_i d, pr od_l i st _pr i ce, pr od_st at us)
VALUES ( s. pr od_i d, s. pr od_new_pr i ce, s. pr od_new_st at us) ;
Multitable Inserts
/ * Mul t i t abl e I nser t s */
- - uncondi t i onal
I NSERT ALL
I NTO t ar get 1 VALUES ( pr oduct _i d, cust omer _i d, sysdat e, pr oduct _quant i t y)
I NTO t ar get 2 VALUES ( pr oduct _i d, sysdat e, pr oduct _pr i ce, pr oduct _di scount )
SELECT s. pr oduct _i d, s. cust omer _i d, sysdat e, s. pr oduct _quant i t y,
s. pr oduct _pr i ce, s. pr oduct _di scount
FROM sour ce s;

- - condi t i onal ALL r ows
- - a r ow can be on t he t wo t abl es
I NSERT ALL
WHEN pr oduct _i d I N( SELECT pr oduct _i d FROM pr i mar y) THEN
I NTO t ar get 1 VALUES ( pr oduct _i d, cust omer _i d, sysdat e, pr oduct _quant i t y)
WHEN pr oduct _i d I N ( SELECT pr oduct _i d FROM secondar y) THEN
I NTO t ar get 2 VALUES ( pr oduct _i d, sysdat e, pr oduct _pr i ce, pr oduct _di scount )
SELECT s. pr oduct _i d, s. cust omer _i d, sysdat e, s. pr oduct _quant i t y,
s. pr oduct _pr i ce, s. pr oduct _di scount
FROM sour ce s;

- - condi t i onal f i r st r ows
- - i nser t i nt o t abl e of f i r st appl i ed condi t i on - > a r ow i s i n onl y one t abl e
I NSERT FI RST WHEN ( sum_quant i t y_sol d > 10 AND pr od_wei ght _cl ass < 5) AND
sum_quant i t y_sol d >=1) OR ( sum_quant i t y_sol d > 5 AND pr od_wei ght _cl ass > 5)
Page 694 Oracle DBA Code Examples

THEN
I NTO l ar ge_f r ei ght _shi ppi ng VALUES
( t i me_i d, cust _i d, pr od_i d, pr od_wei ght _cl ass, sum_quant i t y_sol d)
WHEN sum_amount _sol d > 1000 AND sum_quant i t y_sol d >=1 THEN
I NTO expr ess_shi ppi ng VALUES
( t i me_i d, cust _i d, pr od_i d, pr od_wei ght _cl ass,
sum_amount _sol d, sum_quant i t y_sol d)
WHEN ( sum_quant i t y_sol d >=1) THEN I NTO def aul t _shi ppi ng VALUES
( t i me_i d, cust _i d, pr od_i d, sum_quant i t y_sol d)
ELSE I NTO i ncor r ect _sal es_or der VALUES ( t i me_i d, cust _i d, pr od_i d)
SELECT s. t i me_i d, s. cust _i d, s. pr od_i d, p. pr od_wei ght _cl ass,
SUM( amount _sol d) AS sum_amount _sol d,
SUM( quant i t y_sol d) AS sum_quant i t y_sol d
FROM sal es s, pr oduct s p
WHERE s. pr od_i d = p. pr od_i d AND s. t i me_i d = TRUNC( SYSDATE)
GROUP BY s. t i me_i d, s. cust _i d, s. pr od_i d, p. pr od_wei ght _cl ass;

- - Mi xed Condi t i onal and Uncondi t i onal I nser t
I NSERT FI RST WHEN cust _cr edi t _l i mi t >= 4500 THEN
I NTO cust omer s_speci al VALUES ( cust _i d, cust _cr edi t _l i mi t )
ELSE I NTO cust omer s
SELECT * FROM cust omer s_new;
Parallel Insert
For further details see: Enabling Direct-Path INSERT
/ * Par al l el l oadi ng i nt o t abl e */
- - must bef or e t he hi nt
ALTER SESSI ON ENABLE PARALLEL DML;
- - t hen use t he hi nt
I NSERT / *APPEND NOLOGGI NG PARALLEL */
I NTO sal es_dat a
SELECT pr oduct _i d, cust omer _i d, TRUNC( sal es_dat e) ,
di scount _r at e, sal es_quant i t y, sal e_pr i ce
FROM sal es_hi st or y;
- - i f t r i gger s ar e t her e, hi nt won' t be used
Deleting Duplicate Rows in a Table
- - del et e dupl i cat ed r ows i n our _t abl e based on col 1, col 2. . et c.
DELETE FROM our _t abl e
WHERE r owi d not i n
( SELECT MI N( r owi d)
FROM our _t abl e
GROUP BY col umn1, col umn2, col umn3. . . ) ;
Adding a Primary Key to a Table and then Filling it
cr eat e sequence seq_OAS_BALANCE;

al t er t abl e OAS_BALANCE add ( pki d number ) ;

Page 695 Oracle DBA Code Examples

decl ar e
n number ;
cur sor cr s i s sel ect r owi d f r omOAS_BALANCE f or updat e of pki d;
begi n
f or r i n cr s l oop
sel ect seq_OAS_BALANCE. next val i nt o n f r omdual ;
updat e OAS_BALANCE set pki d=n wher e cur r ent of cr s;
end l oop;
commi t ;
end;
/
Page 696 Oracle DBA Code Examples

More DBA Scripts
Compare Table Sizes in Two Databases
- - compar e t abl es i n cur r ent db wi t h same t abl es i n ot her db
- - usef ul f or checki ng af t er t r ansf er r i ng t oo many t abl es

DECLARE
N NUMBER;
M NUMBER;
BEGI N
DBMS_OUTPUT. ENABLE( 100000) ;
FOR S I N ( SELECT USERNAME FROM SCHEMA_NAMES WHERE USERNAME <>' MOL' ORDER BY
1) LOOP
FOR O i n ( SELECT TABLE_NAME FROM DBA_TABLES@OLDORA11G WHERE OWNER =
S. USERNAME ) LOOP
BEGI N
N : = 0;
M : = 0;
EXECUTE I MMEDI ATE ' SELECT COUNT( ROWI D) FROM ' | | S. USERNAME | | ' . " ' | |
O. TABLE_NAME | | ' " @OLDORA11G' I NTO N;
EXECUTE I MMEDI ATE ' SELECT COUNT( ROWI D) FROM ' | | S. USERNAME | | ' . " ' | |
O. TABLE_NAME | | ' " ' I NTO M;
I F M <> N THEN
DBMS_OUTPUT. PUT_LI NE( S. USERNAME | | CHR( 9) | | O. TABLE_NAME) ;
END I F;
EXCEPTI ON
WHEN OTHERS THEN
DBMS_OUTPUT. PUT_LI NE( S. USERNAME | | CHR( 9) | | O. TABLE_NAME) ;
RAI SE;
END;
END LOOP;
END LOOP;
END;
/
Page 697 Oracle DBA Code Examples

Using Linux for Oracle
Verifying the Kernel
# i s of f or mat : <Base>- <Er r at a>. <Mod><Type>
# Mod= Modi f i er ( devel oper )
# Type: None: Uni pr ocessor , smp: SMP up t o 16 GB, hugemem: SMP up t o 64 GB
uname - r
2. 6. 9- 42. 0. 0. 0. 1. ELsmp

# name of t he r el ease
cat / et c/ ent er pr i se- r el ease
Checking for a Tainted Kernel
Usually, tainted kernelt is not supported by Oracle. Some exceptions: OCFS (276450.1)
and EMC Powerpath driver (284823.1)
# 0: not t ai nt ed 1: t ai nt ed
cat / pr oc/ sys/ ker nel / t ai nt ed

# t o l i st t he st at us of modul es
l smod
Supported Hardware
Systems listed in Red Hat site (https://hardware.redhat.com) are supported by Oracle
Linux.
Using Oracle Relink Utility
If the operating system or Oracle object files change, then Oracle executables should be
relinked to create updated executables properly integrated with the operating system.
If utility returns nothing, then it means it successfully finished.
Relinking occurs automatically when a patch set is installed, but must be performed
manually when:
o An OS upgrade has occurred
o A change has been made to the OS system libraries. This can occur during the
application of an OS patch.
o A new installation failed during the relinking phase.
o An individual Oracle patch has been applied. Explicit relink instructions are usually
either included in README or integrated into the patch install script.
1. Ver i f y whet her ORACLE_HOME i s cor r ect l y set .
2. Set LD_LI BRARY_PATH t o i ncl ude $ORACLE_HOME/ l i b.
3. Execut e t he appr opr i at e r el i nk command t o r el i nk t he
appr opr i at e bi nar i es:
r el i nk al l : Al l Or acl e execut abl es
r el i nk or acl e Dat abase execut abl es
r el i nk net wor k: Li st ener , cman, names
Page 698 Oracle DBA Code Examples

r el i nk oemagent : I nt el l i gent Agent
r el i nk ut i l i t i es: SQL*Loader , t kpr of , r man,
i mpdp, expdp, i mp, exp
r el i nk ct x: Or acl e Text
Certified and Supported File Systems
In Linux, Oracle certifies three file systems:
o ext3
o Automatic Storage Management (ASM)
o Oracle Cluster File System/Oracle Cluster File System 2 (OCFS2)
Enterprise Linux Runlevels
Runlevel 0: Halt. It is used to shut down the system.
Runlevel 1: Single-user (maintenance) mode. Only root may log in.
Runlevel 2: Multiuser mode, text-based console only
Runlevel 3: Multiuser mode with networking
Runlevel 4: For custom use
Runlevel 5: The default mode; multiuser with networking and active X session
Runlevel 6: Reboot. This shuts everything down and then starts it back.
Boot i ng t o a Nondef aul t Runl evel
Ent er pr i se Li nux:
>you pr ess [ E] t hen scr ol l down t o sel ect t he ker nel
>pr ess [ E] agai n
>pr ess t he spacebar
>ent er t he r unl evel you want t o boot t o
>t hen pr ess [ B]

# t o pr i nt pr evi ous and cur r ent r unl evel s:
r unl evel
Using /etc/oratab File and dbstart Utility
Y or N in /etc/oratab indicates to the dbstart utility whether the database should be brought
up at system boot time.
ASM and database instances created without using DBCA will not appear in the oratab file.
You should manually add them:
+ASM: / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1: Y
or cl : / u01/ app/ or acl e/ pr oduct / 10. 2. 0/ db_1: Y
The dbst ar t scr i pt t hat i s pr ovi ded wi t h 10. 2. 0. 1. 0 cont ai ns an er r or .
The Met al i nk not e 336299. 1 document s t hi s i ssue. To sol ve t hi s pr obl em,
per f or mt he f ol l owi ng st eps:
1. Edi t $ORACLE_HOME/ bi n/ dbst ar t
2. Go t o l i ne 78.
3. Repl ace t he l i ne wi t h:
Page 699 Oracle DBA Code Examples

ORACLE_HOME_LI STNER=$ORACLE_HOME
4. Save t he f i l e and exi t t he edi t or .
5. Execut e dbst ar t .
Automating Jobs
Using cron
/ * secur i t y */
Onl y user s l i st ed i n t he / et c/ cr on. al l ow f i l e ar e al l owed t o use cr on
User s l i st ed i n t he / et c/ cr on. deny f i l e cannot use cr on.
I f nei t her of t hese f i l es exi st , onl y t he super user can use cr on.


/ * Managi ng cr ont ab f i l es */
cr ont ab used t o i nst al l , dei nst al l or l i st t he t abl es ( cr ont abs) .
- u user t he user whose cr ont ab i s t o be t weaked
- l di spl ay t he cur r ent cr ont ab f i l e
- r r emove t he cur r ent cr ont ab f i l e
- e edi t . Af t er exi t f r omt he edi t or , t he modi f i ed cr ont ab wi l l be
i nst al l ed


/ * Usi ng cr on */
cr ont ab f or mat : <mi nut e> <hour > <day> <mont h> <weekday> <cmd>
1. mi nut e ( f r om0 t o 59) or speci al keywor ds:
2. hour ( f r om0 t o 23)
3. day of mont h ( f r om1 t o 31)
4. mont h ( f r om1 t o 12)
5. day of week ( f r om0 t o 6) ( 0=Sunday)

Speci al keywor ds ar e:
@r eboot Run once, at st ar t up
@year l y Run once a year " 0 0 1 1 *"
@annual l y ( same as @year l y)
@mont hl y Run once a mont h " 0 0 1 * *"
@weekl y Run once a week " 0 0 * * 0"
@dai l y Run once a day " 0 0 * * *"
@mi dni ght ( same as @dai l y)
@hour l y Run once an hour " 0 * * * *"

I f t he admi ni st r at or put s an execut abl e scr i pt i nt o one of t he f ol l owi ng
di r ect or i es,
t hen cr on r uns t he scr i pt at t he appr opr i at e i nt er val :
/ et c/ cr on. hour l y
/ et c/ cr on. dai l y
/ et c/ cr on. weekl y
/ et c/ cr on. mont hl y


/ * Mai l i ng t he cr ont ab out put */
By def aul t cr on saves t he out put i n t he user ' s mai l box on t he l ocal syst em.
But you can al so conf i gur e cr ont ab t o f or war d al l out put t o a r eal emai l
addr ess:
cr ont ab
MAI LTO=" your name@your domai n. com"
Page 700 Oracle DBA Code Examples


I f want t o r ecei ve onl y one cr onj ob' s out put i n your mai l ,
make sur e t hi s package i s i nst al l ed:
apt i t ude i nst al l mai l x
t hen change t he cr onj ob l i ke t hi s:
*/ 10 * * * * / bi n/ execut e/ t hi s/ scr i pt . sh 2>&1 | mai l - s " Cr onj ob ouput "
your name@your domai n


/ * Exampl es */
>ever y Fr i day 1AM
0 1 * * 5 / bi n/ execut e/ t hi s/ scr i pt . sh

>14 mi nut es af t er 10 p. m. ever y Monday t hr ough Fr i day of ever y mont h
14 22 * * 1- 5 su - or acl e - c / usr / l ocal / bi n/ backup. cmd >/ dev/ nul l 2>&1

>10 past af t er ever y hour on t he 1st of ever y mont h
10 * 1 * * / bi n/ execut e/ t hi s/ scr i pt . sh

>ever y 10 mi nut es
0, 10, 20, 30, 40, 50 * * * * / bi n/ execut e/ t hi s/ scr i pt . sh
*/ 10 * * * * / bi n/ execut e/ t hi s/ scr i pt . sh

>dai l y
@dai l y / bi n/ execut e/ t hi s/ scr i pt . sh
Using anacron
Most system cron jobs will run during the night and will get done only if the computer is
switched on. The anacron mechanism on the other hand assumes that the computer is not
running continuously. After the computer is started anacron will execute jobs after a certain
delay.
anacron keeps track of the day a given job has been executed. So the shortest period a job
can be executed is a day.
The anacron daemon is usually started from an rc-script and will read an anacrontab which
has the following format:
Per i od Del ay J ob- I dent i f i er Command
The period is given in days, the delay is in minutes, the job-identifier can be any character
and the command is usually of the form r un- par t s / et c/ cr on. dai l y but can be any
command.
Exampl e 9. 4. Sampl e / et c/ anacr ont ab
SHELL=/ bi n/ sh
PATH=/ usr / l ocal / sbi n: / usr / l ocal / bi n: / sbi n: / bi n: / usr / sbi n: / usr / bi n
MAI LTO=r oot
1 65 cr on. dai l y r un- par t s / et c/ cr on. dai l y
7 70 cr on. weekl y r un- par t s / et c/ cr on. weekl y
30 75 cr on. mont hl y r un- par t s / et c/ cr on. mont hl y

Using at command
The at command executes a command once at a specified time.
By default at is restricted to the root user. To override this you must either have an empty
/etc/at.deny or have a /etc/at.allow with the appropriate names.
at jobs are saved in /var/spool/at/
Page 701 Oracle DBA Code Examples

at jobs are spooled in /var/spool/at/
at [ t i me]
Wher e t i me can be expr essed as:
now
now + 1 mi n
now + 1 hour
now + 1 day
3am+ 2days
mi dni ght
10: 15 Apr 12
t eat i me
For compl et e l i st of val i d t i me f or mat s see / usr / shar e/ doc/ at - xxx/ t i mespec

# execut e t he commands i n t he f i l e
at - f myj obs. t xt now + 1 hour

# l i st commands t hat ar e schedul ed
at - l
at q

# r emove a j ob
at r m<j obi d>
Using batch command
batch command executes commands when system load average drops below 0.8, or the
value specified in the invocation of atrun.
bat ch [ - V] [ - q queue] [ - f f i l e] [ - mv] [ TI ME]
Task Scheduler
There are GUI task schedulers available that are front ends for cron in both the Gnome and
the K(ommon) Desktop Environment (KDE).
Configuring Linux Memory for Oracle
32 bit Architecture:
With Linux 32-bit, Oracle is able to use about 1.7GB of address space for its SGA. To
increase it, refere to noted 200266.1. Be aware of the consequenced limitations.
In Red Hat Enterprise Linux 3, 4 or 5 the smp kernel can be used on systems with up to 16
GB of RAM.
The hugemem kernel is required in order to use all the memory on systems that have more
than 16GB of RAM up to 64GB. However, it is recommend to use the hugemem kernel even
on systems that have 8GB of RAM.
In Red Hat Enterprise Linux 5, a 32 bit kernel is always a hugemem kernel so there is no
need to install a special kernel.
Using Linux Performance Monitoring Tools
Note: OS Watcher uses most commonly used Linux tools and store their output in files. It is a
nice frame work to implement using those tools. To learn more about using it, see Using OS
Watcher.
Page 702 Oracle DBA Code Examples

About Linux Tools
t op: useful for diagnosing CPU and I/O issues, though not as reliable for Oracle memory
issues. Individual process memory numbers should not be relied upon.
sar : reports system activity including memory, I/O, and CPU usage.
sar samples the /proc file system at 10-minute intervals and records the data in /var/log/sa
as a sa# file where # is the day of the month. A full months worth of statistics are retained
so that the administrator can use sar to view past statistics as well as current. For example,
to view the CPU statistics for the 23rd of the month:
sar u 2 4 f /var/log/sa/sa29
-o [<fnmae>] save output to filename (default /var/log/sa/sadd ) (cannot be used with
X)
-f [<fnmae>] read from filename (default /var/log/sa/sadd )
-X pid | SELF | ALL Report statistics for the child processes of the process whose PID is pid.
SELF statistics of the child processes of the sar process itself
ALL statistics of the child processes of all the system processes.
vmst at : activity on processes, memory, paging, block I/O, traps, and CPU activity (best for
memory)
i ost at : disk activity
System Log Files: /var/log/message ../syslog
f r ee command displays the total amount of free and used physical and swap memory in
the system, as well as the shared memory and buffers used by the kernel.
mpstat: reporter on CPU statistics.
Graphical Measurement Tools
Using Linux Tools
/ * CPU */
# how many CPUs
cat / pr oc/ cpui nf o

# use t op t o see aver ae l oad ( now, 5 mi nut es ago, and 10 mi nut es ago) .
# l oad f act or = l oad aver age/ #CPUs
# i f l f <1: no l oad on CPU,
# bet ween 1 and 2: CPU r unni ng at capaci t y
# >2, CPU may be a bot t l eneck ( use sar and vmst at t o i nvest i gat e)
# i f you use " 1" i nt er act i ve command, you can see l oad per CPU
t op

# CPU met r i cs
# al l appended by <i nt er val > <count >
vmst at
mpst at - P <CPU>| ALL
sar - u
# queue si ze: wai t i ng f or CPU
# ( shoul dn' t be l ar ger t han CPU#)
sar - q
# di spl ay CPU st at s onl y
i ost at - c

# t o know whi ch sessi on i s consumi ng CPU
Page 703 Oracle DBA Code Examples

# get i t s PI D f r omt op
# t hen:
sel ect pi d, spi d, pname, user name, pr ogr am
f r omv$pr ocess
wher e spi d=20052;

sel ect * f r omv$sessi on
wher e paddr = ( sel ect addr f r omv$pr ocess wher e spi d=20304) ;


/ * Memor y */
# Tot al Memor y
f r ee - m, t op, or cat / pr oc/ memi nf o

# hi gher " Pages I n" i ndi cat e RAM shor t age
t op
f r ee
cat / pr oc/ memi nf o
# pagi ng i nf o
sar - B
# memor y met r i cs
sar - R


/ * I O */
# st or age vendor s have t hei r moni t or i ng t ool s
# i o act i vi t y by di sk
# check avgr q- sz. awai t whi ch gi ves t he aver age wai t t i me f or r equest s
i ost at - d
# by par t i t i on
i ost at - p
# exet ended out put
i ost at - d - x
# r t ps/ wt ps r equest s per se
sar - d 2 10
# about over al l i o st at s
vmst at
Checking Some General Guideline on Truning Oracle in Linux
Use an appropriately sized database block: general purpose:8K, OLTP:4K, DSS:16K. Use a
larger block size if the application has very large indexes (15>levels), or consider using
partitioned indexes.
Use a larger redo log buffer than default: for OLTP systems
Multiprocessing (SMP) machines.
Setting PRE_PAGE_SGA = true causes each server process that starts to touch every page
of the SGA, thus mapping all the SGA pages to physical memory. It may slow down
connection time, though; so make sure you have enough free memory to accomodate all
SGA.
Use automatic memory management.
Setting atime off: In Linux, by default, the last time-read attribute (atime) is updated every
time a file is read. For database files, this is not an important statistic and you can turn it
off to reduce the number of I/Os:
Page 704 Oracle DBA Code Examples

# Thi s par amet er can be set f or a f i l e wi t h:
chat t r +A <f i l ename>
# f or a di r ect or y wi t h:
chat t r - R +A <di r ect or y name>

# To make i t per si st ent acr oss r eboot s:
vi / et c/ f st ab f i l e
/ dev/ hdb7 / u3/ app/ or acl e/ ext 3 r w, noat i me 1 1
Troubleshooting Oracle Database in Linux
Using OS Watcher (OSW)
OS Watcher (OSW) is a collection of UNIX shell scripts intended to collect and archive
operating system and network metrics to aid support in diagnosing performance issues.
OSW operates as a set of background processes on the server and gathers OS data on a
regular basis, invoking such Unix utilities as vmstat, netstat and iostat.
OSW will need access to the OS utilities: top, vmstat, iostat, mpstat, netstat, and
traceroute.
On RAC, you can install it in every node.
After generating the output files, consider generating a profile from oswg (next section).
Obtain latest version from Note 301137.1
/ * Managi ng OSW*/
# i nst al l i ng OSW( di r ect or y osw wi l l be cr eat ed) :
t ar xvf osw. t ar


# Uni nst al l i ng OSW
r m- r f osw


# Set t i ng up OSWf or t r aci ng pr i vat e net wor ks ( RAC) :
mv Exampl epr i vat e. net pr i vat e. net


# st ar t i ng OSW
. / st ar t OSW. sh <i nt er val i n seconds> <hour # r et ent i on>
# t o st ar t up i n backgr ound:
nohup . / st ar t OSW. sh 30 12 &


# St oppi ng OSW
. / st opOSW. sh



/ * Di agnost i c Dat a Out put */
# ar chi ved f i l es gener at ed per hour wi t h t he f ol l owi ng f or mat :
<node_name>_<OS_ut i l i t y>_YY. MM. DD. HH24. dat


# t her e ar e 3 ent r i es f or each t i mest amp. You shoul d al ways i gnor e
# t he f i r st ent r y as t hi s ent r y i s al ways i nval i d. The second and
Page 705 Oracle DBA Code Examples

# t hi r d ent r y wi l l be val i d but t he second ent r y wi l l be 1 sec l at er
# t han t he t i mest amp and t he t hi r d ent r y wi l l be 2 seconds l at er t han t he
t i mest amp.


# oswi ost at
# What t o l ook f or :
- Aver age ser vi ce t i mes gr eat er t han 20msec f or l ong dur at i on.
- Hi gh aver age wai t t i mes
r / s Shows t he number of r eads/ second
w/ s Shows t he number of wr i t es/ second
kr / s Shows t he number of ki l obyt es r ead/ second
kw/ s Shows t he number of ki l obyt es wr i t t en/ second
wai t Aver age number of t r ansact i ons wai t i ng f or ser vi ce ( queue l engt h)
act v Aver age number of t r ansact i ons act i vel y bei ng ser vi ced
wsvc_t Aver age ser vi ce t i me i n wai t queue, i n mi l l i seconds
asvc_t Aver age ser vi ce t i me of act i ve t r ansact i ons, i n mi l l i seconds
%w Per cent of t i me t her e ar e t r ansact i ons wai t i ng f or ser vi ce
%b Per cent of t i me t he di sk i s busy
devi ce Devi ce name


# oswmpst at
What t o l ook f or
- I nvol unt ar y cont ext swi t ches ( t hi s i s pr obabl y t he mor e r el evant st at i st i c
when exami ni ng per f or mance i ssues. )
- Number of t i mes a CPU f ai l ed t o obt ai n a mut ex. Val ues consi st ent l y gr eat er
t han 200 per CPU causes syst emt i me t o i ncr ease.
- xcal i s ver y i mpor t ant , show pr ocessor mi gr at i on


# oswnet st at
# t he col l i si ons shoul d be 0. 1 per cent or l ess
Net wor k col l i si on r at e = Out put col l i si on / Out put packet s
# I nput Er r or Rat e = I er r s / I pkt s
I f t he i nput er r or r at e i s hi gh ( over 0. 25 per cent ) , t he host i s excessi vel y
dr oppi ng packet s.
# segment r et r ansmi ssi on r at e shoul d be l ow
%segment - r et r ans=( t cpRet r ansSegs / t cpOut Dat aSegs) * 100


# oswpr vt net
check I nt er f ace i s up and r espondi ng


# oswps
l i st of pr ocesses


# oswt op
# exami ne aver age l oad
# Lar ge r un queue
# A pr ocess whi ch i s " hoggi ng" CPU i s al ways suspect
# number of pr ocesses usual l y do not change over t i me


# oswvmst at
Page 706 Oracle DBA Code Examples

Using OS Watcher Graphs(OSWg)
Usi ng OSWg

# t o use J ava shi pped wi t h Or acl e
$ cd $ORACLE_HOME/ j r e/ 1. 4. 2/ bi n
expor t PATH=/ u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ j dk/ j r e/ bi n: $PATH


# i nvoki ng t he oswg:
j ava - j ar oswg. j ar - i / home/ or acl e/ osw/ ar chi ve
# i f you see: j ava. l ang. Out Of Memor yEr r or ,
# you may have t o i ncr ease t he si ze of t he j ava heap:
$j ava - j ar - Xmx512M oswg. j ar - i / home/ or acl e/ osw/ ar chi ve

Not e: t o gener at e a pr of i l e, mkdi r pr of i l e under osw home

# Usi ng OSWg: Menu Opt i on
j ava - j ar OSWg. j ar - i <f ul l y qual i f i ed pat h name of an osw ar chi ve di r ect or y>

# ot her st ar t i ng opt i ons:
j ava - j ar OSWg. j ar - i <f ul l y qual i f i ed pat h name of an osw ar chi ve di r ect or y>
- P <name> - L <name> - 6 - 7 - 8 - B <t i me> - E <t i me>

- B <st ar t t i me> Same as opt i on T f r omt he menu. The st ar t t i me wi l l al l ow t he
user t o sel ect a st ar t t i me f r omwi t hi n t he ar chi ve of f i l es t o gr aph/ pr of i l e.
Thi s over r i des t he def aul t st ar t t i me whi ch i s t he ear l i est t i me ent r y i n t he
ar chi ve di r ect or y. The f or mat of t he st ar t t i me i s Mon DD HH: MM: SS YYYY.
( Exampl e : J ul 25 11: 58: 01 2007) . An end t i me i s r equi r ed i f sel ect i ng t hi s
opt i on.
- E <end t i me> Same as opt i on T f r omt he menu. The end t i me wi l l al l ow t he user
t o sel ect an end t i me f r omwi t hi n t he ar chi ve of f i l es t o gr aph/ pr of i l e. Thi s
over r i des t he def aul t end t i me whi ch i s t he l at est t i me ent r y i n t he ar chi ve
di r ect or y. The f or mat of t he end t i me i s Mon DD HH: MM: SS YYYY. ( Exampl e : J ul
25 11: 58: 01 2007) . A st ar t t i me i s r equi r ed i f sel ect i ng t hi s opt i on.
Using the On-Board Monitor (LTOM)
LTOM is an embedded real-time data Collection and diagnostics platform developed by
Center of Expertise in Oracle.
LTOMg is embedded in LTOM.
Its reference is Note 352363.1.
Usage details are in README file.
Automatic Hang Detection
o it starts collecting statisics about hanged sessions
o to use it for RAC, install LTOM in a single node. (Other features require installing it in all
nodes)
o uses a rule based hang detection algorithm configured in
$TOM_HOME/init/hangDetect.properties
System Profiler
o The System Profiler provides the ability to continually collect data from both the
operating system and oracle and provides an integrated snapshot of the overall health
of the operating system together with the database.
o Once the data is collected, the data can be parsed and analyzed through LTOMg.
Page 707 Oracle DBA Code Examples

Automatic Session Tracing
o Automatic Session Tracing uses a set of rules to determine when to turn on SQL trace
for individual oracle sessions, using event 10046 level 12 trace.
/ * i nst al l i ng l t om*/
# Runni ng LTOM
# os user must be member of dba gr oup
# db user r equi r ed wi t h f ul l dba pr i v
t ar - xf l t om420. t ar
# t he scr i pt cr eat es " t om" user whi ch can be dr opped af t er i nst al l at i on
cd l t om/ t om_base/ i nst al l
# i f def aul t j ava cannot hel p, use Or acl e' s one ( add i t t o . bash_pr of i l e)
expor t PATH=/ u01/ app/ or acl e/ pr oduct / 11. 2. 0/ db_1/ j dk/ j r e/ bi n: $PATH
. / aut oi nst al l . sh


# uni nst al l
r m- r f t om_base


/ * TOOL USAGE */
# i nser t act i ve
expor t TOM_HOME=/ home/ or acl e/ l t om/ t om_base/ t om
cd / home/ or acl e/ l t om/ t om_base/ t om
. / st ar t l t om. sh

# i n t he backgr ound:
see t he README f i l e

# r unni ng l t omg
j ava - j ar LTOMg. j ar - i
/ home/ or acl e/ l t om/ t om_base/ t om/ r ecor di ngs/ pr of i l e/ pr o1284214950770. l og
j ava - j ar - Xmx512M LTOMg. j ar - i
/ u02/ home/ l t om/ r ecor di ngs/ pr of i l e/ pr o1190754096675. l og
Using strace
Strace is a utility that intercepts and records the system calls, which are called by a
process, and the signals, which are received by a process.
st r ace o / t mp/ hel l owor l d. out . / hel l owor l d. sh

st r ace aef Tt t o / t mp/ dat e. out dat e

st r ace p 1287 o / t mp/ or a_pmon_or cl . out

You might also like