101816212-Oracle

Embed Size (px)

Citation preview

  • 8/10/2019 101816212-Oracle

    1/80

    Oracle 10g /

    11g Database

    Administration

    May 17

    2012An Oracle database is a collection of data treated as a unit. The purpose of a databaseis to store and retrieve related information. A database server is the key to solving theproblems of information management. In general, a server reliably manages a largeamount of data in a multiuser environment so that many users can concurrently accessthe same data. All this is accomplished while delivering high performance. A databaseserver also prevents unauthorized access and provides efficient solutions for failurerecovery.

    Sai DBA

  • 8/10/2019 101816212-Oracle

    2/80

    2

    Oracle Database Administration Contents

    SlNo contents

    PageNo's

    1 Introduction to Oracle Database 6

    Overview of Oracle Grid Architecture 6Difference between a cluster and a grid 7

    Responsibilities of Database Administrators 7

    Creating the Database 7

    2 Managing Tablespaces and Datafiles 11

    Creating New Tablespaces 11

    Bigfile Tablespaces (Introduced in Oracle Ver. 10g) 12

    To Extend the Size of a tablespace 12

    To decrease the size of a tablespace 13

    Coalescing Tablespaces 13

    Taking tablespaces Offline or Online 13

    Making a Tablespace Read only. 14

    Renaming Tablespaces 14

    Dropping Tablespaces14

    Temporary Tablespace 15

    Increasing or Decreasing the size of a Temporary Tablespace 15

    Tablespace Groups 15

    Creating a Temporary Tablespace Group 16

    Assigning a Tablespace Group as the Default Temporary Tablespace 16

    Diagnosing and Repairing Locally Managed Tablespace Problems 16

    Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap) 17

    Scenario 2: Dropping a Corrupted Segment 18

    Scenario 3: Fixing Bitmap Where Overlap is Reported 18

    Scenario 4: Correcting Media Corruption of Bitmap Blocks 18

    Scenario 5: Migrating from a Dictionary-Managed to a Locally Managed Tablespace 18

    Transporting Tablespaces 19

    Procedure for transporting tablespaces 20

    Transporting Tablespace Example 21

    Viewing Information about Tablespaces and Datafiles 24

    Relocating or Renaming Datafiles 24

    Renaming or Relocating Datafiles belonging to a Single Tablespace 24

    Procedure for Renaming and Relocating Datafiles in Multiple Tablespaces 25

  • 8/10/2019 101816212-Oracle

    3/80

    3

    3 Managing REDO LOGFILES 27

    Adding a New Redo Logfile Group 27

    Adding Members to an existing group 27

    Dropping Members from a group 27

    Dropping Logfile Group 28

    Resizing Logfiles 28

    Renaming or Relocating Logfiles 28

    Clearing REDO LOGFILES 29

    Viewing Information About Logfiles 29

    4 Managing Control Files 30

    Multiplexing Control File 30

    Changing the Name of a Database 31

    Creating A New Control File 31

    Cloning an Oracle Database 32

    5 Managing the UNDO TABLESPACE 36

    Switching to Automatic Management of Undo Space 36

    Calculating the Space Requirements For Undo Retention 36Altering UNDO Tablespace 37

    Dropping an Undo Tablespace 37

    Switching Undo Tablespaces 37

    Viewing Information about Undo Tablespace 38

    6 SQL Loader 39

    CASE STUDY (Loading Data from MS-ACCESS to Oracle) 39

    CASE STUDY (Loading Data from Fixed Length file into Oracle) 41

    Loading Data into Multiple Tables using WHEN condition 42

    Conventional Path Load and Direct Path Load 43

    Direct Path 44

    Restrictions on Using Direct Path Loads 44

    7 Export and Import 45

    Invoking Export and Import 45

    Command Line Parameters of Export tool 45

    Example of Exporting Full Database 47

    Example of Exporting Schemas 47

  • 8/10/2019 101816212-Oracle

    4/80

    4

    Exporting Individual Tables 47

    Exporting Consistent Image of the tables 48

    Using Import Utility 49

    Example Importing Individual Tables 49

    Example, Importing Tables of One User account into another User account 49

    Example Importing Tables Using Pattern Matching 49

    Migrating a Database across platforms 49

    8 DATA PUMP Utility 51

    Using Data Pump Export Utility 51

    Example of Exporting a Full Database 51

    Example of Exporting a Schema 52

    Exporting Individual Tables using Data Pump Export 52

    Excluding and Including Objects during Export 53

    Using Query to Filter Rows during Export 53

    Suspending and Resuming Export Jobs (Attaching and Re-Attaching to the Jobs) 53

    9 Data Pump Import Utility 55

    Importing Full Dump File 55

    Importing Objects of One Schema to another Schema 55Loading Objects of one Tablespace to another Tablespace 55

    Generating SQL File containing DDL commands using Data Pump Import 55

    Importing objects of only a Particular Schema 56

    Example 56

    Importing Only Particular Tables 56

    Running Import Utility in Interactive Mode 56

    10 Flash Back Features 58

    Flashback Query 58

    Using Flashback Version Query 58

    Using Flashback Table to return Table to Past States 60

    Purging Objects from Recycle Bin 61

    Flashback Drop of Multiple Objects With the Same Original Name 62

    Flashback Database: Alternative to Point-In-Time Recovery 63

    Enabling Flash Back Database 63

    To how much size we should set the flash recovery area 63

    How far you can flashback database 64

    Example: Flashing Back Database to a point in time 64

  • 8/10/2019 101816212-Oracle

    5/80

    5

    11 Log Miner 66

    LogMiner Configuration 66

    LogMiner Dictionary Options 66

    Using the Online Catalog 67

    Extracting a LogMiner Dictionary to the Redo Log Files 67

    Extracting the LogMiner Dictionary to a Flat File 67

    Redo Log File Options 68

    Automatically 68

    Manually 68

    Example: Finding All Modifications in the Current Redo Log File 68

    Example of Mining Without Specifying the List of Redo Log Files Explicitly 70

    Example : Mining Redo Log Files in a Given Time Range 70

    12 BACKUP AND RECOVERY 75

    Opening the Database in Archivelog Mode 75

    Bringing the Database again in NoArchiveLog mode 75

    Taking Offline (COLD) Backups 76

    Taking Online (HOT) Backups 76

    Recovering from the Loss of a Datafile 76

  • 8/10/2019 101816212-Oracle

    6/80

    6

    Introduction to Oracle Database

    An Oracle databaseis a collection of data treated as a unit. The purpose of a database is to store and retrieve relatedinformation. A database server is the key to solving the problems of information management. In general, a serverreliably manages a large amount of data in a multiuser environment so that many users can concurrently access thesame data. All this is accomplished while delivering high performance. A database server also prevents unauthorizedaccess and provides efficient solutions for failure recovery.

    Oracle Database is the first database designed for enterprise grid computing, the most flexible and cost effective wayto manage information and applications. Enterprise grid computing creates large pools of industry-standard, modularstorage and servers. With this architecture, each new system can be rapidly provisioned from the pool of components.There is no need for peak workloads, because capacity can be easily added or reallocated from the resource pools asneeded.

    The database has logical structuresand physical structures. Because the physical and logical structures areseparate, the physical storage of data can be managed without affecting the access to logical storage structures.

    Overview of Oracle Grid Architecture

    The Oracle grid architecture pools large numbers of servers, storage, and networks into a flexible, on-demand computing resource for enterprisecomputing needs. The grid computing infrastructure continually analyzes demand for resources and adjusts supply accordingly.

    For example, you could run different applications on a grid of several linked database servers. When reports are dueat the end of the month, the database administrator could automatically provision more servers to that application tohandle the increased demand.

    Grid computing uses sophisticated workload management that makes it possible for applications to share resourcesacross many servers. Data processing capacity can be added or removed on demand, and resources within a locationcan be dynamically provisioned. Web services can quickly integrate applications to create new business processes.

    Difference between a cluster and a grid

    Clustering is one technology used to create a grid infrastructure. Simple clusters have static resources for specificapplications by specific owners. Grids, which can consist of multiple clusters, are dynamic resource pools shareableamong many different applications and users. A grid does not assume that all servers in the grid are running the same

    set of applications. Applications can be scheduled and migrated across servers in the grid. Grids share resources fromand among independent system owners.

    At the highest level, the idea of grid computing is computing as a utility. In other words, you should not care whereyour data resides, or what computer processes your request. You should be able to request information orcomputation and have it delivered - as much as you want, and whenever you want. This is analogous to the wayelectric utilities work, in that you don't know where the generator is, or how the electric grid is wired, you just ask forelectricity, and you get it. The goal is to make computing a utility, a commodity, and ubiquitous. Hence the name, TheGrid. This view of utility computing is, of course, a "client side" view.

    From the "server side", or behind the scenes, the grid is about resource allocation, information sharing, and highavailability. Resource allocation ensures that all those that need or request resources are getting what they need, that

    resources are not standing idle while requests are going unserviced. Information sharing makes sure that theinformation users and applications need is available where and when it is needed. High availability features guaranteeall the data and computation is always there, just like a utility company always provides electric power.

  • 8/10/2019 101816212-Oracle

    7/80

    7

    Responsibilities of Database Administrators

    Each database requires at least one database administrator (DBA). An Oracle Database system can be large and can

    have many users. Therefore, database administration is sometimes not a one-person job, but a job for a group ofDBAs who share responsibility.

    A database administrator's responsibilities can include the following tasks:

    Installing and upgrading the Oracle Database server and application tools Allocating system storage and planning future storage requirements for the database system Creating primary database storage structures (tablespaces) after application developers have designed an

    application Creating primary objects (tables, views, indexes) once application developers have designed an application Modifying the database structure, as necessary, from information given by application developers Enrolling users and maintaining system security

    Ensuring compliance with Oracle license agreements Controlling and monitoring user access to the database Monitoring and optimizing the performance of the database Planning for backup and recovery of database information Maintaining archived data on tape Backing up and restoring the database Contacting Oracle for technical support

    Creating the Database

    This section presents the steps involved when you create a database manually. These steps should be followed in theorder presented. Before you create the database make sure you have done the planning about the size of the

    database, number of tablespaces and redo log files you want in the database.

    Regarding the size of the database you have to first find out how many tables are going to be created in the databaseand how much space they will be occupying for the next 1 year or 2. The best thing is to start with some specific sizeand later on adjust the size depending upon the requirement

    Plan the layout of the underlying operating system files your database will comprise. Proper distribution of files canimprove database performance dramatically by distributing the I/O during file access. You can distribute I/O in severalways when you install Oracle software and create your database. For example, you can place redo log files onseparate disks or use striping. You can situate datafiles to reduce contention. And you can control data density(number of rows to a data block).

    Select the standard database block size. This is specified at database creation by the DB_BLOCK_SI ZEinitializationparameter and cannot be changed after the database is created. For databases, block size of 4K or 8K is widely used

    Before you start creating the Database it is best to write down the specification and then proceed

    The examples shown in these steps create an example database my_i ca_db

    Let us create a database my_i ca_dbwith the following specification

    Database name and System IdentifierSI D = myi cadbDB_NAME = myi cadb

    TABLESPACES(we will have 5 tablespaces in this database. With 1 datafile in each tablespace)

    Tabl espace Name Dat af i l e Si ze

  • 8/10/2019 101816212-Oracle

    8/80

    8

    syst em / u01/ or acl e/ or adat a/ myi ca/ sys. dbf 250Muser s / u01/ or acl e/ or adat a/ myi ca/ usr . dbf 100Mundotbs / u01/ oracl e/ oradata/ myi ca/ undo. dbf 100Mt emp / u01/ oracl e/ oradata/ myi ca/ t emp. dbf 100Mi ndex_dat a / u01/ or acl e/ or adat a/ myi ca/ i ndx. dbf 100M

    sysaux / u01/ or acl e/ or adat a/ myi ca/ sysaux. dbf 100M

    LOGFILES(we will have 2 log groups in the database)

    Logfile Group Member SizeGr oup 1 / u01/ or acl e/ or adat a/ myi ca/ l og1. or a 50M

    Gr oup 2 / u01/ or acl e/ or adat a/ myi ca/ l og2. or a 50MCONTROL FI LE / u01/ or acl e/ or adat a/ myi ca/ cont r ol . or aPARAMETER FI LE / u01/ oracl e/ dbs/ i ni t myi cadb. ora

    (rememer the parameter file name should of the format i ni t . or aand it should be in ORACLE_ HOME/ dbs

    directory in Unix o/s and ORACLE_HOME/ dat abasedirectory in windows o/s)

    Now let us start creating the database.

    Step 1: Login to oracle account and make directories for your database.

    $mkdi r / u01/ or acl e/ or adat a/ myi ca$mkdi r / u01/ oracl e/ oradata/ myi ca/ bdump$mkdi r / u01/ oracl e/ oradata/ myi ca/ udump$mkdi r / u01/ oracl e/ oradata/ myi ca/ cdump

    Step 2: Create the parameter file by copying the default template (i ni t . or a) and set the required parameters

    $cd / u01/ or acl e/ dbs $cp i ni t . or a i ni t myi cadb. or a

    Now open the parameter file and set the following parameters

    $vi i ni t myi cadb. or a

    DB_NAME=myi cadbDB_BLOCK_SI ZE=8192CONTROL_FI LES=/ u01/ or acl e/ oradata/ myi ca/ cont r ol . or aBACKGROUND_DUMP_DEST=/ u01/ or acl e/ or adat a/ myi ca/ bdumpUSER_DUMP_DEST=/ u01/ or acl e/ or adat a/ myi ca/ udumpCORE_DUMP_DEST=/ u01/ or acl e/ or adat a/ myi ca/ cdump

    UNDO_TABLESPACE=undot bs UNDO_MANAGEMENT=AUTO

    After entering the above parameters save the file by pressing Esc : wq

    Step 3: Now set ORACLE_SID environment variable and start the instance.

    $expor t ORACLE_SI D=myi cadb$sql pl us Ent er User : / as sysdbaSQL>st ar t up nomount

    Step 4: Give the create database command

    Here I am not specfying optional setting such as language, characterset etc. For thesesettings oracle will use the default values. I am giving the barest command to create thedatabase to keep it simple.

    The command to create the database is

  • 8/10/2019 101816212-Oracle

    9/80

    9

    SQL>cr eat e database myi cadbdat af i l e / u01/ or acl e/ or adat a/ myi ca/ sys. dbf si ze 250Msysaux dat af i l e / u01/ or acl e/ or adat a/ myi ca/ sysaux. dbf si ze 100mundo t abl espace undot bs

    dat af i l e / u01/ or acl e/ or adat a/ myi ca/ undo. dbf si ze 100m def aul t t emporary t abl espace t emp

    t empf i l e / u01/ or acl e/ or adat a/ myi ca/ t mp. dbf si ze 100m l ogf i l e

    gr oup 1 / u01/ or acl e/ or adat a/ myi ca/ l og1. or a si ze 50m, gr oup 2 / u01/ or acl e/ or adat a/ myi ca/ l og2. or a si ze 50m;

    After the command fishes you will get the following message

    Dat abase cr eat ed.

    If you are getting any errors then see accompanying messages. If no accompanying messages are shown then you

    have to see the alert_myicadb.log file located in BACKGROUND_DUMP_DESTdirectory, which will show the exactreason why the command has failed. After you have rectified the error please delete all created files in/ u01/ or acl e/ or adat a/ myi cadirectory and again give the above command.

    Step 5: After the above command finishes, the database will get mounted and opened. Nowcreate additional tablespaces

    To create USERStablespaceSQL>cr eat e t abl espace user s

    dat af i l e / u01/ or acl e/ or adat a/ myi ca/ usr . dbf si ze 100M;

    To create I NDEX_DATAtablespace

    SQL>cr eat e t abl espace i ndex_dat adat af i l e / u01/ or acl e/ or adat a/ myi ca/ i ndx. dbf si ze 100M

    Step 6: To populate the database with data dictionaries and to install procedural options executethe following scripts

    First execute the CATALOG. SQLscript to install data dictionariesSQL>@/ u01/ oracl e/ r dbms/ admi n/ catal og. sql

    The above script will take several minutes. After the above script is finished run the CATPROC. SQLscript toinstall procedural option.SQL>@/ u01/ oracl e/ r dbms/ admi n/ cat proc. sql

    This script will also take several minutes to complete.

    Step 7: Now change the passwords for SYSand SYSTEMaccount, since the default passwordschange_on_i nst al l and manager are known by everybody.

    SQL>al t er user sys i dent i f i ed by myi ca;

    SQL>al t er user syst em i dent i f i ed by myi ca;

    Step 8: Create Additional user accounts. You can create as many user account as you like. Let us create the popularaccount SCOTT.

    SQL>cr eate user scot t def aul t t abl espace usersi dent i f i ed by ti ger quot a 10M on user s;

    SQL>grant connect t o scot t ;

    Step 9: Add this database SI Din l i s tener . orafile and restart the listener process.

  • 8/10/2019 101816212-Oracle

    10/80

    10

    $cd / u01/ oracl e/ net work/ admi n

    $vi l i s tener . ora

    (This file will already contain sample entries. Copy and paste one sample entry and edit the SI Dsetting)

    LI STENER = ( DESCRI PTI ON_LI ST = ( DESCRI PTI ON =

    ( ADDRESS =( PROTOCOL = TCP) ( HOST=200. 200. 100. 1) ( PORT = 1521) ) )

    ) SI D_LI ST_LI STENER = ( SI D_LI ST = ( SI D_DESC = ( SI D_NAME = PLSExt Pr oc)

    ( ORACLE_HOME =/ u01/ or acl e) ( PROGRAM = ext proc)

    )

    ( SI D_DESC = ( SI D_NAME=ORCL) ( ORACLE_HOME=/ u01/ or acl e)

    ) #Add t hese l i nes

    ( SI D_DESC = ( SI D_NAME=myi cadb)

    ( ORACLE_HOME=/ u01/ or acl e) )

    )

    Save the file by pressing Esc : wq

    Now restart the listener process.

    $l snrct l stop$l snrct l s tart

    Step 10: It is recommended to take a full database backup after you just created the database.How to take backup is deal in the Backup and Recovery Section.

    Congratualtions you have just created an oracle database.

  • 8/10/2019 101816212-Oracle

    11/80

    11

    Managing Tablespaces and Datafiles

    Using multiple tablespaces provides several Advantages

    Separate user data from data dictionary data to reduce contention among dictionary objects and schema

    objects for the same datafiles.

    Separate data of one application from the data of another to prevent multiple applications from being

    affected if a tablespace must be taken offline.

    Store different the datafiles of different tablespaces on different disk drives to reduce I/O contention.

    Take individual tablespaces offline while others remain online, providing better overall availability.

    Creating New Tablespaces

    You can create Locally Managed or Dictionary Managed Tablespaces. In prior versions of Oracle only Dictionary

    managed Tablespaces were available but from Oracle ver. 8i you can also create Locally managed tablespaces. The

    advantages of locally managed tablespaces are

    Locally managed tablespaces track all extent information in the tablespace itself by using bitmaps, resulting in the

    following benefits:

    Concurrency and speed of space operations is improved, because space allocations and deallocations modify

    locally managed resources (bitmaps stored in header files) rather than requiring centrally managed

    resources such as enqueues

    Performance is improved, because recursive operations that are sometimes required during dictionary-

    managed space allocation are eliminated

    To create a locally managed tablespace give the following command

    SQL> CREATE TABLESPACE i ca_l mt s DATAFI LE ' / u02/ oracl e/ i ca/ i ca01. dbf ' SI ZE 50M

    EXTENT MANAGEMENT LOCAL AUTOALLOCATE;

    AUTOALLOCATE causes the tablespace to be system managed with a minimum extent size of 64K.

    The alternative to AUTOALLOCATE is UNIFORM. which specifies that the tablespace is managed with extents of

    uniform size. You can specify that size in the SIZE clause of UNIFORM. If you omit SIZE, then the default size is 1M.

    The following example creates a Locally managed tablespace with uniform extent size of 256K

    SQL> CREATE TABLESPACE i ca_l mt DATAFI LE ' / u02/ oracl e/ i ca/ i ca01. dbf ' SI ZE 50M

    EXTENT MANAGEMENT LOCAL UNI FORM SI ZE 256K;

    To Create Dictionary Managed Tablespace

    SQL> CREATE TABLESPACE i ca_l mt DATAFI LE ' / u02/ oracl e/ i ca/ i ca01. dbf ' SI ZE 50M

    EXTENT MANAGEMENT DI CTI ONARY;

  • 8/10/2019 101816212-Oracle

    12/80

    12

    Bigfile Tablespaces (Introduced in Oracle Ver. 10g)

    A bigfile tablespaceis a tablespace with a single, but very large (up to 4G blocks) datafile. Traditionalsmallfile tablespaces, in contrast, can contain multiple datafiles, but the files cannot be as large. Bigfiletablespaces can reduce the number of datafiles needed for a database.

    To create a bigfile tablespace give the following command

    SQL> CREATE BI GFI LE TABLESPACE i ca_bi gt bs

    DATAFI LE ' / u02/ or acl e/ i ca/ bi gt bs01. dbf ' SI ZE 50G;

    To Extend the Size of a tablespace

    Option 1

    You can extend the size of a tablespace by increasing the size of an existing datafile by typing the following

    command

    SQL> al t er dat abase i ca dat af i l e / u01/ or acl e/ dat a/ i cat bs01. dbf r esi ze 100M;

    This will increase the size from 50M to 100M

    Option 2

    You can also extend the size of a tablespace by adding a new datafile to a tablespace. This is useful if the size of

    existing datafile is reached o/s file size limit or the drive where the file is existing does not have free space. To add a

    new datafile to an existing tablespace give the following command.

    SQL> al t er t abl espace add dat af i l e / u02/ or acl e/ i ca/ i cat bs02. dbf si ze 50M;

    Option 3

    You can also use auto extend feature of datafile. In this, Oracle will automatically increase the size of a datafile

    whenever space is required. You can specify by how much size the file should increase and Maximum size to which itshould extend.

    To make a existing datafile auto extendable give the following command

    SQL> al t er dat abase dat af i l e / u01/ or acl e/ i ca/ i cat bs01. dbf aut o ext end ON next

    5M maxsi ze 500M;

    You can also make a datafile auto extendable while creating a new tablespace itself by giving the following

    command.

    SQL> cr eat e t abl espace i ca dat af i l e / u01/ or acl e/ i ca/ i cat bs01. dbf si ze 50M

    auto ext end ON next 5M maxsi ze 500M;

  • 8/10/2019 101816212-Oracle

    13/80

    13

    To decrease the size of a tablespace

    You can decrease the size of tablespace by decreasing the datafile associated with it. You decrease a datafile only up

    to size of empty space in it. To decrease the size of a datafile give the following command

    SQL> al t er dat abase dat af i l e / u01/ or acl e/ i ca/ i cat bs01. dbf r esi ze 30M;

    Coalescing Tablespaces

    A free extent in a dictionary-managed tablespace is made up of a collection of contiguous free blocks. When

    allocating new extents to a tablespace segment, the database uses the free extent closest in size to the required

    extent. In some cases, when segments are dropped, their extents are deallocated and marked as free, but adjacent

    free extents are not immediately recombined into larger free extents. The result is fragmentation that makes

    allocation of larger extents more difficult.

    You should often use the ALTER TABLESPACE . . . COALESCEstatement to manually coalesce any adjacent free

    extents. To Coalesce a tablespace give the following command

    SQL> alter tablespace ica coalesce;

    Taking tablespaces Offline or Online

    You can take an online tablespace offline so that it is temporarily unavailable for general use. The rest of the

    database remains open and available for users to access data. Conversely, you can bring an offline tablespace online

    to make the schema objects within the tablespace available to database users. The database must be open to alter

    the availability of a tablespace.

    To alter the availability of a tablespace, use the ALTER TABLESPACE statement. You must have the ALTER

    TABLESPACE or MANAGE TABLESPACE system privilege.

    To Take a Tablespace Offline give the following command

    SQL>al t er t abl espace i ca of f l i ne;

    To again bring it back online give the following command.

    SQL>al t er t abl espace i ca onl i ne;

    To take individual datafile offline type the following command

  • 8/10/2019 101816212-Oracle

    14/80

    14

    SQL>al t er dat abase dat af i l e / u01/ or acl e/ i ca/ i ca_t bs01. dbf of f l i ne;

    Again to bring it back online give the following command

    SQL> al t er dat abase dat af i l e / u01/ or acl e/ i ca/ i ca_t bs01. dbf onl i ne;

    Note: You cant take individual datafiles offline it the database is running in NOARCHIVELOG mode. If the datafile

    has become corrupt or missing when the database is running in NOARCHIVELOG mode then you can only drop it by

    giving the following command

    SQL>al t er dat abase dat af i l e / u01/ or acl e/ i ca/ i ca_t bs01. dbf

    of f l i ne f or dr op;

    Making a Tablespace Read only.

    Making a tablespace read-only prevents write operations on the datafiles in the tablespace. The primary purpose of

    read-only tablespaces is to eliminate the need to perform backup and recovery of large, static portions of a

    database. Read-only tablespaces also provide a way to protecting historical data so that users cannot modify it.

    Making a tablespace read-only prevents updates on all tables in the tablespace, regardless of a user's update

    privilege level.

    To make a tablespace read only

    SQL>al t er t abl espace i ca r ead onl y

    Again to make it read write

    SQL>al t er t abl espace i ca r ead wr i t e;

    Renaming Tablespaces

    Using the RENAME TO clause of the ALTER TABLESPACE, you can rename a permanent or temporary tablespace. For

    example, the following statement renames the users tablespace:

    ALTER TABLESPACE user s RENAME TO user st s;

    The following affect the operation of this statement:

    The COMPATIBLE parameter must be set to 10.0 or higher.

    If the tablespace being renamed is the SYSTEM tablespace or the SYSAUX tablespace, then it will not be

    renamed and an error is raised.

    If any datafile in the tablespace is offline, or if the tablespace is offline, then the tablespace is not renamed

    and an error is raised.

    Dropping Tablespaces

    You can drop a tablespace and its contents (the segments contained in the tablespace) from the database if the

    tablespace and its contents are no longer required. You must have the DROP TABLESPACE system privilege to drop a

    tablespace.

  • 8/10/2019 101816212-Oracle

    15/80

    15

    Caution:Once a tablespace has been dropped, the data in the tablespace is not recoverable. Therefore, make sure

    that all data contained in a tablespace to be dropped will not be required in the future. Also, immediately before and

    after dropping a tablespace from a database, back up the database completely

    To drop a tablespace give the following command.

    SQL> drop t abl espace i ca;

    This will drop the tablespace only if it is empty. If it is not empty and if you want to drop it anyhow then add the

    following keyword

    SQL>dr op t abl espace i ca i ncl udi ng cont ent s;

    This will drop the tablespace even if it is not empty. But the datafiles will not be deleted you have to use operating

    system command to delete the files.

    But If you include datafiles keyword then, the associated datafiles will also be deleted from the disk.

    SQL>dr op t abl espace i ca i ncl udi ng cont ent s and dat af i l es;

    Temporary Tablespace

    Temporary tablespace is used for sorting large tables. Every database should have one temporary tablespace. To

    create temporary tablespace give the following command.

    SQL>cr eate t emporary t abl espace t emp t empf i l e / u01/ oracl e/ data/ i ca_t emp. dbf si ze 100M

    ext ent management l ocal uni f orm si ze 5M;

    The extent management clause is optional for temporary tablespaces because all temporary tablespaces are created

    with locally managed extents of a uniform size. The AUTOALLOCATEclause is not allowed for temporarytablespaces.

    Increasing or Decreasing the size of a Temporary Tablespace

    You can use the resize clause to increase or decrease the size of a temporary tablespace. The following statement

    resizes a temporary file:

    SQL>ALTER DATABASE TEMPFI LE ' / u02/ oracl e/ dat a/ l mt emp02. dbf ' RESI ZE 18M;

    The following statement drops a temporary file and deletes the operating system file:

    SQL> ALTER DATABASE TEMPFI LE ' / u02/ or acl e/ data/ l mt emp02. dbf ' DROP I NCLUDI NG

    DATAFI LES;

    Tablespace Groups

    A tablespace groupenables a user to consume temporary space from multiple tablespaces. A tablespace group has

    the following characteristics:

  • 8/10/2019 101816212-Oracle

    16/80

    16

    It contains at least one tablespace. There is no explicit limit on the maximum number of tablespaces that are

    contained in a group.

    It shares the namespace of tablespaces, so its name cannot be the same as any tablespace.

    You can specify a tablespace group name wherever a tablespace name would appear when you assign a

    default temporary tablespace for the database or a temporary tablespace for a user.

    You do not explicitly create a tablespace group. Rather, it is created implicitly when you assign the first temporarytablespace to the group. The group is deleted when the last temporary tablespace it contains is removed from it.

    Using a tablespace group, rather than a single temporary tablespace, can alleviate problems caused where one

    tablespace is inadequate to hold the results of a sort, particularly on a table that has many partitions. A tablespace

    group enables parallel execution servers in a single parallel operation to use multiple temporary tablespaces.

    The view DBA_TABLESPACE_GROUPS lists tablespace groups and their member tablespaces.

    Creating a Temporary Tablespace Group

    You create a tablespace group implicitly when you include theTABLESPACE GROUPclause in the CREATETEMPORARY TABLESPACEor ALTER TABLESPACEstatement and the specified tablespace group does notcurrently exist.

    For example, if neither group1nor group2exists, then the following statements create those groups, each of whichhas only the specified tablespace as a member:

    CREATE TEMPORARY TABLESPACE i ca_t emp2 TEMPFI LE ' / u02/ oracl e/ i ca/ i ca_t emp. dbf 'SI ZE 50M

    TABLESPACE GROUP gr oup1;

    ALTER TABLESPACE i ca_t emp2 TABLESPACE GROUP gr oup2;

    Assigning a Tablespace Group as the Default Temporary Tablespace

    Use the ALTER DATABASE . . . DEFAULTTEMPORARYTABLESPACEstatement to assign a tablespace group asthe default temporary tablespace for the database. For example:

    ALTER DATABASE sampl e DEFAULT TEMPORARY TABLESPACE gr oup2;

    Diagnosing and Repairing Locally Managed Tablespace Problems

    To diagnose and repair corruptions in Locally Managed Tablespaces Oracle has supplied a package called

    DBMS_SPACE_ADMIN. This package has many procedures described below:

    Procedure Description

    SEGMENT_VERI FY Verifies the consistency of the extent map of the segment.

    SEGMENT_CORRUPT Marks the segment corrupt or valid so that appropriate error recovery can

  • 8/10/2019 101816212-Oracle

    17/80

    17

    Procedure Description

    be done. Cannot be used for a locally managed SYSTEMtablespace.

    SEGMENT_DROP_CORRUPT Drops a segment currently marked corrupt (without reclaiming space).

    Cannot be used for a locally managed SYSTEMtablespace.

    SEGMENT_DUMP Dumps the segment header and extent map of a given segment.

    TABLESPACE_VERI FY Verifies that the bitmaps and extent maps for the segments in the

    tablespace are in sync.

    TABLESPACE_REBUI LD_BI TMAPS Rebuilds the appropriate bitmap. Cannot be used for a locally managed

    SYSTEMtablespace.

    TABLESPACE_FI X_BI TMAPS Marks the appropriate data block address range (extent) as free or used in

    bitmap. Cannot be used for a locally managed SYSTEMtablespace.

    TABLESPACE_REBUI LD_QUOTAS Rebuilds quotas for given tablespace.

    TABLESPACE_MI GRATE_FROM_LOCAL Migrates a locally managed tablespace to dictionary-managed tablespace.

    Cannot be used to migrate a locally managed SYSTEMtablespace to a

    dictionary-managed SYSTEMtablespace.

    TABLESPACE_MI GRATE_TO_LOCAL Migrates a tablespace from dictionary-managed format to locally managedformat.

    TABLESPACE_RELOCATE_BI TMAPS Relocates the bitmaps to the destination specified. Cannot be used for a

    locally managed system tablespace.

    TABLESPACE_FI X_SEGMENT_STATES Fixes the state of the segments in a tablespace in which migration was

    aborted.

    Be careful using the above procedures if not used properly you will corrupt your database. Contact Oracle Support

    before using these procedures.

    Following are some of the Scenarios where you can use the above procedures

    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.

  • 8/10/2019 101816212-Oracle

    18/80

    18

    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.

    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 overlapsare 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 onlyone 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.

    Scenario 5: Migrating from a Dictionary-Managed to a Locally Managed Tablespace

    To migrate a dictionary-managed tablespace to a locally managed tablespace. You use the

    TABLESPACE_MIGRATE_TO_LOCAL procedure.

  • 8/10/2019 101816212-Oracle

    19/80

    19

    For example if you want to migrate a dictionary managed tablespace ICA2 to Locally managed then give the

    following command.

    EXEC DBMS_SPACE_ADMI N. TABLESPACE_MI GRATE_TO_LOCAL ( ' i ca2' ) ;

    Transporting Tablespaces

    You can use the transportable tablespaces feature to move a subset of an Oracle Database and "plug" it in to

    another Oracle Database, essentially moving tablespaces between the databases. The tablespaces being transported

    can be either dictionary managed or locally managed. Starting with Oracle9i, the transported tablespaces are not

    required to be of the same block size as the target database standard block size.

    Moving data using transportable tablespaces is much faster than performing either an export/import or unload/load

    of the same data. This is because the datafiles containing all of the actual data are simply copied to the destinationlocation, and you use an import utility to transfer only the metadata of the tablespace objects to the new database.

    Starting with Oracle Database 10g, you can transport tablespaces across platforms. This functionality can be used to

    Allow a database to be migrated from one platform to another. However not all platforms are supported. To see

    which platforms are supported give the following query.

    SQL> COLUMN PLATFORM_NAME FORMAT A30

    SQL> SELECT * FROM V$TRANSPORTABLE_PLATFORM;

    PLATFORM_I D PLATFORM_NAME ENDI AN_FORMAT

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

    1 Sol ar i s[ t m] OE ( 32- bi t ) Bi g

    2 Sol ar i s[ t m] OE ( 64- bi t ) Bi g

    7 Mi cr osof t Wi ndows NT Li t t l e

    10 Li nux I A ( 32- bi t ) Li t t l e

    6 AI X- Based Syst ems ( 64- bi t ) Bi g

    3 HP- UX ( 64- bi t ) Bi g

    5 HP Tru64 UNI X Li t t l e

    4 HP- UX I A ( 64- bi t ) Bi g

    11 Li nux I A ( 64- bi t ) Li t t l e

    15 HP Open VMS Li t t l e

    10 rows sel ect ed.

    If the source platform and the target platform are of different endianness, then an additional step must be done on

    either the source or target platform to convert the tablespace being transported to the target format. If they are of

  • 8/10/2019 101816212-Oracle

    20/80

    20

    the same endianness, then no conversion is necessary and tablespaces can be transported as if they were on the

    same platform.

    Important: Before a tablespace can be transported to a different platform, the datafile header must identify the

    platform to which it belongs. In an Oracle Database with compatibility set to 10.0.0 or higher, you can accomplish

    this by making the datafile read/write at least once.

    SQL> al t er t abl espace i ca r ead onl y;

    Then,

    SQL> al t er t abl espace i ca read wr i t e;

    Procedure for transporting tablespaces

    To move or copy a set of tablespaces, perform the following steps.

    1. For cross-platform transport, check the endian format of both platforms by querying theV$TRANSPORTABLE_PLATFORMview.

    If you are transporting the tablespace set to a platform different from the source platform, then determine if

    the source and target platforms are supported and their endianness. If both platforms have the same

    endianness, no conversion is necessary. Otherwise you must do a conversion of the tablespace set either at

    the source or target database.

    Ignore this step if you are transporting your tablespace set to the same platform.

    2. Pick a self-contained set of tablespaces.3. Generate a transportable tablespace set.

    A transportable tablespace set consists of datafiles for the set of tablespaces being transported and an

    export file containing structural information for the set of tablespaces.

    If you are transporting the tablespace set to a platform with different endianness from the source platform,

    you must convert the tablespace set to the endianness of the target platform. You can perform a source-side

    conversion at this step in the procedure, or you can perform a target-side conversion as part of step 4.

    4. Transport the tablespace set.

    Copy the datafiles and the export file to the target database. You can do this using any facility for copying

    flat files (for example, an operating system copy utility, ftp, the DBMS_FI LE_COPYpackage, or publishing on

    CDs).

    If you have transported the tablespace set to a platform with different endianness from the source platform,

    and you have not performed a source-side conversion to the endianness of the target platform, you should

    perform a target-side conversion now.

    5. Plug in the tablespace.

    Invoke the Export utility to plug the set of tablespaces into the target database.

  • 8/10/2019 101816212-Oracle

    21/80

    21

    Transporting Tablespace Example

    These steps are illustrated more fully in the example that follows, where it is assumed the following datafilesand tablespaces exist:

    Tablespace Datafile:i ca_sal es_1 /u01/oracle/oradata/ica_salesdb/ica_sales_101.dbf

    i ca_sal es_2 /u01/oracle/oradata/ica_salesdb/ica_sales_201.dbf

    Step 1: Determine if Platforms are Supported and Endianness

    This step is only necessary if you are transporting the tablespace set to a platform different from the source

    platform. If i ca_sal es_1and i ca_sal es_2were being transported to a different platform, you can executethe following query on both platforms to determine if the platforms are supported and their endian formats:

    SELECT d. PLATFORM_NAME, ENDI AN_FORMATFROM V$TRANSPORTABLE_PLATFORM t p, V$DATABASE dWHERE t p. PLATFORM_NAME = d. PLATFORM_NAME;

    The following is the query result from the source platform:

    PLATFORM_NAME ENDI AN_FORMAT- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    Sol ar i s[ t m] OE ( 32- bi t ) Bi g

    The following is the result from the target platform:

    PLATFORM_NAME ENDI AN_FORMAT- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Mi cr osof t Wi ndows NT Li t t l e

    You can see that the endian formats are different and thus a conversion is necessary for transporting thetablespace set.

    Step 2: Pick a Self-Contained Set of Tablespaces

    There may be logical or physical dependencies between objects in the transportable set and those outside ofthe set. You can only transport a set of tablespaces that is self-contained. That is it should not have tableswith foreign keys referring to primary key of tables which are in other tablespaces. It should not have tableswith some partitions in other tablespaces. To find out whether the tablespace is self contained do thefollowing

    EXECUTE DBMS_TTS. TRANSPORT_SET_CHECK( ' i ca_sal es_1, i ca_sal es_2' , TRUE) ;

    After executing the above give the following query to see whether any violations are there.

  • 8/10/2019 101816212-Oracle

    22/80

    22

    SQL> SELECT * FROM TRANSPORT_SET_VI OLATI ONS;

    VI OLATI ONS

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

    Const r ai nt DEPT_FK bet ween t abl e SAMI . EMP i n t abl espace I CA_SALES_1 and t abl e

    SAMI . DEPT i n t abl espace OTHER

    Par t i t i oned t abl e SAMI . SALES i s par t i al l y cont ai ned i n t he t r anspor t abl e set

    These violations must be resolved before i ca_sal es_1and i ca_sal es_2are transportable

    Step 3: Generate a Transportable Tablespace Set

    After ensuring you have a self-contained set of tablespaces that you want to transport, generate a transportable

    tablespace set by performing the following actions:

    Make all tablespaces in the set you are copying read-only.

    SQL> ALTER TABLESPACE i ca_sal es_1 READ ONLY;

    Tablespace altered.

    SQL> ALTER TABLESPACE i ca_sal es_2 READ ONLY;

    Tablespace altered.

    Invoke the Export utility on the host system and specify which tablespaces are in the transportable set.

    SQL> HOST

    $ exp syst em/ passwor d FI LE=/ u01/ or acl e/ expdat . dmpTRANSPORT_TABLESPACES = i ca_sal es_1, i ca_sal es_2

    If i ca_sal es_1and i ca_sal es_2are being transported to a different platform, and the endianness of theplatforms is different, and if you want to convert before transporting the tablespace set, then convert the

    datafiles composing the i ca_sal es_1and i ca_sal es_2tablespaces. You have to use RMAN utility toconvert datafiles

    $ RMAN TARGET /

    Recover y Manager : Rel ease 10. 1. 0. 0. 0Copyr i ght ( c) 1995, 2003, Or acl e Cor por at i on. Al l r i ght s r eser ved.

    connect ed t o t ar get dat abase: i ca_sal esdb ( DBI D=3295731590)

  • 8/10/2019 101816212-Oracle

    23/80

    23

    Convert the datafiles into a temporary location on the source platform. In this example, assume that the temporary

    location, directory /temp, has already been created. The converted datafiles are assigned names by the system.

    RMAN> CONVERT TABLESPACE i ca_sal es_1, i ca_sal es_2TO PLATFORM ' Mi cr osof t Wi ndows NT' FORMAT ' / t emp/ %U' ;

    St ar t i ng backup at 08- APR- 03usi ng t ar get dat abase cont r ol f i l e i nst ead of r ecover y cat al og

    al l ocat ed channel : ORA_DI SK_1channel ORA_DI SK_1: si d=11 devtype=DI SKchannel ORA_DI SK_1: st ar t i ng dat af i l e conver si oni nput dat af i l e f no=00005 name=/ u01/ or acl e/ or adat a/ i ca_sal esdb/ i ca_sal es_101. dbfconver t ed dat af i l e=/ t emp/ dat a_D- 10_I - 3295731590_TS- ADMI N_TBS_FNO- 5_05ek24v5

    channel ORA_DI SK_1: dataf i l e conver si on compl et e, el apsed t i me: 00: 00: 15channel ORA_DI SK_1: st ar t i ng dat af i l e conver si oni nput dat af i l e f no=00004 name=/ u01/ or acl e/ or adat a/ i ca_sal esdb/ i ca_sal es_101. dbfconver t ed dat af i l e=/ t emp/ dat a_D- 10_I - 3295731590_TS- EXAMPLE_FNO- 4_06ek24vl

    channel ORA_DI SK_1: dataf i l e conver si on compl et e, el apsed t i me: 00: 00: 45

    Fi ni shed backup at 08- APR- 07

    Step 4: Transport the Tablespace Set

    Transport both the datafiles and the export fileof the tablespaces to a place accessible to the target database.

    You can use any facility for copying flat files (for example, an operating system copy utility, ftp, theDBMS_FI LE_TRANSFERpackage, or publishing on CDs).

    Step 5: Plug In the Tablespace Set

    Plug in the tablespaces and integrate the structural information using the Import utility, i mp:

    I MP syst em/ password FI LE=expdat . dmpDATAFI LES=/ i ca_sal esdb/ i ca_sal es_101. dbf , / i ca_sal esdb/ i ca_sal es_201. dbf

    REMAP_SCHEMA=( smi t h: sami ) REMAP_SCHEMA=( wi l l i ams: j ohn)

    The REMAP_SCHEMAparameter changes the ownership of database objects. If you do not specify REMAP_SCHEMA, all

    database objects (such as tables and indexes) are created in the same user schema as in the source database, and

    those users must already exist in the target database. If they do not exist, then the import utility returns an error. In

    this example, objects in the tablespace set owned by smi t hin the source database will be owned by sami in the

    target database after the tablespace set is plugged in. Similarly, objects owned by wi l l i ams in the source database

    will be owned byj ohnin the target database. In this case, the target database is not required to have users smi t h

    and wi l l i ams, but must have users sami andj ohn.

    After this statement executes successfully, all tablespaces in the set being copied remain in read-only mode.Check the import logs to ensure that no error has occurred.

    Now, put the tablespaces into read/write mode as follows:

  • 8/10/2019 101816212-Oracle

    24/80

    24

    ALTER TABLESPACE i ca_sal es_1 READ WRI TE;

    ALTER TABLESPACE i ca_sal es_2 READ WRI TE;

    Viewing Information about Tablespaces and Datafiles

    Oracle has provided many Data dictionaries to view information about tablespaces and datafiles. Some of them are:

    To view information about Tablespaces in a database give the following query

    SQL>sel ect * f r omdba_t abl espacesSQL>sel ect * f r omv$t abl espace;

    To view information about Datafiles

    SQL>sel ect * f r om dba_dat a_f i l es;SQL>sel ect * f r om v$dat af i l e;

    To view information about Tempfiles

    SQL>sel ect * f r om dba_t emp_f i l es;SQL>sel ect * f r om v$t empf i l e;

    To view information about free space in datafiles

    SQL>sel ect * f r omdba_f r ee_space;

    To view information about free space in tempfiles

    SQL>sel ect * f r om V$TEMP_SPACE_HEADER;

    Relocating or Renaming Datafiles

    You can rename datafiles to either change their names or relocate them.

    Renaming or Relocating Datafiles belonging to a Single Tablespace

    To rename or relocate datafiles belonging to a Single Tablespace do the following.

    1. Take the tablespace offline

    2. Rename or Relocate the datafiles using operating system command

    3. Give the ALTER TABLESPACE with RENAME DATAFILE option to change the filenames within the Database.

    4. Bring the tablespace Online

    For Example suppose you have a tablespace users with the following datafiles

  • 8/10/2019 101816212-Oracle

    25/80

    25

    /u01/oracle/ica/usr01.dbf

    /u01/oracle/ica/usr02.dbf

    Now you want to relocate / u01/ or acl e/ i ca/ usr 01. dbf to / u02/ or acl e/ i ca/ usr01. dbf andwant to rename / u01/ or acl e/ i ca/ usr02. dbf to / u01/ or acl e/ i ca/ user s02. dbf then followthe given the steps

    1. Bring the tablespace offline

    SQL> al t er t abl espace user s of f l i ne;

    2. Copy the file to new location using o/s command.

    $cp / u01/ or acl e/ i ca/ usr 01. dbf / u02/ or acl e/ i ca/ usr 01. dbf

    Rename the file / u01/ or acl e/ i ca/ usr02. dbf to / u01/ or acl e/ i ca/ user s02. dbf usingo/s command.

    $mv / u01/ or acl e/ i ca/ usr 02. dbf / u01/ or acl e/ i ca/ user s02. dbf

    3. Now start SQLPLUS and type the following command to rename and relocate these files

    SQL> al t er t abl espace users r ename f i l e / u01/ or acl e/ i ca/ usr01. dbf , / u01/ or acl e/ i ca/ usr02. dbf

    t o / u02/ or acl e/ i ca/ usr01. dbf , / u01/ or acl e/ i ca/ user s02. dbf ;

    4. Now bring the tablespace Online

    SQL> al t er t abl espace users onl i ne;

    Procedure for Renaming and Relocating Datafiles in Multiple Tablespaces

    You can rename and relocate datafiles in one or more tablespaces using the ALTER DATABASE RENAME FI LEstatement. This method is the only choice if you want to rename or relocate datafiles of several tablespaces

    in one operation. You must have the ALTER DATABASEsystem privilege

    To rename datafiles in multiple tablespaces, follow these steps.

    1. Ensure that the database is mounted but closed.

    2. Copy the datafiles to be renamed to their new locations and new names, using the operating system..

    3. Use ALTER DATABASEto rename the file pointers in the database control file.

    For example, the following statement renames the datafiles/ u02/ or acl e/ r bdb1/ sor t 01. dbfand

    / u02/ or acl e/ r bdb1/ user 3. dbfto / u02/ or acl e/ r bdb1/ t emp01. dbfand

    / u02/ or acl e/ r bdb1/ user s03. dbf, respectively:

    ALTER DATABASERENAME FI LE ' / u02/ or acl e/ r bdb1/ sor t 01. dbf ' ,

    ' / u02/ or acl e/ r bdb1/ user 3. dbf '

  • 8/10/2019 101816212-Oracle

    26/80

    26

    TO ' / u02/ or acl e/ r bdb1/ t emp01. dbf ' ,' / u02/ or acl e/ r bdb1/ user s03. dbf ;

    Always provide complete filenames (including their paths) to properly identify the old and new

    datafiles. In particular, specify the old datafile names exactly as they appear in the DBA_DATA_FI LES

    view.

    4. Back up the database. After making any structural changes to a database, always perform animmediate and complete backup.

    5. Start the Database

  • 8/10/2019 101816212-Oracle

    27/80

    27

    Managing REDO LOGFILES

    Every Oracle database must have at least 2 redo logfile groups. Oracle writes all statements except, SELECT

    statement, to the logfiles. This is done because Oracle performs deferred batch writes i.e. it does write changes to

    disk per statement instead it performs write in batches. So in this case if a user updates a row, Oracle will change the

    row in db_buffer_cache and records the statement in the logfile and give the message to the user that row is

    updated. Actually the row is not yet written back to the datafile but still it give the message to the user that row is

    updated. After 3 seconds the row is actually written to the datafile. This is known as deferred batch writes.

    Since Oracle defers writing to the datafile there is chance of power failure or system crash before the row is written

    to the disk. Thats why Oracle writes the statement in redo logfile so that in case of power failure or system crash

    oracle can re-execute the statements next time when you open the database.

    Adding a New Redo Logfile Group

    To add a new Redo Logfile group to the database give the following command

    SQL>al t er database add l ogf i l e gr oup 3

    / u01/ or acl e/ i ca/ l og3. or a si ze 10M;

    Note: You can add groups to a database up to the MAXLOGFILES setting you have specified at the time of creating

    the database. If you want to change MAXLOGFILE setting you have to create a new controlfile.

    Adding Members to an existing group

    To add new member to an existing group give the following command

    SQL>al t er dat abase add l ogf i l e member

    / u01/ or acl e/ i ca/ l og11. or a t o gr oup 1;

    Note: You can add members to a group up to the MAXLOGMEMBERS setting you have specified at the time of

    creating the database. If you want to change MAXLOGMEMBERS setting you have create a new controlfile

    Important: Is it strongly recommended that you multiplex logfiles i.e. have at least two log members, one member in

    one disk and another in second disk, in a database.

    Dropping Members from a group

    You can drop member from a log group only if the group is having more than one member and if it is not the current

    group. If you want to drop members from the current group, force a log switch or wait so that log switch occurs and

    another group becomes current. To force a log switch give the following command

    SQL>al t er syst em swi t ch l ogf i l e;

    The following command can be used to drop a logfile member

    SQL>al t er dat abase dr op l ogf i l e member / u01/ or acl e/ i ca/ l og11. or a ;

  • 8/10/2019 101816212-Oracle

    28/80

    28

    Note: When you drop logfiles the files are not deleted from the disk. You have to use O/S command to delete the

    files from disk.

    Dropping Logfile Group

    Similarly, you can also drop logfile group only if the database is having more than two groups and if it is not thecurrent group.

    SQL>al t er database dr op l ogf i l e gr oup 3;

    Note: When you drop logfiles the files are not deleted from the disk. You have to use O/S command to delete the

    files from disk.

    Resizing Logfiles

    You cannot resize logfiles. If you want to resize a logfile create a new logfile group with the new size andsubsequently drop the old logfile group.

    Renaming or Relocating Logfiles

    To Rename or Relocate Logfiles perform the following steps

    For Example, suppose you want to move a logfile from / u01/ or acl e/ i ca/ l og1. or a to

    / u02/ or acl e/ i ca/ l og1. or a , then do the following

    Steps

    1. Shutdown the database

    SQL>shut down i mmedi at e;

    2. Move the logfile from Old location to new location using operating system command

    $mv / u01/ or acl e/ i ca/ l og1. or a / u02/ or acl e/ i ca/ l og1. or a

    3. Start and mount the database

    SQL>st ar t up mount

    4. Now give the following command to change the location in controlfile

    SQL>al t er dat abase r ename f i l e / u01/ or acl e/ i ca/ l og1. or a t o

    / u02/ or acl e/ i ca/ l og2. or a ;

    5. Open the database

  • 8/10/2019 101816212-Oracle

    29/80

    29

    SQL>al t er dat abase open;

    Clearing REDO LOGFILES

    A redo log file might become corrupted while the database is open, and ultimately stop database activity because

    archiving cannot continue. In this situation the ALTER DATABASE CLEAR LOGFI LEstatement can be usedreinitialize the file without shutting down the database.

    The following statement clears the log files in redo log group number 3:

    ALTER DATABASE CLEAR LOGFI LE GROUP 3;

    This statement overcomes two situations where dropping redo logs is not possible:

    If there are only two log groups

    The corrupt redo log file belongs to the current group

    If the corrupt redo log file has not been archived, use the UNARCHI VEDkeyword in the statement.

    ALTER DATABASE CLEAR UNARCHI VED LOGFI LE GROUP 3;

    This statement clears the corrupted redo logs and avoids archiving them. The cleared redo logs are available for use

    even though they were not archived.

    If you clear a log file that is needed for recovery of a backup, then you can no longer recover from that backup. The

    database writes a message in the alert log describing the backups from which you cannot recover

    Viewing Information About Logfiles

    To See how many logfile groups are there and their status type the following query.

    SQL>SELECT * FROM V$LOG;

    GROUP# THREAD# SEQ BYTES MEMBERS ARC STATUS FI RST_CHANGE# FI RST_TI M- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    1 1 20605 1048576 1 YES ACTI VE 61515628 21- J UN- 072 1 20606 1048576 1 NO CURRENT 41517595 21- J UN- 07

    3 1 20603 1048576 1 YES I NACTI VE 31511666 21- J UN- 074 1 20604 1048576 1 YES I NACTI VE 21513647 21- J UN- 07

    To See how many members are there and where they are located give the following query

    SQL>SELECT * FROM V$LOGFI LE;

    GROUP# STATUS MEMBER- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    1 / U01/ ORACLE/ I CA/ LOG1. ORA2 / U01/ ORACLE/ I CA/ LOG2. ORA

  • 8/10/2019 101816212-Oracle

    30/80

    30

    Managing Control Files

    Every Oracle Database has a control file, which is a small binary file that records the physical structure ofthe database. The control file includes:

    The database name

    Names and locations of associated datafiles and redo log files

    The timestamp of the database creation

    The current log sequence number

    Checkpoint information

    It is strongly recommended that you multiplex control files i.e. Have at least two control files one in one hard disk

    and another one located in another disk, in a database. In this way if control file becomes corrupt in one disk the

    another copy will be available and you dont have to do recovery of control file.

    You can multiplex control file at the time of creating a database and later on also. If you have not multiplexed

    control file at the time of creating a database you can do it now by following given procedure.

    Multiplexing Control File

    Steps:

    1. Shutdown the Database.

    SQL>SHUTDOWN I MMEDI ATE;

    2. Copy the control file from old location to new location using operating system command. For example.

    $cp / u01/ or acl e/ i ca/ cont r ol . or a / u02/ or acl e/ i ca/ cont r ol . or a

    3. Now open the parameter file and specify the new location like this

    CONTROL_FI LES=/ u01/ or acl e/ i ca/ cont r ol . or a

    Change it to

    CONTROL_FI LES=/ u01/ or acl e/ i ca/ cont r ol . or a, / u02/ or acl e/ i ca/ cont r ol . or a

    4. Start the Database

  • 8/10/2019 101816212-Oracle

    31/80

    31

    Now Oracle will start updating both the control files and, if one control file is lost you can copy it from

    another location.

    Changing the Name of a Database

    If you ever want to change the name of database or want to change the setting of MAXDATAFI LES,MAXLOGFI LES, MAXLOGMEMBERSthen you have to create a new control file.

    Creating A New Control File

    Follow the given steps to create a new controlfile

    Steps

    1. First generate the create controlfile statement

    SQL>al t er dat abase backup cont r ol f i l e t o t r ace;

    After giving this statement oracle will write the CREATECONTROLFI LEstatement in a trace file. The trace

    file will be randomly named something like ORA23212.TRCand it is created in USER_DUMP_DEST

    directory.

    2. Go to the USER_DUMP_DESTdirectory and open the latest trace file in text editor. This file will contain theCREATECONTROLFI LEstatement. It will have two sets of statement one with RESETLOGSand anotherwithout RESETLOGS. Since we are changing the name of the Database we have to use RESETLOGSoption

    of CREATECONTROLFI LEstatement. Now copy and paste the statement in a file. Let it be c. sql

    3. Now open the c.sql file in text editor and set the database name from ica to prod shown in an example below

    CREATE CONTROLFI LE

    SET DATABASE pr od

    LOGFI LE GROUP 1 ( ' / u01/ or acl e/ i ca/ r edo01_01. l og' ,

    ' / u01/ or acl e/ i ca/ r edo01_02. l og' ) ,

    GROUP 2 ( ' / u01/ or acl e/ i ca/ r edo02_01. l og' ,

    ' / u01/ or acl e/ i ca/ r edo02_02. l og' ) ,

    GROUP 3 ( ' / u01/ or acl e/ i ca/ r edo03_01. l og' ,

    ' / u01/ or acl e/ i ca/ r edo03_02. l og' )

    RESETLOGS

    DATAFI LE ' / u01/ oracl e/ i ca/ syst em01. dbf ' SI ZE 3M,

    ' / u01/ or acl e/ i ca/ r bs01. dbs' SI ZE 5M,

    ' / u01/ or acl e/ i ca/ user s01. dbs' SI ZE 5M,

  • 8/10/2019 101816212-Oracle

    32/80

    32

    ' / u01/ or acl e/ i ca/ t emp01. dbs' SI ZE 5M

    MAXLOGFI LES 50

    MAXLOGMEMBERS 3

    MAXLOGHI STORY 400

    MAXDATAFI LES 200

    MAXI NSTANCES 6

    ARCHI VELOG;

    4. Start and do not mount the database.

    SQL>STARTUP NOMOUNT;

    5. Now execute c.sql script

    SQL> @/ u01/ oracl e/ c. sql

    6. Now open the database with RESETLOGS

    SQL>ALTER DATABASE OPEN RESETLOGS;

    Cloning an Oracle Database.

    You have a Production database running in one server. The company management wants to develop some new

    modules and they have hired some programmers to do that. Now these programmers require access to the

    Production database and they want to make changes to it. You as a DBA cant give direct access to Production

    database so you want to create a copy of this database on another server and wants to give developers access to it.

    Let us see an example of cloning a database

    We have a database running the production server with the following files

    PARAMETER FI LE l ocat ed i n / u01/ or acl e/ i ca/ i ni t i ca. or a

    CONTROL FI LES=/ u01/ or acl e/ i ca/ cont r ol . or aBACKGROUND_DUMP_DEST=/ u01/ or acl e/ i ca/ bdumpUSER_DUMP_DEST=/ u01/ or acl e/ i ca/ udumpCORE_DUMP_DEST=/ u01/ or acl e/ i ca/ cdumpLOG_ARCHI VE_DEST_1=l ocat i on=/ u01/ oracl e/ i ca/ arc1

    DATAFI LES = / u01/ or acl e/ i ca/ sys. dbf

    / u01/ or acl e/ i ca/ usr. dbf

  • 8/10/2019 101816212-Oracle

    33/80

    33

    / u01/ or acl e/ i ca/ r bs. dbf/ u01/ or acl e/ i ca/ t mp. dbf/ u01/ or acl e/ i ca/ sysaux. dbf

    LOGFI LE= / u01/ or acl e/ i ca/ l og1. or a

    / u01/ or acl e/ i ca/ l og2. or a

    Now you want to copy this database to SERVER 2 and in SERVER 2 you dont have /u01filesystem. InSERVER 2 you have /d01filesystem.

    To Clone this Database on SERVER 2 do the following.

    Steps :-

    1. In SERVER 2 install the same version of o/s and same version Oracle as in SERVER 1.

    2. In SERVER 1 generate CREATECONTROLFI LEstatement by typing the following command

    SQL>al t er dat abase backup cont r ol f i l e t o t r ace;

    Now, go to the USER_DUMP_DESTdirectory and open the latest trace file. This file will contain steps andas well as CREATECONTROLFI LEstatement. Copy the CREATECONTROLFI LEstatement and paste in afile. Let the filename be cr .sql

    The CREATECONTROLFI LEStatement will look like this.

    CREATE CONTROLFI LE

    SET DATABASE pr od

    LOGFI LE GROUP 1 ( ' / u01/ or acl e/ i ca/ l og1. or a'

    GROUP 2 ( ' / u01/ or acl e/ i ca/ l og2. or a'

    DATAFI LE ' / u01/ or acl e/ i ca/ sys. dbf ' SI ZE 300M,

    ' / u01/ or acl e/ i ca/ r bs. dbf ' SI ZE 50M,

    ' / u01/ or acl e/ i ca/ usr . dbf ' SI ZE 50M,

    ' / u01/ or acl e/ i ca/ t mp. dbf ' SI ZE 50M,

    / u01/ or acl e/ i ca/ sysaux. dbf si ze 100M;

    MAXLOGFI LES 50

    MAXLOGMEMBERS 3

    MAXLOGHI STORY 400

  • 8/10/2019 101816212-Oracle

    34/80

    34

    MAXDATAFI LES 200

    MAXI NSTANCES 6

    ARCHI VELOG;

    3. In SERVER 2 create the following directories

    $cd / d01/ or acl e

    $mkdi r i ca

    $mkdi r arc1

    $cd i ca

    $mkdi r bdump udump cdump

    Shutdown the database on SERVER 1 and transfer all datafiles, logfiles and control file to SERVER 2 in

    /d01/or acl e/i cadirectory.

    Copy parameter file to SERVER 2 in /d01/or acl e/dbs directory and copy all archive log files toSERVER 2 in /d01/or acl e/i ca/arc1directory. Copy the cr. sql script file to /d01/or acl e/i cadirectory.

    4. Open the parameter file SERVER 2 and change the following parameters

    CONTROL FI LES=/ / d01/ or acl e/ i ca/ cont r ol . or a

    BACKGROUND_DUMP_DEST=/ / d01/ or acl e/ i ca/ bdumpUSER_DUMP_DEST=/ / d01/ oracl e/ i ca/ udumpCORE_DUMP_DEST=/ / d01/ oracl e/ i ca/ cdumpLOG_ARCHI VE_DEST_1=l ocat i on=/ / d01/ oracl e/ i ca/ arc1

    5. Now, open the cr . sql file in text editor and change the locations like this

    CREATE CONTROLFI LE

    SET DATABASE pr od

    LOGFI LE GROUP 1 ( ' / / d01/ or acl e/ i ca/ l og1. or a'

    GROUP 2 ( ' / / d01/ or acl e/ i ca/ l og2. or a'

  • 8/10/2019 101816212-Oracle

    35/80

    35

    DATAFI LE ' / / d01/ or acl e/ i ca/ sys. dbf ' SI ZE 300M,

    ' / / d01/ or acl e/ i ca/ r bs. dbf ' SI ZE 50M,

    ' / / d01/ or acl e/ i ca/ usr. dbf ' SI ZE 50M,

    ' / / d01/ or acl e/ i ca/ t mp. dbf ' SI ZE 50M,

    / / d01/ or acl e/ i ca/ sysaux. dbf si ze 100M;

    MAXLOGFI LES 50

    MAXLOGMEMBERS 3

    MAXLOGHI STORY 400

    MAXDATAFI LES 200

    MAXI NSTANCES 6

    ARCHI VELOG;

    In SERVER 2 export ORACLE_SI Denvironment variable and start the instance

    $expor t ORACLE_SI D=i ca

    $sql pl us

    Ent er User : / as sysdba

    SQL> st ar t up nomount ;

    6. Run cr.sql script to create the controlfile

    SQL>@/ d01/ or acl e/ i ca/ cr . sql

    7. Open the database

    SQL>al t er dat abase open;

  • 8/10/2019 101816212-Oracle

    36/80

    36

    Managing the UNDO TABLESPACE

    Every Oracle Database must have a method of maintaining information that is used to roll back, or undo,changes to the database. Such information consists of records of the actions of transactions, primarily beforethey are committed. These records are collectively referred to as undo.

    Undo records are used to:

    Roll back transactions when a ROLLBACKstatement is issued Recover the database Provide read consistency Analyze data as of an earlier point in time by using Flashback Query Recover from logical corruptions using Flashback features

    Earlier releases of Oracle Database used rollback segments to store undo. Oracle9iintroduced automatic

    undo management, which simplifies undo space management by eliminating the complexities associatedwith rollback segment management. Oracle strongly recommends that you use undo tablespace to manageundo rather than rollback segments.

    Switching to Automatic Management of Undo Space

    To go for automatic management of undo space set the following parameter.

    Steps:-

    1. If you have not created an undo tablespace at the time of creating a database then, create an undo

    tablespace by typing the following command

    SQL>cr eat e undo t abl espace myundo dat af i l e / u01/ or acl e/ i ca/ undo_t bs. dbf si ze 500M

    aut oext end ON next 5M ;

    When the system is first running in the production environment, you may be unsure of the spacerequirements of the undo tablespace. In this case, you can enable automatic extension for datafiles ofthe undo tablespace so that they automatically increase in size when more space is needed

    2. Shutdown the Database and set the following parameters in parameter file.

    UNDO_MANAGEMENT=AUTOUNDO_TABLESPACE=myundo

    3. Start the Database.

    Now Oracle Database will use Automatic Undo Space Management.

    Calculating the Space Requirements For Undo Retention

    You can calculate space requirements manually using the following formula:

    UndoSpace = UR * UPS + over head

  • 8/10/2019 101816212-Oracle

    37/80

    37

    where:

    UndoSpace is the number of undo blocks

    UR is UNDO_RETENTI ONin seconds. This value should take into consideration long-running queriesand any flashback requirements.

    UPS is undo blocks for each second overhead is the small overhead for metadata (transaction tables, bitmaps, and so forth)

    As an example, if UNDO_RETENTI ONis set to 3 hours, and the transaction rate (UPS) is 100 undo blocks foreach second, with a 8K block size, the required undo space is computed as follows:

    (3 * 3600 * 100 * 8K) = 8.24GBs

    To get the values for UPS, Overhead query the V$UNDOSTATview. By giving the following statement

    SQL> Sel ect * f r om V$UNDOSTAT;

    Altering UNDO Tablespace

    If the Undo tablespace is full, you can resize existing datafiles or add new datafiles to it

    The following example extends an existing datafile

    SQL> alter database datafile / u01/ or acl e/ i ca/ undo_t bs. dbf r esi ze 700M

    The f ol l owi ng exampl e adds a new dat af i l e t o undo t abl espace

    SQL> ALTER TABLESPACE myundo

    ADD DATAFI LE ' / u01/ oracl e/ i ca/ undo02. dbf ' SI ZE 200M AUTOEXTEND ONNEXT 1M MAXSI ZE UNLI MI TED;

    Dropping an Undo Tablespace

    Use the DROP TABLESPACEstatement to drop an undo tablespace. The following example drops the undotablespace undot bs_01:

    SQL> DROP TABLESPACE myundo;

    An undo tablespace can only be dropped if it is not currently used by any instance. If the undo tablespacecontains any outstanding transactions (for example, a transaction died but has not yet been recovered), the

    DROP TABLESPACEstatement fails.

    Switching Undo Tablespaces

    You can switch from using one undo tablespace to another. Because the UNDO_TABLESPACEinitialization

    parameter is a dynamic parameter, the ALTER SYSTEM SETstatement can be used to assign a new undotablespace.

  • 8/10/2019 101816212-Oracle

    38/80

    38

    The following statement switches to a new undo tablespace:

    ALTER SYSTEM SET UNDO_TABLESPACE = myundo2;

    Assuming myundois the current undo tablespace, after this command successfully executes, the instanceuses myundo2in place of myundoas its undo tablespace.

    Viewing Information about Undo Tablespace

    To view statistics for tuning undo tablespace query the following dictionary

    SQL>sel ect * f r om v$undost at ;

    To see how many active Transactions are there and to see undo segment information give the followingcommand

    SQL>sel ect * f r om v$t r ansact i on;

    To see the sizes of extents in the undo tablespace give the following query

    SQL>sel ect * f r om DBA_UNDO_EXTENTS;

  • 8/10/2019 101816212-Oracle

    39/80

    39

    SQL Loader

    SQL LOADER utility is used to load data from other data source into Oracle. For example, if you have atable in FOXPRO, ACCESS or SYBASE or any other third party database, you can use SQL Loader to loadthe data into Oracle Tables. SQL Loader will only read the data from Flat files. So If you want to load thedata from Foxpro or any other database, you have to first convert that data into Delimited Format flat file orFixed length format flat file, and then use SQL loader to load the data into Oracle.

    Following is procedure to load the data from Third Party Database into Oracle using SQL Loader.

    1. Convert the Data into Flat file using third party database command.2. Create the Table Structure in Oracle Database using appropriate datatypes3. Write a Control File, describing how to interpret the flat file and options to load the data.4. Execute SQL Loader utility specifying the control file in the command line argument

    To understand it better let us see the following case study.

    CASE STUDY (Loading Data from MS-ACCESS to Oracle)

    Suppose you have a table in MS-ACCESS by name EMP, running under Windows O/S, with the followingstructure

    EMPNO I NTEGERNAME TEXT( 50)SAL CURRENCYJ DATE DATE

    This table contains some 10,000 rows. Now you want to load the data from this table into an Oracle Table.

    Oracle Database is running in LI NUXO/S.

    Solution

    Steps

    Start MS-Access and convert the table into comma delimited flat (popularly known as csv) , by clicking on

    F i l e/SaveAs menu. Let the delimited file name be emp.csv

    1. Now transfer this file to Linux Server using FTP commanda. Go to Command Prompt in windows

    b. At the command prompt type FTP followed by IP address of the server running Oracle.

    FTP will then prompt you for username and password to connect to the Linux Server. Supplya valid username and password of Oracle User in LinuxFor example:-

    C: \ >f t p 200. 200. 100. 111Name: oracl ePasswor d: or acl eFTP>

  • 8/10/2019 101816212-Oracle

    40/80

    40

    c. Now give PUTcommand to transfer file from current Windows machine to Linux machine.

    FTP>putLocal f i l e: C: \ >emp. csvr emot e- f i l e: / u01/ or acl e/ emp. csvFi l e t r ansf er r ed i n 0. 29 Seconds

    FTP>d. Now after the file is transferred quit the FTPutility by typing byecommand.

    FTP>byeGood- Bye

    2. Now come the Linux Machine and create a table in Oracle with the same structure as in MS-ACCESS by taking appropriate datatypes. For example, create a table like this

    $sql pl us scot t / t i ger SQL>CREATE TABLE emp ( empno number ( 5) ,

    name var char2(50) , sal number( 10, 2) , j date date) ;

    3. After creating the table, you have to write a control file describing the actions which SQL Loader should do. You can use any text editor to write the control file. Now let us write a controlfile for ourcase study

    $vi emp. ct l 1 LOAD DATA2 I NFI LE / u01/ or acl e/ emp. csv 3 BADFI LE / u01/ oracl e/ emp. bad

    4 DI SCARDFI LE / u01/ oracl e/ emp. dsc 5 I NSERT I NTO TABLE emp6 FI ELDS TERMI NATED BY , OPTI ONALLY ENCLOSED BY TRAI LI NG

    NULLCOLS7 ( empno, name, sal , j date date mm/ dd/ yyyy ) Notes:(Do not write the line numbers, they are meant for explanation purpose)

    1. The LOADDATAstatement is required at the beginning of the control file.

    2. The I NFI LEoption specifies where the input file is located

    3. Specifying BADFI LEis optional. If you specify, then bad records found during loading will be stored in this file.

    4. Specifying DI SCARDFI LEis optional. If you specify, then records which do not meet a WHENcondition willbe written to this file.

    5. You can use any of the following loading option

    1. I NSERT: Loads rows only if the target table is empty

    2. APPEND: Load rows if the target table is empty or not.

    3. REPLACE: First deletes all the rows in the existing table and then, load rows.

    4. TRUNCATE: First truncates the table and then load rows.

  • 8/10/2019 101816212-Oracle

    41/80

    41

    6. This line indicates how the fields are separated in input file. Since in our case the fields are separated by , so wehave specified , as the terminating char for fields. You can replace this by any char which is used to terminate

    fields. Some of the popularly use terminating characters are semicolon ; , colon : , pipe | etc.TRAI LI NGNULLCOLSmeans if the last column is null then treat this as null value, otherwise, SQLLOADERwill treat the record as bad if the last column is null.

    7. In this line specify the columns of the target table. Note how do you specify format for Date columns

    4. After you have wrote the control file save it and then, call SQLLoader utility by typing thefollowing command

    $sql l dr user i d=scot t / t i ger cont r ol =emp. ct l l og=emp. l og

    After you have executed the above command SQLLoader will shows you the output describinghow many rows it has loaded.

    The LOGoption of sql l dr specifies where the log file of this sql loader session should be created.

    The log file contains all actions which SQLl oader has performed i.e. how many rows wereloaded, how many were rejected and how much time is taken to load the rows and etc. You have to

    view this file for any errors encountered while running SQLLoader .

    CASE STUDY (Loading Data from Fixed Length file into Oracle)

    Suppose we have a fixed length format file containing employees data, as shown below, and wants to loadthis data into an Oracle table.

    7782 CLARK MANAGER 7839 2572. 50 10

    7839 KI NG PRESI DENT 5500. 00 10

    7934 MI LLER CLERK 7782 920. 00 10

    7566 J ONES MANAGER 7839 3123. 75 20

    7499 ALLEN SALESMAN 7698 1600. 00 300. 00 30

    7654 MARTI N SALESMAN 7698 1312. 50 1400. 00 30

    7658 CHAN ANALYST 7566 3450. 00 20

    7654 MARTI N SALESMAN 7698 1312. 50 1400. 00 30

    SOLUTION:

    Steps :-

    1. First Open the file in a text editor and count the length of fields, for example in our fixed lengthfile, employee number is from 1stposition to 4thposition, employee name is from 6thposition to

    15th

    position, Job name is from 17th

    position to 25th

    position. Similarly other columns are alsolocated.

    2. Create a table in Oracle, by any name, but should match columns specified in fixed length file.In our case give the following command to create the table.

  • 8/10/2019 101816212-Oracle

    42/80

    42

    SQL> CREATE TABLE emp ( empno NUMBER( 5) , name VARCHAR2( 20) , j ob VARCHAR2( 10) , mgr NUMBER( 5) , sal NUMBER( 10, 2) ,

    comm NUMBER( 10, 2) , deptno NUMBER( 3) ) ;

    3. After creating the table, now write a control file by using any text editor$vi empf i x. ct l 1) LOAD DATA2) I NFI LE ' / u01/ or acl e/ f i x. dat ' 3) I NTO TABLE emp4) ( empno POSI TI ON( 01: 04) I NTEGER EXTERNAL,

    name POSI TI ON( 06: 15) CHAR,

    j ob POSI TI ON( 17: 25) CHAR, mgr POSI TI ON( 27: 30) I NTEGER EXTERNAL, sal POSI TI ON( 32: 39) DECI MAL EXTERNAL, comm POSI TI ON( 41: 48) DECI MAL EXTERNAL,

    5) dept no POSI TI ON( 50: 51) I NTEGER EXTERNAL)

    Notes:(Do not write the line numbers, they are meant for explanation purpose)

    1. The LOAD DATA statement is required at the beginning of the control file.2. The name of the file containing data follows the INFILE parameter.3. The INTO TABLE statement is required to identify the table to be loaded into.

    4. Lines 4 and 5 identify a column name and the location of the data in the datafile to be loaded into that column.empno, name, job, and so on are names of columns in table emp. The datatypes (INTEGER EXTERNAL, CHAR,DECIMAL EXTERNAL) identify the datatype of data fields in the file, not of corresponding columns in the emptable.

    5. Note that the set of column specifications is enclosed in parentheses.

    4. After saving the control file now start SQL Loader utility by typing the following command.

    $sql l dr user i d=scot t / t i ger cont r ol =empf i x. ct l l og=empf i x. l og di r ect =yAfter you have executed the above command SQLLoader will shows you the output describing howmany rows it has loaded.

    Loading Data into Multiple Tables using WHEN condition

    You can simultaneously load data into multiple tables in the same session. You can also use WHENcondition to load only specified rows which meets a particular condition (only equal to = and not equal to conditions are allowed).

    For example, suppose we have a fixed length file as shown below

    7782 CLARK MANAGER 7839 2572. 50 10

    7839 KI NG PRESI DENT 5500. 00 10

    7934 MI LLER CLERK 7782 920. 00 10

  • 8/10/2019 101816212-Oracle

    43/80

    43

    7566 J ONES MANAGER 7839 3123. 75 20

    7499 ALLEN SALESMAN 7698 1600. 00 300. 00 30

    7654 MARTI N SALESMAN 7698 1312. 50 1400. 00 30

    7658 CHAN ANALYST 7566 3450. 00 20

    7654 MARTI N SALESMAN 7698 1312. 50 1400. 00 30

    Now we want to load all the employees whose deptnois 10 into emp1 table and those employees whosedeptnois not equal to 10 in emp2table. To do this first create the tables emp1and emp2by takingappropriate columns and datatypes. Then, write a control file as shown below

    $vi emp_mul t i . ct l

    Load Dat ai nf i l e / u01/ oracl e/ empf i x. dat append i nt o tabl e scot t . emp1WHEN ( dept no= 10 )

    ( empno POSI TI ON( 01: 04) I NTEGER EXTERNAL, name POSI TI ON( 06: 15) CHAR, j ob POSI TI ON( 17: 25) CHAR, mgr POSI TI ON( 27: 30) I NTEGER EXTERNAL, sal POSI TI ON( 32: 39) DECI MAL EXTERNAL, comm POSI TI ON( 41: 48) DECI MAL EXTERNAL,

    dept no POSI TI ON( 50: 51) I NTEGER EXTERNAL) I NTO TABLE scot t . emp2WHEN ( dept no 10 )( empno POSI TI ON( 01: 04) I NTEGER EXTERNAL, name POSI TI ON( 06: 15) CHAR, j ob POSI TI ON( 17: 25) CHAR, mgr POSI TI ON( 27: 30) I NTEGER EXTERNAL, sal POSI TI ON( 32: 39) DECI MAL EXTERNAL, comm POSI TI ON( 41: 48) DECI MAL EXTERNAL, dept no POSI TI ON( 50: 51) I NTEGER EXTERNAL)

    After saving the file emp_mul t i .ct l run sql l dr $sql l dr user i d=scot t / t i ger cont r ol =emp_mul t i . ct l

    Conventional Path Load and Direct Path Load.

    SQL Loader can load the data into Oracle database using Conventional Path method or Direct Path method.

    You can specify the method by using DI RECTcommand line option. If you give DI RECT=TRUEthen SQLloader will use Direct Path Loading otherwise, if omit this option or specify DI RECT=f al se, then SQLLoader will use Conventional Path loading method.

    Conventional Path

    Conventional path load (the default) uses the SQL I NSERTstatement and a bind array buffer to load datainto database tables.

  • 8/10/2019 101816212-Oracle

    44/80

    44

    When SQL*Loader performs a conventional path load, it competes equally with all other processes forbuffer resources. This can slow the load significantly. Extra overhead is added as SQL statements aregenerated, passed to Oracle, and executed.

    The Oracle database looks for partially filled blocks and attempts to fill them on each insert. Althoughappropriate during normal use, this can slow bulk loads dramatically.

    Direct Path

    In Direct Path Loading, Oracle will not use SQL I NSERTstatement for loading rows. Instead it directlywrites the rows, into fresh blocks beyond High Water Mark, in datafiles i.e. it does not scan for free blocks

    before high water mark. Direct Path load is very fast because

    Partial blocks are not used, so no reads are needed to find them, and fewer writes are performed.

    SQL*Loader need not execute any SQL I NSERTstatements; therefore, the processing load on theOracle database is reduced.

    A direct path load calls on Oracle to lock tables and indexes at the start of the load and releases themwhen the load is finished. A conventional path load calls Oracle once for each array of rows to

    process a SQL I NSERTstatement. A direct path load uses multiblock asynchronous I/O for writes to the database files. During a direct path load, processes perform their own write I/O, instead of using Oracle's buffer

    cache. This minimizes contention with other Oracle users.

    Restrictions on Using Direct Path Loads

    The following conditions must be satisfied for you to use the direct path load method:

    Tables are not clustered. Tables to be loaded do not have any active transactions pending. Loading a parent table together with a child Table

    Loading BFI LEcolumns

  • 8/10/2019 101816212-Oracle

    45/80

  • 8/10/2019 101816212-Oracle

    46/80

    46

    Keyword Description (Default)

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

    USERID username/password

    BUFFER size of data buffer

    FILE output files (EXPDAT.DMP)

    COMPRESS import into one extent (Y)

    GRANTS export grants (Y)

    INDEXES export indexes (Y)

    DIRECT direct path (N)

    LOG log file of screen output

    ROWS export data rows (Y)

    CONSISTENT cross-table consistency(N)

    FULL export entire file (N)

    OWNER list of owner usernames

    TABLES list of table names

    RECORDLENGTH length of IO record

    INCTYPE incremental export type

    RECORD track incr. export (Y)

    TRIGGERS export triggers (Y)

    STATISTICS analyze objects (ESTIMATE)

    PARFILE parameter filename

    CONSTRAINTS export constraints (Y)OBJECT_CONSISTENT transaction set to read only during object export (N)

    FEEDBACK display progress every x rows (0)

    FILESIZE maximum size of each dump file

    FLASHBACK_SCN SCN used to set session snapshot back to

    FLASHBACK_TIME time used to get the SCN closest to the specified time

  • 8/10/2019 101816212-Oracle

    47/80

    47

    QUERY select clause used to export a subset of a table

    RESUMABLE suspend when a space related error is encountered(N)

    RESUMABLE_NAME text string used to identify resumable statement

    RESUMABLE_TIMEOUT wait t