Introduction to Oracle on dba automation

download Introduction to Oracle on dba automation

of 47

Transcript of Introduction to Oracle on dba automation

  • 7/28/2019 Introduction to Oracle on dba automation

    1/47

    PREFACE

    Knowledge is precious but wisdom comes through

    experience. A famous method to explain but I try my best to

    give presentation and make short report on it. Philosopher oncequoted these words to make people understand the importance

    of practical knowledge and how to represent this in front of the

    other people and the very important way is how to explain to

    them so that they could understand easily.

    Theory in any subject is important but that subject

    knowledge is important if should be understood by the other

    people in a very simple way by you.

    An Engineering student cannot be perfect engineer orprofessional without the practical, theoretical knowledge if he

    /she is not be able to represent that knowledge to you in a very

    simple way so that you can easily understood. I got the

    opportunity to make a presentation on the Oracle.

  • 7/28/2019 Introduction to Oracle on dba automation

    2/47

    Introduction to Oracle

    Oracle is most widely database used in the world. It runs virtually everykind of computer. It functions virtually identically on all the machines, sowhen we learn it on one, we can use it on any other. This fact makes

    knowledgeable oracle user and developers very much in demand, and

    makes oracle knowledge and skills very portable.

    Oracle can easily be used for simple operations such as entering multiple

    data and running standard reports. But an approach would ignore its great

    power; it would be like be buying a high performance racing car, and thenpulling it around with a horse.

    Oracle is an Object-relational database. A relational database is anextremely simple way of thinking and managing the data used in

    business. It is nothing more than a collection of tables of data. We allencounter table every day: weather reports, stocks charts, sports scores.

    These all tables, with column headings and rows of information simply

    presented. Even so the relational approach can be sophisticated and

    powerful enough for even the most complex of business. An object

    relational database supports all of the features of a relational database

    while also supporting object-oriented concepts and features.Oracle has grown from its humble beginnings as one of a number of

    databases available in the 1970s to the market leader of today. In its early

    days, Oracle Corporation was known more as an aggressive sales and

    promotion organization than a technology supplier. Over the years, theOracle database has grown in depth and quality, and its technical

    capabilities now are generally recognized as the most advanced. With

    each release, Oracle has added more power and features to its already

    solid base while improving the manageability.

  • 7/28/2019 Introduction to Oracle on dba automation

    3/47

    Features of OracleTo give some structure to the broad spectrum of the Oracle database,

    weve organized the features into the following sections:

    Database application development features:

    Database Programming:

    All flavors of the Oracle database include different languages and

    interfaces that allow programmers to access and manipulate the data in

    the database. Database programming features usually interest two groups:

    developers building Oracle-based applications that will be sold

    commercially and IT organizations within companies that custom-

    develop applications unique to their businesses.

    Database Extensibility:

    The Internet and corporate intranets have created a growing demand forstorage and manipulation of nontraditional data types within the database.

    There is a need for extensions to the standard functionality of a database

    for storing and manipulating image, audio, video, spatial, and time series

    information. These capabilities are enabled through extensions to

    standard SQL.

    Database connection features:

    Database Networking:

    Database users connect to the database

    by establishing a network connection. You can also link database servers

    via network connections. Oracle provides a number of features to

    establish connections between users and the database and/or between

    Database servers.

    Oracle Application Server:

    The popularity of Internet and intranet applications has led to a change in

    deployment from client/server (with fat clients running a significant piece

    of the application) to three-tier architecture (with a browser supplyingeverything needed on a thin client). The Oracle Application Server

    provides a means of implementing the middle tier of a three-tier solution

    for web-based applications, component-based applications, and enterprise

    application integration.

  • 7/28/2019 Introduction to Oracle on dba automation

    4/47

    Distributed database features:

    Distributed Queries and Transactions:

    Data within an organization is often spread among multiple databases forreasons of both capacity and organizational responsibility. Users may

    want to query this distributed data or update it as if it existed within asingle database.

    Heterogeneous Services:

    Heterogeneous Services allow non-Oracle data and services to be

    accessed from an Oracle database through generic connectivity viaODBC and OLE-DB included with the database.

    Data movement features:

    Moving data from one Oracle database to another is often a requirement

    when using distributed databases, or when a user wants to implement

    multiple copies of the same database in multiple locations to reduce

    network traffic or increase data availability. You can export data and data

    dictionaries (metadata) from one database and import them into another.

    Performance features:

    Database Parallelization:

    Databases tasks implemented in parallel speed up querying, tuning, and

    maintenance of the database. By breaking up a single task into smaller

    tasks and assigning each subtask to an independent process, you can

    dramatically improve the performance of certain types of database

    operation. Examples of query features implemented in parallel include:

    Table scans

    Nested loops

    Sort merge joins

    GROUP BYs NOT IN sub queries (anti-joins) User-defined functions

    Index scans

    Select distinct UNION and UNION ALL Hash joins ORDER BY and aggregation

    Bitmap star joins Partition-wise joins

  • 7/28/2019 Introduction to Oracle on dba automation

    5/47

    Stored procedures (PL/SQL, Java, external routines)

    Data Warehousing and Business Intelligence:

    Oracle has also added some performance enhancements that specifically

    apply to data warehousing applications.

    Database management features:

    Oracle Enterprise Manager:

    As part of every Database Server, Oracle provides the Oracle Enterprise

    Manager (EM), a database management tool framework with a graphical

    interface used to manage database users, instances, and features (such as

    replication) that can provide additional information about the Oracleenvironment. EM can also manage Oracles Application Server,

    Collaboration Suite, and E-Business Suite.

    Backup and Recovery:

    As every database administrator knows, backing up a database is a rathermundane but necessary task. An improper backup makes recovery

    difficult, if not impossible. Unfortunately, people often realize the

    extreme importance of this everyday task only when it is too late

    usually after losing business-critical data due to a failure of a relatedsystem.

    Database Availability:

    Database availability depends upon the reliability and management of the

    database, the underlying operating system, and the specific hardware

    components of the system. Oracle has improved availability by reducing

    backup and recovery times. It has done this through:

    Providing online and parallel backup and recovery. Improving the management of online data through range

    partitioning.Oracle SQL

    The history of SQL begins in an IBM laboratory in San Jose,

    California, where SQL was developed in the late 1970s.

    SQL stands for Structured Query Language, and the language itselfis often referred to as "sequel."

    It is a standard and programming language.

  • 7/28/2019 Introduction to Oracle on dba automation

    6/47

    SQL lets you access and manipulate databases. It was originally developed for IBM'sDB2 product. American National Standard Institute is primary organization for

    fostering of technology standard. Long established computer

    standard includes the American code for information interchange(ANSI).

    SQL is a nonprocedural language, in contrast to the procedural or

    third generation languages (3GLs) such as COBOL and C that had

    been created up to that time.

    Nonprocedural means what rather than how. For example, SQL

    describes what data to retrieve, delete, or insert, rather than how to

    perform the operation. Some common RDBMS that used SQL are ORACLE, CYBASE,

    and Microsoft SQL SERVER.

    What Can SQL do?

    SQL can execute queries against a database.

    SQL can retrieve data from a database. SQL can insert records in a database. SQL can update records in a database.

    SQL can delete records from a database.

    SQL can create new databases.

    SQL can create new tables in a database. SQL can create stored procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures, and views.

    SQL StatementSELECT Data retrieval

    INSERTUPDATEDELETEMERGE

    Data manipulating language(DML)

    CREATE

    ALTER

    DROPRENAMETRUNCATE

    Data definition language(DDL)

    COMMITROLLBACK

    SAVEPOINT

    Transaction control

  • 7/28/2019 Introduction to Oracle on dba automation

    7/47

    GRANT

    REVOKE

    Data control language(DCL)

    Statement Description

    SELECT Retrieves data from database

    INSERTUPDATE

    DELETEMERGE

    Enter new rows, changes existing rowsand removes unwanted rows from

    tables in the database, respectively.

    CREATEALTER

    DROP

    RENAMETRUNCATE

    Set up changes and removes data

    structures from the tables.

    COMMITROLLBACKSAVEPOINT

    Manages the changes made by DMLstatements. Changes to the data can be

    grouped together into logical

    transactions.

    GRANT

    REVOKE

    Gives or remove access rights to both

    the Oracle database and the structure

    with in it.

    SELECT Statement

    Syntax:

    SELECT [ALL|DISTINCT] columns/expr [AS new name]FROM table[WHERE conditions]

    [GROUP BY fields][HAVING conditions][ORDER BY column/integer [ASC|DESC]]

    SELECT Specifies the columns or fields to be included in the result

    set.DISTINCT

    FROM Identifies the tables or views from which the data will be

    retrieved.

    WHERE The predicate(s) that determine which rows will be

    retrieved.

    GROUP BY Use to group output by the field with duplicate values and

    apply group functions to the grouped data.

    HAVING Use to place a condition on results of group function

    calculations.ORDER BY Determines the sequence of the rows (Default order is

  • 7/28/2019 Introduction to Oracle on dba automation

    8/47

    ascending).

    Example:

    SELECT ename, age, add as Address, sal SalaryFROM emp

    WHERE sal>10000

    ORDER BY sal DESC;

    Operators in SQL

    Arithmatic operators:

    Used for arithmetic operations.

    -, +, *, /.

    Concatenation operator(||):

    It combines columns or character string to other columns.

    Comparison operators:

    =, (, !=, ^=).

    Other comparison operators: LIKE:

    we use LIKE operator to perform wildcard search using % and _. % represents any sequence of zero or more characters. _ represents any single character.

    IN:

    Determine if a value is a member of a specific search set.

    IS NULL:

    Determine if a value is null.

    BETWEENAND..:

    Use to display rows based on a range of values.

    Logical Operators:

    AND, OR, NOT.

  • 7/28/2019 Introduction to Oracle on dba automation

    9/47

    We can use NOT with various operators such as NOT IN,NOT BETWEEN, NOT LIKE etc.

    Set Operators:

    Set operators are used to combine results of two or more

    queries. UNION, UNION ALL, INTERSECT, MINUS.

    Oracle SQL Functions

    Number Functions:

    Number functions accept numeric input and return numeric

    values.

    Example:

    ABS (n), ROUND (n [, m]), TRUNC (n [, m])

    Character Functions:

    Character functions accept character input and return either

    character or numeric values.

    Example:

    CONCAT (char1, char2), INITCAP (char), LOWER (char), LTRIM (char

    [, set]), LPAD (char, n [, char2])

    Group Functions:

    Default is to include all the candidate rows, but using

    DISTINCT causes the group functions to use only the

    distinct values of the argument expression. Example:

    AVG ([DISTINCT | ALL] n), COUNT (* | [DISTINCT | ALL] expr),

    MAX ([DISTINCT | ALL] expr), MIN ([DISTINCT | ALL] expr),

    STDDEV ([DISTINCT | ALL] n), SUM ([DISTINCT | ALL] n),VARIANCE ([DISTINCT | ALL] n)

    Date Functions and formats:

    Date functions operate on values of the DATE data type.

  • 7/28/2019 Introduction to Oracle on dba automation

    10/47

    All date functions return a value of DATE data type, except

    the MONTHS_BETWEEN function, which returns a

    number. Example:

    TRUNC (d [,fmt]), SYSDATE, ROUND (d[,fmt]), NEXT_DAY (d,char),

    NEW_TIME (d, a, b), MONTHS_BETWEEN (d, e)

    Conversion Functions:

    Conversion functions convert a value from one data type to

    another.

    Generally, the form of the function names follows the

    convention data type TO data type, the first data type is the

    input data type; the last data type is the output data type. Example:

    The SYSDATE function returns the current date and timefrom Oracle. If you want to only manipulate the CURRENT

    DATE, and you are not selecting other columns from a

    table, you may issue a SELECT statement using the Oracle

    one row table:

    SELECT SYSDATE FROM DUAL;

  • 7/28/2019 Introduction to Oracle on dba automation

    11/47

    Database Transaction

    Transaction consists of statement that make up of a consistent

    change to the data. A database traction consists of one of the following:

    DML statements which constitute one consistent change to

    the data. One DDL statement. One DCL statement.

    A transaction begin when the 1st DML statement is encounteredand ends when one of the following occur:

    A COMMIT or ROLLBACK is issued.

    A DDL statement such as create is issued.

    A DCL statement is issued.

    The user exits iSQL*plus. A machine fails or the system crashes.

    After transaction ends, the next executable statement automatically

    starts the next transaction.

    A DDL statement or a DCL statement is automatically committed

    and therefore implicitly ends the transaction.

  • 7/28/2019 Introduction to Oracle on dba automation

    12/47

    Database Objects

    There are several type of database objects:

    Table:

    It is a basic unit of storage composed of rows & columns.

    View:

    It logically represents subset of data from one or moretables.

    Sequence:

    It is used to generate primary key values.

    Index:

    Improves the performance of some queries.

    Synonym:

    It provides an alternative name for an object.

    Table

    It is a basic unit of storage composed of rows & columns.

    We dont need to specify size of the table at the time of creation.

    Table names & column names must begin with an alphabet. If a table does not belong to a user, the owner name must be prefix

    to the table.

    Creating a Table

    Syntax:

    CREATE TABLE [Schema].table_name(

    column_name datatype [DEFAULT

    expr][column_constraint].

    [table_constraint]

  • 7/28/2019 Introduction to Oracle on dba automation

    13/47

    );

    Example:

    CREATE TABLE emp

    (rollno number(5) CONSTRAINT emp_rollno_pkPRIMARY KEY,name varchar2(20) CONSTRAINT emp_name_nn NOT

    NULL,

    age number(2),

    CONSTRAINT emp_age_chk CHECK(age>20));

    To create a table, a user must have CREATE TABLE privilage.

    DEFAULT option prevents NULL values from entering the

    column.

    Constraint

    Unique constraint:

    Ensures that no two rows of a table can have duplicatevalues in a specific column or set of columns.

    Primary key constraint:

    Only one primary key can be created for a table.

    The primary key is column or set of columns that uniquely

    identifies each row in the table.

    The primary key constraint ensures that the columns cannotcontain null values.

    Foreign key constraint:

    The FOREIGN key REFRENCE integrity constraint

    gesignates a column or a combination of columns as a

    foreign key and establish a relationship between primary

    key and unique key in the same table or different table. A foreign key value must match an existing value in the

    parent table or be null. ON DELETE CASCADE:

    It deletes the dependent rows in the child table when

    a rpw in the parent table is deleted.

  • 7/28/2019 Introduction to Oracle on dba automation

    14/47

    ON DELETE SET NULL:

    It converts foreign key values to null when a row inparent table is removed.

    Without these two options, the row in the parent table cantbe deleted if it referenced in the child table.

    Check constraint:

    It defines a condition that each row must satisfy.

    The condition can use the same construct as queryconditions with the following exception:

    References to CURRVAL, NEXTVAL andROWNUM pseudo columns.

    Calls to SYSDATE, UID, USER, functions.

  • 7/28/2019 Introduction to Oracle on dba automation

    15/47

    Joining Tables

    Having a common column in two tables implies a relationship

    between two tables, the nature of relationship is determined by

    which table uses the column as the primary key. Sometimes we have to select data from two or more tables to make

    our result complete, we have to perform a join. The common column appearing in the child table is referred to as

    foreign key.

    Types of joins

    Oracle property joins:

    Equi join. Non-equi join.

    Outer join.

    Self join. Cartesian product.

    SQL:1999 Compliant joins:

    Natural join.

    Using clause.

    Full or left or right outer join.

    Arbitrary join condition using ON clause. Cross join.

  • 7/28/2019 Introduction to Oracle on dba automation

    16/47

    View

    A view is a logical table based on a table or another view.

    A view contains no data of its own but is like a window through

    which data from table can be viewed or changed. The view is stored as a select statement in the data dictionary.

    Advantages of Views

    View restricts access to a data because a view can display selected

    columns and rows from the table. View can be used to make a simple query to retrieve the result of

    complicated query.

    One view can be used to retrieve data from several tables.

    Creating a View

    Syntax:

    CREATE [OR REPLACE][FORCE/NOFORCE]VIEW view_name[(alias (, alias).)] AS sub query[WITH CHECK OPTION [CONSTRAINT

    constraint_name]]

    [WITH READ ONLY [CONSTRAINT constraint_name]];

    OR REPLACE Recreates the view if it exist.

    FORCE Creates the view regardless of whether or not thebase table exists.

    OFORCE Creates the view only if the base table exists.

    Alias Specify name for expression selected by the view

    query.

    WITH CHECK

    OPTION

    Specifies that only rows accessible to the view can

    be inserted or updated.

    WITH READ ONLY Ensures that no DML operation can be performed

    on this view.

    Example:

    CREATE VIEW v1SELECT ename, job, deptno

    FROM emp

    Where deptno=20;

  • 7/28/2019 Introduction to Oracle on dba automation

    17/47

    Removing a View

    Syntax:

    DROP VIEW view_name;

    Example:

    DROP VIEW v1;

    Sequence

    A sequence is a user created database object that can be shared by

    multiple user to generate a sequential series of unique integers.

    Normally a sequence is used to generate primary key values that

    must unique for each row.

    The sequence is generated & incremented by an internal Oracle

    Server routine. Two sequence methods

    NextVal:provides the next value in a sequence. CurrVal:provides the current value in a sequence.

    Creating a Sequence

    Syntax:

    CREATE SEQUENCE sequence_name

    [INCREMENT BY n]

    [START WITH n][{MAXVALUE n/NOMAXVALUE}]

    [{MINVALUE n/NOMINVALUE}]

    [{CYCLE/NOCYCLE}]

    [{CACHE n/NOCACHE}]INCREMENT BY n Interval by which the sequence is incremented or

    decremented (default value is 1).

    START WITH n First no. to be generated (default is 1).

    MAXVALUE Max. value to be generated.

    OMAXVALUE Specifies a max. value of 10^27 for an increasingsequence and -1 for a decreasing sequence.

    MINVALUE Min. value to be generated.

    OMINVALUE Specifies a min. value of 1 for an increasing

    sequence and(10^26) for a decreasing sequence.CYCLE/NOCYCLE Specifies whether the sequence continues to

  • 7/28/2019 Introduction to Oracle on dba automation

    18/47

    generate values after reaching its max. or min.

    values(default is NOCYCLE).

    CACHE/NOCACHE Specifies how many values the Oracle server

    preallocates and keep in memory(default is 20).

    Example:

    CREATE SEQUENCE seq

    INCREMENT BY 10START WITH 100

    MAXVALUE 1000

    CACHE 50;

  • 7/28/2019 Introduction to Oracle on dba automation

    19/47

    Removing a Sequence

    Syntax:

    DROP SEQUENCE sequence_name;

    Example:

    DROP SEQUENCE seq;

    Index

    An Oracle server index is a schema object that can speed up of

    retrieval of rows by using a pointer.

    An index provides direct & fast access to rows in a table.

    Once index is created, no direct activity required by the user.

    If we dont have index of a column , then a full table scan occurs. When we drop a table, corresponding index is automatically drop.

    Creating an Index

    Syntax:

    CREATE INDEX index_name

    ON table_name(column,column..);

    Example:

    CREATE INDEX CustNameIdxON CUSTOMER(Name);

    Removing an Index

    Syntax:

    DROP INDEX index_name;

    Example:

    DROP INDEX CustNameIdx;

    Synonym

    To refer to a table owned by another user we need to prefix the

    table name with the name of the user who create it followed by a

    period.

  • 7/28/2019 Introduction to Oracle on dba automation

    20/47

    Creating synonym eliminates the need to qualify the object name

    with the schema and provide us with an alternative name for atable, view, sequence, procedure, etc.

    Creating an Synonym

    Syntax:

    CREATE [PUBLIC] SYNONYM synonym_name FOR

    object;

    Example:

    CREATE PUBLIC SYNONYM loc

    FOR smith. location;

    Removing an Synonym

    Syntax:

    DROP SYNONYM synonym_name;

    Example:

    DROP SYNONYM loc;Error handling

    Prevents database locking.

    Ensures that errors are presented to the user in a sensible format. Makes code robust.

    Essential when using PL/SQL as formal programming language orinterfacing with Oracle applications.

    Grant & Revoke statement

    Use the GRANT statement to grant:

    System privileges to users and roles.

    Both privileges and roles are either local, global, or external.

    Grant roles to users and roles.

    To grant the CREATE SESSION system privilege to the sampleuser hr, allowing hr to log on to Oracle Database, issue the

    following statement:

  • 7/28/2019 Introduction to Oracle on dba automation

    21/47

    GRANT CREATE SESSION TO hr;

    To grant the dw_manager role with the ADMIN OPTION to thesample user sh, issue the following statement:

    GRANT dw_manager TO sh WITH ADMIN OPTION;

    Use the REVOKE statement to:

    Revoke system privileges from users and roles.

    Revoke roles from users and roles. Revoke object privileges for a particular object from users and

    roles.

    REVOKE UPDATE ON hr.employees FROM emp;

    Enterprise Manager Console

    The Oracle Enterprise Manager Console provides graphical

    facilities for managing an Oracle database.

    The utility can be used to manage:

    Database structures such as tables and views. User accounts, passwords, roles, and privileges.

    The Manager Console includes a SQL scratchpad for executingSQL statements.

    Application Logic

    Oracle database application can be processed using :

    Programming language to invoke Oracle DBMS commands. Stored procedures. Start command to invoke database commands stored in .sql

    files. Triggers.

  • 7/28/2019 Introduction to Oracle on dba automation

    22/47

    SQL*Plus

    Oracle SQL*Plus or the Oracle Enterprise Manager Console may

    be used to manage an Oracle database.

    SQL*Plus is a text editor available in all Oracle. Except inside quotation marks of strings, Oracle commands are

    case-insensitive. The semicolon (;) terminates a SQL statement.

    The right-leaning slash (/) executes SQL statement stored in Oracle

    buffer. SQL*Plus can be used to:

    Enter SQL statements.

    Submit SQL files created by text editors, e.g., notepad, toOracle.

    SQL*Plus Prompt

  • 7/28/2019 Introduction to Oracle on dba automation

    23/47

    Oracle PL/SQL

    Procedural Language/SQL (PL/SQL) is Oracle Corporations

    procedural language extension to SQL, the standard data accesslanguage for relational databases.

    PL/SQL offers modern software engineering features such as data

    encapsulation, exception handling, information hiding, object

    orientation, and brings state-of-the-art programming to the Oracle

    Server and toolset.

    PL/SQL incorporates many of the advanced features of

    programming languages that were designed during the 1970s and

    1980s.

    It allows the data manipulation and query statements of SQL to beincluded

    In block- structured and procedural units of code, making PL/SQL a

    powerful transaction processing language.

    With PL/SQL, you can use SQL statements to finesse Oracle data,

    and PL/SQL control statements to process the data.

    PL/SQL Environment

  • 7/28/2019 Introduction to Oracle on dba automation

    24/47

    PL/SQL is not an Oracle product in its own right,it is a technology

    used by the Oracle server and by certain Oracle tools.

    Blocks of PL/SQL are passed to and processed by a PL/SQL

    engine, which may reside within the tool or within the Oracle

    server. The engine that is used depends on where the PL/SQLblock is being invoked from.

    When you submit PL/SQL blocks from a Pro*C or a Pro*Cobol

    program, user-exit, iSQL*Plus, or Server Manager, the PL/SQL

    engine in the Oracle Server processes them.

    It separates the SQL statements and sends them individually to the

    SQL statements executor. A single transfer is required to send the block from the application

    to the Oracle Server, thus improving performance, especially in a

    client-server network.

    PL/SQL code can also be stored in the Oracle Server assubprograms that can be referenced by any number of applicationsconnected to the database.

    Benefits of PL/SQL

    Integration:

  • 7/28/2019 Introduction to Oracle on dba automation

    25/47

    PL/SQL plays a central role in both the Oracle server

    (through stored procedures, stored functions, database

    triggers, and packages) and Oracle development tools

    (through Oracle Developer component triggers).

    Oracle Forms Developer, Oracle Reports Developer, andOracle Graphics Developer applications make use of shared

    libraries that hold code (procedures and functions) and can

    be accessed locally or remotely.

    SQL data types can also be used in PL/SQL.

    Combined with the direct access that SQL provides, these

    shared data types integrate PL/SQL with the Oracle server

    data dictionary.

    PL/SQL bridges the gap between convenient access to

    database technology and the need for proceduralprogramming capabilities.

    PL/SQL in Oracle Tools:

    Many Oracle tools, including Oracle Developer, have their

    own PL/SQL engine, which is independent of the engine

    present in the Oracle Server.

    The engine filters out SQL statements and sends them

    individually to the SQL statement executor in the Oracle

    server. It processes the remaining procedural statements in the

    procedural statement executor, which is in the PL/SQL

    engine.

    The procedural statement executor processes data that is

    local to the application (that is, data already inside the client

    environment, rather than in the database).

    This reduces the work that is sent to the Oracle server andthe number of memory cursors that are required.

    Improved Performance:

    PL/SQL can improve the performance of an application.

    The benefits differ depending on the execution

    environment.

    PL/SQL can be used to group SQL statements togetherwithin a single block and to send the entire block to the

    server in a single call, thereby reducing networking traffic.

  • 7/28/2019 Introduction to Oracle on dba automation

    26/47

    Without PL/SQL, the SQL statements are sent to the Oracle

    server one at a time. Each SQL statement results in another

    call to the Oracle server and higher performance overhead.

    In a networked environment, the overhead can become

    significant. PL/SQL can also operate with Oracle Server application

    development tools such as Oracle Forms and Oracle

    Reports.

    By adding procedural processing power to these tools,

    PL/SQL enhances performance.

    You can take advantage of the procedural capabilities ofPL/SQL, which are not available in SQL.

    PL/SQL Block Structure:

    Every unit of PL/SQL comprises one or more blocks.

    These blocks can be entirely separate or nested one within

    another.

    The basic units (procedures, functions, and anonymous

    blocks) that make up a PL/SQL program are logical blocks,

    which can contain any number of nested sub blocks.

    Therefore, one block can represent a small part of another

    block, which in turn can be part of the whole unit of code.

    Modularized Program Development:

    Group logically related statements within blocks. Nest subblocks inside larger blocks to build powerful

    programs.

    Break down a complex problem into a set of manageable,

    well-defined, logical modules and implement the modules

    with blocks. Place reusable PL/SQL code in libraries to be shared

    between Oracle Forms and Oracle Reports applications or

    store it in an Oracle server to make it accessible to anyapplication that can interact with an Oracle database.

    Portability:

    Because PL/SQL is native to the Oracle server, you can

    move programs to any host environment (operating system

    or platform) that supports the Oracle server and PL/SQL.

  • 7/28/2019 Introduction to Oracle on dba automation

    27/47

    In other words, PL/SQL programs can run anywhere the

    Oracle server can run,you do not need to tailor them to each

    new environment.

    You can also move code between the Oracle server and

    your application. You can write portable program packagesand create libraries that can be reused in differentenvironments.

    Identifiers:

    In PL/SQL you can use identifiers to do the following:

    Declare variables, cursors, constants, and exceptions and

    then use them in SQL and procedural statements.

    Declare variables belonging to scalar, reference, composite,and large object (LOB) data types.

    Declare variables dynamically based on the data structure oftables and columns in the database.

    Procedural Language Control Structures:

    Procedural Language Control Structures allow you to dothe following:

    Execute a sequence of statements conditionally.

    Execute a sequence of statements iteratively in a loop. Process individually the rows returned by a multiple-row

    query with an explicit cursor.

    Errors:

    The Error handling functionality in PL/SQL allows youto do the following:

    Process Oracle server errors with exception-handling

    routines.

    Declare user-defined error conditions and process them with

    exception-handling routines.

    PL/SQL Block Structure

  • 7/28/2019 Introduction to Oracle on dba automation

    28/47

    The Declerative section contains all variables, constants, cursors,and userdefined exceptions that are referenced in the executableand declarative sections.

    Executable section contains SQL statements to manipulate data in

    the database and PL/SQL statements to manipulate data in the

    block.

    Exception handling section Specifies the actions to perform whenerrors and abnormal conditions arise in the executable section.

    DBMS_OUTPUT.PUT_LINE

    DBMS_OUTPUT is an oracle supplied package and PUT_LINE is

    a procedure within that package.

    This procedure is used to display output on the screen.

    We must set the SERVEROUTPUT variable to ON before we usedthe DBMS_OUTPUT.PUT_LINE.

  • 7/28/2019 Introduction to Oracle on dba automation

    29/47

    Example:

    SET SERVEROUTPUT ONDEFINE p_annual_sal = 60000

    DECLAREv_sal NUMBER(9,2) := &p_annual_sal;

    BEGIN

    v_sal := v_sal/12;DBMS_OUTPUT.PUT_LINE (The monthly salary is

    || TO_CHAR(v_sal));

    END;

    Handling Variables in PL/SQL

    Declare and initialize variables in the declaration section.

    Assign new values to variables in the executable section.

    Pass values into PL/SQL blocks through parameters. View results through output variables.

    Types of Variables

    PL/SQL variables:

    Scalar

    hold a single value.

    Composite

    allow groups of fields to be defined and manipulated inPL/SQL blocks.

    Reference

    hold values, called pointers, that designate other programitems.

    LOB (large objects)

    hold values, called locators, that specify the location of

    large objects (for example graphic images) that are storedout of line.

    Non-PL/SQL variables:

  • 7/28/2019 Introduction to Oracle on dba automation

    30/47

    Bind and host variables

    host (or bind) variables can be used to pass run timevalues out of the PL/SQL block back to the iSQL*Plus

    environment.

    Declaring PL/SQL Variables

    Syntax:

    identifier [CONSTANT] datatype [NOT NULL][:= | DEFAULT expr];

    Examples:

    DECLAREv_hiredate DATE;

    v_deptno NUMBER(2) NOT NULL := 10;

    v_location VARCHAR2(13) := Atlanta;

    c_comm CONSTANT NUMBER := 1400; v_mgr

    NUMBER(6) DEFAULT 100;

    Identifier: is the name of the scalar variable.

    Expr: can be a variable, literal, or function call, but not adatabase column. DEFAULT:You can use the DEFAULT keyword instead of

    the assignment operator to initialize variables.

    NOT NULL:Impose the NOT NULL constraint when thevariable must contain a value.

    SELECT Statements in PL/SQL

    The INTO clause is required.

    Queries must return one and only one row. Syntax:

    SELECT select_listINTO {variable_name[, variable_name]...

    | record_name}

    FROM table

    [WHERE condition];

  • 7/28/2019 Introduction to Oracle on dba automation

    31/47

    Operators in PL/SQL

    Operator Operation** Exponentiation

    +, - Identity, negation

    *, / Multiplication, division

    +, -, || Addition, subtraction, concatenation

    =, , =, , !=,~=, ^=, IS NULL, LIKE,BETWEEN, IN

    Comparison

    OT Logical negation

    AND Conjunction

    OR Inclusion

    Controlling PL/SQL Flow of Execution

    You can change the logical execution of statements using

    conditional IF statements and loop control structures.

    Conditional IF statements:

    Syntax:

    IF condition THEN

    Statements;[ELSIF condition THENStatements;]ELSE

    Statements;]END IF;

    There are 3 forms of IF statement:

    IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF

    CASE Expressions:

    Syntax:

    CASE selectorWHEN expression1 THEN result1

    WHEN expression2 THEN result2

  • 7/28/2019 Introduction to Oracle on dba automation

    32/47

    ...WHEN expressionN THEN resultN[ELSE resultN+1;]

    END;

    Basic loop:

    Syntax:

    LOOPstatement1;. . .

    EXIT [WHEN condition];

    END LOOP;

    condition is a Boolean variable or expression (TRUE,

    FALSE,

    or NULL);

    WHILE Loops:

    Syntax:

    WHILE condition LOOP

    statement1;statement2;

    . . .

    END LOOP;

    Condition is evaluated at the beginning of each iteration.

    FOR Loops:

    Syntax:

    FOR counter IN [REVERSE]

    lower_bound..upper_bound LOOP

    statement1;statement2;. . .

    END LOOP;

    Do not declare the counter; it is declared implicitly.

  • 7/28/2019 Introduction to Oracle on dba automation

    33/47

    Composite Data Types

    PL/SQL Records:

    A record is a group of related data items stored in fields,each with its own name and data type.

    Each record defined can have as many fields as necessary.

    Records can be assigned initial values and can be defined as

    NOT NULL.

    We can define RECORD types and declare user-defined

    records in the declarative part of any block, subprogram, or

    package. We can declare and reference nested records. One record

    can be the component of another record. Syntax:

    TYPE type_name IS RECORD (field_declaration[, field_declaration]);

    identifier type_name;Where field_declaration is:

    field_name {field_type | variable%TYPE

    | table.column%TYPE | table%ROWTYPE}

    [[NOT NULL] {:= | DEFAULT} expr]

    Example:

    TYPE emp_record_type IS RECORD

    (last_name VARCHAR2(25),

    job_id VARCHAR2(10),

    salary NUMBER(8,2));emp_record emp_record_type;

    The %TYPE Attribute

    Declare a variable according to:

    A database column definition. Another previously declared variable.

    Prefix %TYPE with:

    The database table and column.

    The previously declared variable name.

  • 7/28/2019 Introduction to Oracle on dba automation

    34/47

    The ROW%TYPE Attribute

    Declare a variable according to a collection of columns in a

    database table or view.

    Prefix %ROWTYPE with the database table. Fields in the record take their names and data types from the

    columns of the table or view.

    INDEX BY Tables:

    Are composed of two components:

    Primary key of data type BINARY_INTEGER. Column of scalar or record data type.

    Can increase in size dynamically because they are

    unconstrained. Syntax:

    TYPE type_name IS TABLE OF

    {column_type|variable%TYPE

    |table.column%TYPE}[NOT NULL]| table.%ROWTYPE

    [INDEX BY BINARY_INTEGER];Identifier type_name;

    Example:

    TYPE ename_table_type IS TABLE OFEmployees.last_name%TYPE

    INDEX BY BINARY_INTEGER;

    ename_table ename_table_type;

    Trapping Exceptions

    Here we define the actions that should happen when an exception

    is thrown. Example Exceptions:

    NO_DATA_FOUND

    TOO_MANY_ROWS ZERO_DIVIDE

    When handling an exception, consider performing a rollback.

  • 7/28/2019 Introduction to Oracle on dba automation

    35/47

    Example:

    DECLARE num_row number_table%ROWTYPE; BEGINselect * into num_row from number_table;

    dbms_output.put_line(1/num_row.num); EXCEPTIONWHEN NO_DATA_FOUND THEN

    dbms_output.put_line('No data!'); WHEN

    TOO_MANY_ROWS THEN dbms_output.put_line('Too

    many!'); WHEN OTHERS THEN

    dbms_output.put_line(Error); end;

    Transaction Control Statements

    Initiate a transaction with the first DML command to follow a

    COMMIT or ROLLBACK.

    Use COMMIT and ROLLBACK SQL statements to terminate atransaction explicitly.

  • 7/28/2019 Introduction to Oracle on dba automation

    36/47

    PL/SQL Blocks

    There are 3 types of blocks:

    Anonyms:

    It is a block code without anyname.

    Procedure:

    It is a named block that does some processing but does notreturn any result to the calling environment.

    Function:

    It is also a named block of code & it returns result to thecalling environment.

    Procedure

    A Procedure is a type of subprogram that performs an action and

    does not return a value.

    It is a name of PL/SQL block that can accept parameter and can beremoved.

    It can be compiled and stored in the database as a schema object.

    Promotes reusability and maintainability. Modes:

    IN

    procedure must be called with a value for the parameter. Value cannot be changed.

    OUT

    Procedure must be called with a variable for the parameter. Changes to the parameter are seen by the user (i.e., call by

    reference).

    IN OUT

    Value can be sent, and changes to the parameter are seen bythe user.

  • 7/28/2019 Introduction to Oracle on dba automation

    37/47

    Default Mode is: IN.

    Creating Procedures

    Syntax:

    CREATE [OR REPLACE] PROCEDURE

    procedure_name

    [(parameter1 [mode1] datatype1,

    parameter2 [mode2] datatype2,

    . . .)]

    IS|ASPL/SQL Block;

    Example:

    Create or replace query_emp(p_id IN

    emp.empno%TYPE, p_name OUT emp.ename%TYPE)

    BEGIN

    SELECT ename, sal, deptno INTO p_name, p_sal,

    p_deptno from emp Where empno=p_id; END;

    ISQL*PLUS-Execute query_emp(1046,:name); PRINTNAME

    Removing Procedure

    Drop a procedure stored in the database.

    Syntax:

    DROP PROCEDURE procedure_name;

    Example:

    DROP PROCEDURE query_emp;

    Function

    A function is a named PL/SQL block that can return a value. A function can be stored in the database as a schema object for

    repeated execution. A function is called as part of an expression.

    Creating Function

  • 7/28/2019 Introduction to Oracle on dba automation

    38/47

    Syntax:

    CREATE [OR REPLACE] FUNCTION function_name[(parameter1 [mode1] datatype1,

    parameter2 [mode2] datatype2,. . .)]

    RETURN datatype

    IS|ASPL/SQL Block;

    Example:

    CREATE [OR REPLACE] FUNCTION squareFunc (

    num IN number )

    RETURN numberIS

    BEGIN

    return num*num;

    END;

    Using the function

    BEGIN dbms_output.put_line(squareFunc(3.5)); END;

    Removing Function

    Drop a function stored in the database. Syntax:

    DROP FUNCTION function_name;

    Example:

    DROP FUNCTION squarefunc;

  • 7/28/2019 Introduction to Oracle on dba automation

    39/47

    Database Trigger

    A database trigger is a procedure that is run automatically when an

    event occurs.

    The event could be an insert, a deletion, or even a selection of datafrom a table.

    For example, we might define a trigger that is executed whensomeone attempts to insert a row into a table, and the triggerchecks that the inserted data is valid.

    Types of Triggers

    On the basis of timing when the trigger is executed

    Before and After trigger:

    Triggers can be executed before and after insert, update anddelete.

    Instead of trigger:

    Used to tell ORACLE what to do instead of performing the action that

    invoked the trigger.

    On the basis of level at which the trigger is executed

    Row level trigger:

    The trigger body executes once for each row affected by the triggeringevent.

    Statemant level trigger:

    The trigger body executes once for the triggering event. This is the default.

    Schema trigger:

    We can triggers on schema level operations such as ceate, alter, drop etc.

    These triggers provides to capabilities preventing DDL operation andproviding additional security, monitoring when DDL operation occurs.

  • 7/28/2019 Introduction to Oracle on dba automation

    40/47

    Database trigger:

    We can create trigger to be fired on database events such as logon, logout,shutdown, errors etc.

    Creating DML Triggers

    Syntax:

    CREATE [OR REPLACE] TRIGGER trigger_nametimingevent1 [OR event2 OR event3]ON table/view name[REFERENCING OLD AS old | NEW AS new][FOR EACH ROW]

    [WHEN (condition)]trigger_body

    Trigger_name Is the name of the triggertiming Indicates the time when the trigger fires in

    relationto the triggering event:

    BEFORE,AFTER,INSTEAD OF

    Event Identifies data manipulation operation that causes

    thetrigger to fire: INSERT, UPDATE, DELETE

    Table name Indicates the table associated with the trigger

    REFERENCING Specifies correlation names for the old and newvalues of the current row (The defaults are OLD

    and NEW)

    FOR EACHROW

    Designates that the trigger is a row trigger

    WHEN Specifies the trigger restrictiontrigger body Is the trigger body that defines the action performed

    by the trigger, beginning with eitherDECLARE or

    BEGIN, ending with END, or a call to a procedure

    Example:

    CREATE OR REPLACE TRIGGER secure_empBEFORE INSERT ON employees

    BEGIN

  • 7/28/2019 Introduction to Oracle on dba automation

    41/47

    IF (TO_CHAR(SYSDATE,DY) IN (SAT,SUN))

    OR(TO_CHAR (SYSDATE,HH24: MI)

    NOT BETWEEN 08:00 AND 18:00)

    THEN RAISE_APPLICATION_ERROR (-20500,youmay Insert into EMPLOYEES table only During

    business hours.);END IF;

    END;

    Disabling and Dropping Triggers

    To remove a trigger:

    DROP TRIGGER trigger_name;

    To disable/enable a trigger:

    ALTER TRIGGER trigger_name [ENABLE | DISABLE];

    Example:

    DROP TRIGGER secure_emp; ALTER TRIGGER secure_emp DISABLE;

    Note:

    All triggers on a table are dropped when the

    table is dropped.

    Cursor

    A cursor can be visualized as an array that is used to store one or

    more rows return by query. Whenever you issue a SQL statement, the Oracle server opens an

    area of memory in which the command is parsed and executed.

    This area is called a cursor. There are two types of cursors:

    Implicit cursors:

    Are declared by PL/SQL engine implicitly for all DML and

    PL/SQL select statement, including query that return only

    one row.

  • 7/28/2019 Introduction to Oracle on dba automation

    42/47

    Explicit cursors:

    For query that return more than one row, explicit cursor aredeclared and named by the programmer.

    Step to use a cursor:

    Declare the cursor

    Syntax:

    CURSOR cursor_name is SELECT statement;

    Open the cursor

    Syntax:

    OPEN cursor_name;

    Retrieve data using the fetch statement

    Synatx:

    FETCH cursor_name INTO variable;

    Close the cursor

    Synatx:

    CLOSE cursor_name;

    Example:

    v_empid number;Cursor cur_sample is

    Select empid from employeewhere grade > 4;Begin

    open cur_sample;loopfetch cur_sample into v_empid;

    exit when cur_sample%notfound;

    update employeeset salary = salary + 500

  • 7/28/2019 Introduction to Oracle on dba automation

    43/47

    where empid = v_empid;end loop;End;

    SQL Cursor Attributes

    There are four attributes that can be apply to cursor

    %rowcount:

    Returns the number of rows fetch by the cursor so far (aninteger value).

    %found:

    Boolean attribute that evaluates to TRUE if the previousfetch returns a row else FALSE.

    %notfound:

    Boolean attribute that evaluates to TRUE if previous fetchdid not returns a row else FALSE.

    %isopen:

  • 7/28/2019 Introduction to Oracle on dba automation

    44/47

    Boolean attribute that evaluates to TRUE if cursor isopen,FALSE otherwise.

    Cursor FOR Loops

    Syntax:

    FOR record_name IN cursor_name LOOPstatement 1;

    statement 2;

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

    END LOOP;

    The cursor FOR loop is a shortcut to process cursors.

    Implicitly opens, fetches, and closes cursor. The record is implicitly declared. Example:

    DECLARECURSOR emp_cursor IS

    SELECT ename, deptno

    FROM emp;BEGIN

    FOR emp_record IN emp_cursor LOOP-- implicit open and implicit fetch occur

    IF emp_record.deptno = 30 THEN

    ...END LOOP; -- implicit close occursEND;

    Package

    Packages bundle related PL/SQL types, items, and subprograms

    into one container. A package usually has a specification and a body, stored separately

    in the database. The package specification declares the types, variables, constants,

    exceptions, cursors, and subprograms available for use.

    The body fully defines cursors and subprograms, and so

    implements the specification. When you call a packaged PL/SQL construct for the first time, the

    whole package is loaded into memory.

    Scope of the Description Placement within the

  • 7/28/2019 Introduction to Oracle on dba automation

    45/47

    Construct Package

    Public Can be referenced from anyOracle server environment

    Declared within the packagespecification and may be

    defined within the package

    bodyPrivate Can be referenced only by

    other constructs which are

    part of the same package

    Declared and defined within

    the package body

    Creating the Package Specification

    Syntax:

    CREATE [OR REPLACE] PACKAGE package_name

    IS|ASpublic type and item declarationssubprogram specificationsEND package_name;

    Example:

    CREATE OR REPLACE PACKAGE comm_package ISg_comm NUMBER := 0.10; --initialized to 0.10PROCEDURE reset_comm

    (p_comm IN NUMBER);

    END comm_package;

    Creating the Package Body

    Syntax:

    CREATE [OR REPLACE] PACKAGE BODY package_nameIS|AS

    private type and item declarations

    subprogram bodiesEND package_name;

    Example:

    CREATE OR REPLACE PACKAGE BODY comm_package

    IS

    FUNCTION validate_comm (p_comm IN NUMBER)

    RETURN BOOLEAN

    ISv_max_comm NUMBER;

  • 7/28/2019 Introduction to Oracle on dba automation

    46/47

    BEGINSELECT MAX(commission_pct)INTO v_max_comm

    FROM employees;

    IF p_comm > v_max_comm THEN RETURN(FALSE);ELSE RETURN(TRUE);END IF;END validate_comm;

    Removing Packages

    To remove the package specification and the body, use thefollowing syntax:

    DROP PACKAGE package_name;

    To remove the package body, use the following syntax :

    DROP PACKAGE BODY package_name;

  • 7/28/2019 Introduction to Oracle on dba automation

    47/47

    I took assistance and consulted from the underneath namedsources of information:

    Introduction_To_Oracle9i_SQL_Student_Guide. Introduction_To_Oracle9i_PL-SQL_Student_Guide. Official website of IBM.

    ww.oracle.com

    Encyclopedia website.

    www.wikipedia.com

    http://www.ibm.com/http://www.ibm.com/http://www.wikipedia.com/http://www.wikipedia.com/http://www.wikipedia.com/http://www.ibm.com/