Oracle Database 11g Express Edition PL/SQL and Database Administration Concepts -II

14  Download (0)

Full text


Oracle Database 11g Express Edition – PL/SQL and Database Administration Concepts -II

Slide 1:

Hello and welcome back to the second part of this online, self-paced course titled Oracle Database 11g Express Edition – PL/SQL and Database Administration Concepts - II. My name is Anupama Mandya, and I will be guiding you through this course.

This course is designed to follow the first part of the course PL/SQL and Database Administration Concepts.

Slide 2: Course Objectives

Before we begin, let us look at the objectives of this session. At the end of this session, you should be: • Able to use Records, Cursors and Triggers and Handle Exceptions in PL/SQL

• Familiar with some basic concepts of Administering and Managing the Database • Familiar with some features of Working in a Global Environment

Slide 3: Road Map

In this topic we discuss about Using Records, Cursors, Triggers. We also discuss about how Exceptions are Handled in PL/SQL.

Slide4: Overview- Records Cursors and Triggers

Introduction: In this topic, we discuss some of the other PL/SQL structures like Records, Cursors

and Triggers.

Overview: Records, Cursors and Triggers are some of the other PL/SQL structures. The segments around the core gives an overview of each of these.

Records: A record is a composite variable that can store data values of different types, similar to a struct type in C, C++, or Java. Records are useful for holding data from table rows, or certain columns from table rows.

Cursors: When Oracle Database Express Edition executes a SQL statement, it stores the result set and processing information in an unnamed private SQL area. A pointer to this unnamed area, is called a Cursor.

Triggers: While working with a database application, you may also want to add programmatic

functionality that executes when specific operations occur in the database. You can create a trigger to deal with these complex situations.


A trigger is a PL/SQL unit that is stored in the database and (if it is in the enabled state) automatically executes ("fires") in response to a specified event

Slide 5: Records: In this topic we briefly discuss about Records.

A record is a PL/SQL composite variable that can store data values of different types. Suppose you have data about an employee such as name, salary, and hire date. These items are dissimilar in type but logically related. A record containing a field for each item lets you treat the data as a logical unit. You can use the %ROWTYPE attribute to declare a record that represents a table row or row fetched from a cursor. The internal components of a record are called fields. With user-defined records, you can declare your own fields. To access a record field, you use dot notation: record_name.field_name.

Declaring a Record Type: Records are useful for holding data from table rows, or from certain columns of table rows. Each record field corresponds to a table column.

There are three ways to create a record:

1. Declare a RECORD type, and then declare a variable of that type. The syntax is as shown:

2. Declare a variable of the type table_name%ROWTYPE.

Here, the fields of the record have the same names and data types as the columns of the table. 3. Declare a variable of the type cursor_name%ROWTYPE.

Here, the fields of the record have the same names and data types as the columns of the table in the FROM clause of the cursor SELECT statement.

Slide 6: Demo Setup

Following is a demonstration about Declaring a Record Type using SQL Developer tool Edit. Slide 8: Cursors

About Implicit Cursors: A cursor is a pointer to a private SQL area that stores information about processing a specific SELECT or DML statement.

There are two types of cursors: Implicit Cursors and Explicit Cursors Implicit Cursors :

An implicit cursor is a session cursor that is constructed and managed by PL/SQL. PL/SQL opens an implicit cursor every time you run a SELECT or DML statement. You cannot control an implicit cursor, but you can get information from its attributes. The syntax of an implicit cursor attribute value is


most recently run SELECT or DML statement. If no such statement has run, the value of SQLattribute is NULL.

An implicit cursor closes after its associated statement runs; however, its attribute values remain available until another SELECT or DML statement runs.

Attributes of Implicit Cursors are:

SQL%ISOPEN - Checks if the Cursor is Open

SQL%FOUND - Determines if any rows were affected SQL %NOTFOUND - Determines if No Rows were affected SQL%ROWCOUNT - Checks how many rows were affected

Explicit Cursors: Explicit Cursors : An explicit cursor has a name and is associated with a query (SQL SELECT statement)-usually one that returns multiple rows.

An explicit cursor is a session cursor that you construct and manage. You must declare and define an explicit cursor, giving it a name and associating it with a query (typically, the query returns multiple rows). Then you can process the query result set in either of these ways:

1. Open the explicit cursor (with the OPEN statement), fetch rows from the result set (with the FETCH statement), and close the explicit cursor (with the CLOSE statement).

2. Use the explicit cursor in a cursor FOR LOOP statement

The syntax to use an explicit cursor to retrieve result set rows one at a time is as shown: 1. In the declarative part:

a. Declare the cursor:

b. Declare a record to hold the row returned by the cursor 2. In the executable part:

a. Open the cursor

b. Fetch rows from the cursor (rows from the result set) one at a time, using a LOOP statement that has syntax as shown

c. Close the cursor Slide 9: Demo Setup


Slide 11: Triggers

About Triggers: In this section, we discuss about Triggers. Like a stored procedure, a trigger is a named PL/SQL unit that is stored in the database and can be invoked repeatedly. Unlike a stored procedure, you can enable and disable a trigger, but you cannot explicitly invoke it. While a trigger is enabled, the database automatically invokes it-that is, the trigger fires-whenever its triggering event occurs. While a trigger is disabled, it does not fire.

You create a trigger with the CREATE TRIGGER statement. You specify the triggering event in terms of triggering statements and the item on which they act. The trigger is said to be created on or defined on the item, which is either a table, a view, a schema, or the database. You also specify the timing point, which determines whether the trigger fires before or after the triggering statement runs and whether it fires for each row that the triggering statement affects. By default, a trigger is created in the enabled state.

A trigger has the structure as shown: TRIGGER trigger_name triggering_event [ trigger_restriction ] BEGIN triggered_action; END;

The trigger_name must be unique for triggers in the schema. A trigger can have the same name as another kind of object in the schema (for example, a table); however, Oracle recommends using a naming convention that avoids confusion.

A trigger has two states or modes: ENABLED and DISABLED. When a trigger is first created, it is enabled by default. The Oracle server checks integrity constraints for enabled triggers and guarantees that triggers cannot compromise them.

Types of Triggers: The different types of Triggers are:

Simple triggers, compound triggers, INSTEAD OF Triggers and SYSTEM Triggers 1. A simple trigger can fire at exactly one of these timing points:

 Before the triggering event executes (statement-level BEFORE trigger) • After the triggering event executes (statement-level AFTER trigger) • Before each row that the event affects (row-level BEFORE trigger)


• After each row that the event affects (row-level AFTER trigger) 2. A compound trigger can fire at multiple timing points

3. An INSTEAD OF trigger is defined on a view, and its triggering event is a DML statement. 4. A system trigger is defined on a schema or the database.

Managing Triggers:

To create triggers, use either the SQL Developer tool Create Trigger or the DDL statement CREATE TRIGGER.

To change a trigger, use either the SQL Developer tool Edit or the DDL statement CREATE TRIGGER with the OR REPLACE clause.

To disable or enable a single trigger, use the ALTER TRIGGER statement with the DISABLE or ENABLE clause.

You can drop a trigger, use either the SQL Developer navigation frame and Drop tool, or the DDL statement DROP TRIGGER.

You must drop a trigger before dropping the objects on which it depends. Slide 12: Demo Setup

The following is a demonstration about how to Create a Trigger Slide 14: Exceptions and Exception Handlers

Overview: So far, you have seen how to write PL/SQL blocks with a declarative section and an executable section. For exception handling, you can include another optional section called the

exception section. This section begins with the keyword EXCEPTION. If present, this is the last section in a PL/SQL block

An exception is an error in PL/SQL that is raised during the execution of a block. A block always

terminates when PL/SQL raises an exception, but you can specify an exception handler to perform final actions before the block ends.

When the exception is raised, the control shifts to the exception section and all the statements in the exception section are executed. The PL/SQL block terminates with normal, successful completion. This enables you to provide the user with a customized, informative message if an error is encountered Exceptions can be handled in two ways. it can be predefined or User Defined

The exception-handling part of a subprogram contains one or more exception handlers. An exception handler has this syntax:


WHEN { exception_name [ OR exception_name ]... | OTHERS } THEN statement; [ statement; ]...

An alternative to the WHEN OTHERS exception handler is the EXCEPTION_INIT pragma, which associates a user-defined exception name with an Oracle Database error number.

Handling Pre Defined Exceptions: Oracle Database XE has many predefined exceptions, which it raises automatically when a program violates database rules or exceeds system-dependent limits. For example, if a SELECT INTO statement returns no rows, Oracle Database XE raises the predefined exception NO_DATA_FOUND

Some of the Pre Defined Exceptions are:

TOO_MANY_ROWS which is raised When- Single row SELECT returned multiple rows.

CASE_NOT_FOUND which is raised when - None of the choices in the WHEN clauses of a CASE statement were selected and there is no ELSE clause.

ZERO_DIVIDE which is raised when - A program attempted to divide a number by zero. Declaring and Handling User Defined Exceptions:

PL/SQL lets you define (declare) your own exceptions.

Unlike a predefined exception, a user-defined exception must be raised explicitly, using either the RAISE statement or the DBMS_STANDARD.RAISE_APPLICATION_ERROR procedure.

For example:

IF condition THEN RAISE exception_name; Slide 15: Demo Setup

Following are a simulation and a demonstration about Handling Predefined and User Defined

Exceptions. The simulation allows the learner to perform certain steps based on the instructions given to them and is silent.

Slide 18: Review

Let us now take a brief pause by taking a quiz

Slide 20: Road Map

In this topic, you learn the basic concepts of Administering and Managing Oracle 11g Express Edition Database


Slide 21: Adminster and manage the Database

Overview: With Oracle Database XE and related tools you can administer the database by managing database memory, database storage structure, monitoring storage space usage, managing database users, monitoring the database and backing up the database. You learn how to administer and manage the database by performing these tasks.

Managing Database Memory:

Oracle Database Express Edition uses automatic memory management, which you cannot disable. Oracle Database Express Edition consists of two main components:

1. The Oracle instance which comprises of memory structures known as the System Global Area (SGA) and Oracle background processes.

2. The Oracle database which comprises of data files, redo log files, and control files.

To support database operation, Oracle Database Express Edition needs to start a set of processes, called background processes, and needs to allocate some memory in the host computer. The background processes and allocated memory together make up an Oracle instance.

After starting an instance, the Oracle software associates the instance with a specific database. This is called mounting the database. The database is then ready to be opened, which makes it accessible to authorized users. Multiple instances can execute concurrently on the same computer, each accessing its own physical database

There are two types of memory that the Oracle instance allocates:

1. System global area (SGA)-A shared memory area that contains data buffers and control information for the instance. The SGA is divided into separate buffer areas and data pools.

2. Program global area (PGA)-A memory area used by a single Oracle server process. An Oracle server process is a process that services a client’s requests.

Oracle Database Express Edition creates a new server process whenever it receives a new database connection request. Each new server process then allocates its own private PGA area. The PGA is used to process SQL statements and to hold logon and other session information.

With automatic memory management in Oracle Database Express Edition, the database dynamically exchanges memory between the System Global Area (SGA) and the instance Program Global Area (PGA) as needed to meet processing demands. The database also dynamically tunes the sizes of the individual SGA components and the sizes of the individual PGAs.

The instance is controlled by a set of parameters that are listed in the initialization parameter file (init.ora).


The Oracle database uses initialization parameters to create and configure memory structures. The Oracle Database Express Edition automatic memory management capabilities automatically adjust the memory distribution among the various SGA and PGA subcomponents for optimal performance. These adjustments are made within the boundaries of your total SGA and PGA target values.

Database Storage Structure:

Oracle Database Express Edition (Oracle Database XE) is composed of the following storage structures: 1. Logical structures such as tablespaces are created and recognized by the database only, and are not known to the operating system.

2. Physical structures are those that can be seen and operated on from the operating system, such as the physical files that store data on disk.

3. Recovery-related structures such as redo logs and database backups are used to recover the database after an operating system failure, Oracle instance failure, or media (disk) failure. Recovery-related structures are stored in an automatically managed disk storage area called the flash recovery area.

Oracle Database XE completely automates the management of its logical and physical structures and flash recovery area storage. You use the Oracle Database XE graphical user interface to monitor these structures, mostly to understand how much storage your applications have used so far, how much free storage remains, and whether more space is needed for backups.

Let us now take a look at the database and its storage structure.

The database is the collection of logical and physical structures that together contain all the data and metadata for your applications. The database also contains control structures (such as control files) that it needs for startup and operations

The Oracle Database XE instance (which consists of the Oracle Database XE background processes and allocated memory) works with a single database only.

Rather than enabling you to create multiple databases to accommodate different applications, Oracle Database XE uses a single database, and accommodates multiple applications by enabling you to separate data into different schemas.

A database consists of one or more tablespaces. A tablespace is a logical grouping of one or more physical datafiles or tempfiles, and is the primary structure by which the database manages storage. Database objects, such as tables and indexes, are stored as segments in tablespaces. Each segment contains one or more extents. An extent consists of contiguous data blocks, which means that each extent can exist in only one data file. Data blocks are the smallest unit of I/O in the database.


When the database requests a set of data blocks from the operating system (OS), the OS maps this to an actual file system or disk block on the storage device. Because of this, you need not know the physical address of any of the data in your database.

Monitoring Storage Space Usage:

The most important storage management task is monitoring the amount of free storage space and storage space used for any tablespaces used for storing user data

Because Oracle Database Express Edition (Oracle Database XE) is limited to just over four gigabytes (GB) of user data, your most important storage management task is monitoring the amount of free storage space and storage space used for any tablespaces used for storing user data.

To check this usage information, you can use Oracle SQL Developer tool to view the Free Space Report Managing Database Users:

A user account is identified by a user name and defines the user’s attributes, including the following: ■ Password for database authentication

■ Privileges and roles

■ Default tablespace for database objects

■ Default temporary tablespace for query processing work space Users need privileges to access objects in Oracle Database XE.

When creating a user, you grant privileges to enable the user to connect to the database, to run queries and make updates, and to create schema objects. In addition, they need system privileges that allow them to create objects. After users have created objects, they can grant privileges on their objects to other users. There are two main types of user privileges . They are System privileges and Object privileges

System privileges: A system privilege is the right to perform a particular action, or to perform an action on any schema objects of a particular type. For example, the privileges to create tables and to delete the rows of any table in a database are system privileges

Object privileges-An object privilege is a right to perform a particular action on a specific schema object. Different object privileges are available for different types of schema objects. The privilege to delete rows from the DEPARTMENTS table is an example of an object privilege.

Managing and controlling privileges is made easier by using roles, which are named groups of related privileges. You create roles, grant system and object privileges to the roles, and then grant roles to users. Unlike schema objects, roles are not contained in any schema. For example all DBA users can be granted the DBA role.


Privileges are granted by using the GRANT command. If a system privilege is granted with ADMIN OPTION, then it can be passed on by the grantee. If an object privilege is granted with GRANT OPTION, then it can be passed on.

Backing up the Database:

Backing up and restoring Oracle Database Express Edition is based on protecting the physical files that make up the database: the datafiles, the control file, the server parameter file (SPFILE), and, if in ARCHIVELOG mode, the redo log files.

In Oracle Database EExpress Edition, the database backup and recovery facility is based upon the Recovery Manager (RMAN) utility that is integrated into the database. Although there is a Recovery Manager command line client similar to the SQL Command Line, you do not need to interact with it directly to back up or restore your database. Oracle Database Express Edition includes backup and restore scripts that you access using menu choices on your desktop. These scripts perform a full backup and restore of the entire database, and store backup files in the flash recovery area.

The database automatically manages backups and archived logs in the flash recovery area, deleting any that are obsolete as space is needed for new files.

Slide 22: Demo Setup

The following are some simulations and demonstrations of the “Administer and Manage Database” topic. The simulations are silent.

Slide 27: Review

Let us now take a brief pause by taking a quiz Slide 29: Road Map

The last topic is about Working in a Global Environment. Slide 30: Working in a Global Environment

In this topic we discuss about Working in a Global Environment. Click on each of the markers to learn about Globalization Support Features.


Globalization support features enable you to develop multilingual applications that can be run

simultaneously from anywhere in the world. An application can render the content of the user interface, and process data, using the native language and locale preferences of the user.


In the last topic of this course, we briefly discuss the various globalization support features that are available in Oracle Database 11g Express Edition

Language Support

Oracle Database Express Edition (Oracle Database XE) enables you to store, process,and retrieve data in native languages. The languages that can be stored in a database are all languages written in scripts that are encoded by Oracle-supported character sets. Through the use of Unicode databases and datatypes, Oracle Database supports most contemporary languages.

Additional support is available for a subset of the languages. The database can, for example, display dates using translated month names, and can sort text data according to cultural conventions. The term language support refers to the additional language-dependent functionality, and not to the ability to store text of a specific language.

For example, language support includes displaying dates or sorting text according to specific locales and cultural conventions. Additionally, for some supported languages, Oracle Database provides translated error messages and a translated user interface for the database utilities.

Territory Support

Oracle Database Express Edition supports cultural conventions that are specific to geographical locations. The default local time format, date format, and numeric and monetary conventions depend on the local territory setting.

Setting different NLS parameters enables the database session to use different cultural settings. For example, you can set the euro (EUR) as the primary currency and the Japanese yen (JPY) as the secondary currency for a given database session, even when the territory is AMERICA.

Date and Time Formats

Different countries have different conventions for displaying the hour, day, month, and year. Take a look at the example for different date and time formats

Calendar Formats

Oracle Database Express Edition stores this calendar information for each territory: First day of the week

Sunday in some cultures, Monday in others. Set by the NLS_TERRITORY parameter. First week of the calendar year

Some countries use week numbers for scheduling, planning, and bookkeeping. In the ISO standard, this week number can differ from the week number of the calendar year.


For example, 1st Jan 2005 is in ISO week number 53 of 2004. An ISO week starts on Monday and ends on Sunday. To support the ISO standard, Oracle Database XE provides the IW date format element, which returns the ISO week number. The first calendar week of the year is set by the NLS_TERRITORY


Number of days and months in a year

Oracle Database Express Edition supports six calendar systems in addition to the Gregorian calendar, which is the default.

Numeric and Monetary Formats

Different countries have different numeric and monetary conventions. Take a look at the examples for different numeric and monetary formats

Linguistic Sorting and String Searching

Different languages have different sort orders (collating sequences). Also, different countries or cultures that use the same alphabets sort words differently.

Take a look at the example shown. Length Semantics

In single-byte character sets, the number of bytes and the number of characters in a string are the same. In multibyte character sets, a character or code point consists of one or more bytes.

Calculating the number of characters based on byte length can be difficult in a variable-width character set. Calculating column length in bytes is called byte semantics, while measuring column length in characters is called character semantics.

Character semantics is useful for specifying the storage requirements for multibyte strings of varying widths. For example, in a Unicode database (AL32UTF8), suppose that you must have a VARCHAR2 column that can store up to five Chinese characters with five English characters.

Using byte semantics, this column requires 15 bytes for the Chinese characters, which are 3 bytes long, and 5 bytes for the English characters, which are 1 byte long, for a total of 20 bytes. Using character semantics, the column requires 10 characters.

Unicode and SQL National Character Data Type

Unicode is a character encoding system that defines every character in most of the spoken languages in the world. In Unicode, every character has a unique code, regardless of the platform, program, or language.


You can store Unicode characters in an Oracle Database XE in two ways:

1.You can create a Unicode database that enables you to store UTF-8 encoded characters as SQL character datatypes (CHAR, VARCHAR2, CLOB, and LONG).

2. You can declare columns and variables that have SQL national character datatypes.

The SQL national character data types are NCHAR, NVARCHAR2, and NCLOB. They are also called Unicode data types, because they are used only for storing Unicode data.

The national character set, which is used for all SQL national character data types, is specified when the database is created. The national character set can be either UTF8 or AL16UTF16 (default).

When you declare a column or variable of the type NCHAR or NVARCHAR2, the length that you specify is the number of characters, not the number of bytes.

Initial NLS Parameter Values

The initial values of NLS parameters are set by database initialization parameters.

The Database Administrator can set the values of initialization parameters in the initialization parameter file, and they take effect the next time the database is started.

Slide 31: Course Review

Well, we have now come to the end of this course. Thank you for taking up this course.

In this course, we talked about some basic PL/SQL and Database Administration concepts which included

• Ability of using Records, Cursors and Triggers • Handling Exceptions in PL/SQL programs

• Getting Familiar with some Basic Database Administration and Management Concepts • Ability to determine the various features of Working in a Global Environment

Slide 32: How Can I Learn More?

Oracle offers a variety of additional channels from which you can learn more about Oracle Database 11g Express Edition or about any Oracle products. We at Oracle Education know your time is valuable and limited, and so we thank you for participating in this self-paced training. We hope this course has met your expectations and learning objectives, and wish you the best of luck in all of your endeavors. Thanks again.





Related subjects :