SSTL Oracle SST Prst Ver1.0

download SSTL Oracle SST Prst Ver1.0

of 75

Transcript of SSTL Oracle SST Prst Ver1.0

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    1/75

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    2/75

    Welcome to ORACLE

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    3/75

    Course Overview

    SQL

    SQL Basics

    Datatypes

    DDL Commands Integrity Constraints

    DML Commands

    TCL Commands

    Simple Select

    Select with various Clauses

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    4/75

    Course Overview contd

    Joins Sub-Queries

    Correlated Subqueries

    Views

    Synonyms

    Indexes

    Snapshots

    SQL * Plus Commands

    Set Commands

    SQL * Plus Reports

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    5/75

    Course Overview contd

    PL/SQL Programming

    Basic of PL/SQL

    Anonymous blocks

    Insert, Update, Delete and Select Using AnonymousBlock

    Cursors (Implicit and Explicit Cursors)

    Exception Handling

    Stored Procedures and Functions Packages

    Triggers

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    6/75

    Oracle SQL

    SQL was developed by IBM Corporation in mid 1970s

    Adapted and implemented by Oracle Corporation

    ANSI adopted SQL as a Standard Language for

    RDBMS in OCT 1986.

    Features

    Non- Procedural Language

    Unified Language Common Language for Relational Databases

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    7/75

    SQL

    SQL :

    DDL : Data Definition Language

    DML : Data Manipulation Language

    TCL : Transaction Control Language

    DQL : Data Query Language

    DCL : Data Control Language

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    8/75

    Database Objects

    Used to manipulate data

    Oracle supports different kinds of Data Objects

    Tables

    Views

    Indexes

    Synonyms

    Snapshots

    Sequences

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    9/75

    Table

    Table

    A place to store data of a particular type

    Data is organised in tables in form of rows and columns

    DDL: Used to define data objects

    We can Create, Alter, Drop, Alter , Rename and

    Truncated the objects.

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    10/75

    DDL

    Table Creation

    Syntax :

    SQL > Create table

    ( Col_name 1 datatype(size) constraint,:

    :

    Col_name n datatype(size) constraint,

    Table Level Constraints

    );

    Table Created.

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    11/75

    Elements of Oracle SQL

    Data Types

    number(p, s)

    char (size)

    varchar2 (size)

    long

    raw

    long raw

    date

    timestamp (fractional seconds precision)

    bfile

    blob

    clob

    nclob

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    12/75

    Constraints

    Constraint is condition that is applied over a table

    Oracle Supports Five type of Constraints

    Unique Not Null

    Primary key

    Check

    Foreign key

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    13/75

    DDL Alter table

    Altering TablesModify column

    Syntax :

    SQL> alter table modify ( column_name datatype[Constraint]);

    Altering TablesAdding column

    Syntax :

    SQL> alter table add ( column_name datatype[Constraint]);

    Altering TablesDrop column

    Syntax :SQL> alter table drop column

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    14/75

    SQL statements

    DDL- Rename, Drop and Truncate

    Renaming Oracle Table

    syntax:

    SQL> Rename to

    Dropping a Table

    syntax: DROP TABLE table_name;

    DROP table table_name cascade constraints

    Truncating a Table

    Syntax: Truncate table

    It remove all the rows of the table permanently

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    15/75

    SQL statements

    Data Manipulation Language

    INSERT

    Full phase insertion INSERT INTO departments VALUES (280, 'Recreation', 121, 1700);

    Partial Insertion Insert into table_name(columnnames) values ( val1,val2,val3)

    Insertion using Substitutional Parameters

    Insert into table_name(column names) values( &label1, &label2);

    Insertion from other table Insert into table_name select statement.

    Ex:- insert into emp_new (select * from emp)

    select into emp_new from emp;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    16/75

    Data Manipulation Language

    UPDATE

    Syntax:

    Update set

    Col_name1= val1,

    Col_name2=val2,:

    :

    Col_name N=val N [ Where condition ]

    Ex 1 : update emp set sal=30000;Ex 2 : Update emp set sal= sal+sal where job=MANAGER

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    17/75

    Data Manipulation Language

    DELETE

    Syntax :

    Delete from [ where condition]

    Ex : 1

    Delete from emp;

    Delete from emp where job=MANAGER

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    18/75

    SQL statements

    Transaction Control Language(TCL)

    Commit

    Use the COMMIT statement to end your current transaction and

    make permanent all changes performed in the transaction.

    Rollback

    Use the ROLLBACK statement to undo work done in the currenttransaction

    Savepoint

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    19/75

    SQL statements

    Transaction Control Language(TCL)

    Use the SAVEPOINT statement to identify a point in a

    transaction to which you can later roll back.Example:

    UPDATE employees SET salary = 7000

    WHERE last_name = 'Banda';

    SAVEPOINTsp1;

    UPDATE employees SET salary = 12000 WHERE last_name = 'Greene';

    SAVEPOINTsp2;

    SELECT SUM(salary) FROM employees;

    ROLLBACK TO SAVEPOINTbanda_sal;

    UPDATE employees SET salary = 11000 WHERE last_name = 'Greene';COMMIT;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    20/75

    Simple SELECT

    Selecting All Columns in All Rows

    Syntax : Select * from table_name

    Select Few Columns in All RowsSyntax : Select * from table_name

    Select with Where clause

    Syntax : Select * from table_name [where Condition]

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    21/75

    SELECT

    Order by clauseSyntax : Select * from table_name order by column_name [asc / desc]

    Unique/Distinct Clause

    Select unique job from emp;

    Select count(distinct dept) from emp

    Retrieval Using SQL Operators

    ( IN, Between and , Like, IS)

    Retrieval Using Column Alias Names

    Retrieval Using Substitution Parameters

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    22/75

    SELECT

    Retrieval Using Group by:

    Used to divide the rows into smaller groups

    The where clause cannot be applied to the grouped

    result

    Retrieval Using Having Clause :

    To specify conditions on groups of rows which are grouped by

    Group by clause

    Retrieval from Multiple tables :

    ( Union, Intersect,Difference and Cartesian Product)

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    23/75

    Joins

    Ajoinis used to combine rows from multiple tables. A

    join is performed whenever two or more tables is listed

    in the FROM clause of an SQL statement.

    There are different kinds of joins.

    Inner Join

    Outer Join

    Self Joins

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    24/75

    Joins

    Inner Join

    Inner joins return all rows from multiple tables where the

    join condition is met.

    Inner joins can be classified into: Equi Join

    Non- Equi Join

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    25/75

    Joins

    Outer Join

    This type of join returns all rows from one table and only

    those rows from a secondary table where the join

    condition is met.

    Outer joins can be further classified into: Left Outer Join

    Right Outer Join

    Full Outer Join

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    26/75

    Joins

    Left Outer Join

    LEFT JOIN or LEFT OUTER JOIN

    The result set of a left outer join includes all the rows from the

    left table specified in the LEFT OUTER clause, not just the

    ones in which the joined columns match. When a row in the left

    table has no matching rows in the right table, the associated

    result set row contains null values for all select list columns

    coming from the right table.

    Example:

    Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e ,

    dept d where e.deptno=d.deptno(+)

    J i

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    27/75

    Joins

    Right Outer Join

    A right outer join is the reverse of a left outer join. All

    rows from the right table are returned. Null values are

    returned for the left table any time a right table row has

    no matching row in the left table.

    Example :

    Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from

    emp e , dept d where e.deptno(+)=d.deptno

    Joins

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    28/75

    Joins

    Full Outer Join

    A FULL OUTER JOIN returns all rows in both the left and right tables.

    Any time a row has no match in the other table, the select list columns

    from the other table contain null values.

    Example:Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e , dept d

    where e.deptno=d.deptno(+)

    Union

    Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e , dept d where

    e.deptno(+)=d.deptno

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    29/75

    Sub Query

    A query result can also be used in a condition of a where

    clause. In such a case the query is called a sub query

    and the complete select statement is called a nested

    query.

    Example:

    Select * from emp where deptno=(select deptno from dept where

    dname=ADMIN

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    30/75

    Correlated sub queries

    Correlated sub queries also known as a repeating

    subquery. This means that the subquery is executed

    repeatedly, once for each row that might be selected by

    the outer query

    Example : Retrieve all employees whose salary is > avg sal of the

    same job employees.

    Select * from emp e where sal>(select avg(sal) from emp where job=

    e.job

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    31/75

    SQL Functions

    Arithmetic functions

    (ABS, POWER,SQRT, ROUND, TRUNC,MOD,SIGN,LN,

    CEIL, FLOOR, SIN,COS,TAN,SINH,COSH)

    Character Functions

    ( Length, ASCII,CHR, SUBSTR,INSTR, REPLACE,

    UPPER, LOWER, INITCAP)

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    32/75

    SQL Functions

    Date & Time Functions

    (Add_months,Last_Day,Months_between,Next_Day,Sys

    date)

    Conversion functions

    ( To_char,To_date, To_num)

    Aggregate functions(Max, Min, Count, sum, avg, stddev)

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    33/75

    Views

    A view can be used in the same way as a table

    Rows can be retrieved from a view

    Rows are not physically stored

    Rows can even be modified with some limitations

    A view is evaluated each time it is accessed

    In Oracle SQL no insert, update, or delete modifications

    on the complex view

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    34/75

    Advantages of Views

    Advantages of Views Focus the Data for Users

    Focus on important or appropriate data only

    Limit access to sensitive data

    Mask Database Complexity Hide complex database design

    Simplify complex queries, including distributed queries toheterogeneous data

    Simplify Management of User Permissions

    Improve Performance

    Organize Data for Export to Other Applications

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    35/75

    Views

    Type of Views

    Simple View

    Complex View

    Creating a view

    Create [or replace] view view_name as select statement

    Viewing Existing Views

    Sql > Select * from user_views;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    36/75

    Synonyms

    A synonym is a database object created over a table

    It is just alias name for a table

    Used to refer long table names

    Used to refer other users objects

    Creating a synonym

    Syntax :SQL> create [public] synonym syn_name for [user.] tablename.

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    37/75

    Indexes

    Like any other object indexes also stored in thedatabase

    Used to retrieve data at a faster stream

    Prevents duplication of data

    Null values are not stored in Indexes

    Types Of Indexes

    1. Unique Index

    2. Non-Unique Index3. Single column Index

    4. Concatenated Index

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    38/75

    Indexes

    Creating IndexesSyntax :

    SQL> Create [Unique] index Index_name on table_name(col_names)

    Viewing IndexesSyntax :

    SQL> select * from user_indexes;

    Droping IndexesSyntax :

    SQL > Drop index Index_name;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    39/75

    Snapshots

    A snapshot is a virtual table very equaling to that of a

    view but the only difference is we cannot perform any

    DML operations using a snapshot.

    These are created by DBA only.

    Creating a Snapshot

    Syntax :

    SQL> Create snapshot snap_name as select query;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    40/75

    Sequence Generator

    A sequence generator is a database object used to generatesequence numbers from a starting value to ending value with aspecified increment.

    A sequence generator can retrieve unique values only

    We can alter a sequence generator

    Sequence generator values can be used in select, insert, updatestatements.

    Outermost query of a subquery

    Creating a Sequence:

    Syntax:

    SQL> Create squence seq_nameStartwith N

    Maxvalue M

    Increment by value;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    41/75

    Sequence Generator

    To retrieve values from sequence we can use pseudo

    columns:

    1. Currval: gives current sequence number

    2. Nextval : Next successive sequence number

    Altering a sequence:

    Syntax:

    Alter sequence seq_name maxvalue N increment by X;

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    42/75

    Data Control Language- Privileges

    Privilege is a right to access an object from the

    database.

    There are two types of privileges

    Object Privileges : works on a particular object

    System privileges : works on a class of objects

    Object Privileges are granted by the owner of the object

    System privileges are granted by the DBA.

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    43/75

    Data Control Language- Privileges

    Granting Object Privileges

    Revoking Object Privileges

    Granting System Privileges

    Revoking System Privileges

    C

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    44/75

    Data Control Language- Roles

    A set of privileges

    User must have Create Role privilege to create a role

    Predefined Roles

    Connect Includes the following system privileges: ALTER SESSION, CREATE CLUSTER, CREATE DATABASE LINK, CREATE SEQUENCE, CREATE SESSION, CREATE

    SYNONYM, CREATE TABLE, CREATE VIEW

    ResourceIncludes the following system privileges: CREATE CLUSTER, CREATE INDEXTYPE, CREATE OPERATOR, CREATE PROCEDURE, CREATE

    SEQUENCE, CREATE TABLE, CREATE TRIGGER, CREATE TYPE

    DBA All privileges with Admin Option

    User defined Roles

    Users can create roles and assign to users

    E ti d t i fl t fil

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    45/75

    Exporting data in flat files

    Spool

    sqlplus provides the command spool to save query

    results to a file. At the SQL> prompt, you say:

    spool on;

    And a file called foo.lst will appear in your current

    directory and will record all user input and system

    output, until you exit sqlplus or type:

    spool off;

    Note that if the file foo.lst existed previously, it will be

    overwritten, not appended.

    SQL *Pl C d

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    46/75

    SQL *Plus Commands

    Cl scr

    Desc

    Save

    Execute

    List

    Run

    Append

    Edit , Host Edit Pause

    C t i i th SQL*Pl i t

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    47/75

    Customizing the SQL*Plus environment

    SQL*Plus offers several handy features you can use to control yourSQL*Plus session.

    Set Autocommit on/off

    Set Heading on/off

    Set linesize size

    Set Pagesize size

    Set Sqlpromptprompt

    Set time on/off

    Set Verifyon/off

    Set UnderlineOn/off

    Set SqlTerminator

    Set Wrap on/off

    O l D t Di ti

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    48/75

    Oracle Data Dictionary

    Oracle stores all information about the objects of a

    particular database in a system database that is called

    data dictionary.

    Metadata

    System views are divided into three groups: USER, ALL,

    and DBA

    A view of USER group will have its name starting as

    USER_view_name.

    USER group views have information about the objects

    owned by the user.

    DBA group views are only available to the DBAs.

    S t VIEWS

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    49/75

    Sys tem VIEWS

    Oracle Object Relevant Views

    TABLES USER_TABLES, CAT, TABSUSER_TAB_COLUMNS

    USER_COL_COMMENTS,

    USER_TAB_COMMENT

    USER_OBJECTS

    CONSTRAINTS USER_CONSTRAINTS,USER_CONS_COLUMNS

    USER_OBJECT

    INDEXES USER_INDEXES,

    USER_IND_COLUMNS,USER_OBJECT

    PROCEDURE USER_SOURCE,USER_OBJECT

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    50/75

    PL/SQL Programming

    Wh t I PL/SQL?

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    51/75

    What Is PL/SQL?

    PL/SQL is Oracle's procedural extension to industry

    standard Structured Query Language (SQL).

    PL/SQL extends the SQL by adding several features,

    which are common in other high level programming

    languages like C, Ada etc.

    It is full-fledged programming language that provides

    block structure programming, strongly typed variables ,

    conditional statements, loops, data encapsulation,

    information hiding, exception handling etc.

    PL/SQL

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    52/75

    Anonymous block

    Anonymous blocks do not have any name that is why we can't store

    them in the database server. Of course, we can store them in a text

    file and run them by executing that file in SQL*PLUS environment.

    Anonymous blocks cannot be called by another block and they are

    compiled at runtime.

    An anonymous block may have a named function or procedure in its

    declaration section. Such function or procedure can only be called

    from the execution section of the same anonymous block.

    PL/SQL

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    53/75

    Declare

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

    ----------------- Declaration Section

    Begin

    ---------------- Executable part

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

    Exception

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

    -------------Exception handling part

    End

    Ex:-

    declareemployee_name emp.ename%type;emp_salary emp.sal%type;

    beginSELECT ename, sal into employee_name, emp_salaryFROM empWHERE ename = 'KING';

    DBMS_OUTPUT.PUT_LINE(employee_name || ' is president');DBMS_OUTPUT.PUT_LINE('President earns : ' || emp_salary);

    exceptionWHEN NO_DATA_FOUND OR TOO_MANY_ROWS THENDBMS_OUTPUT.PUT_LINE('Some error occurs in PL/SQL block');END;

    Anonymous block

    PL/SQL Basics

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    54/75

    PL/SQL Basics

    Datatypes

    Operators

    Input & Output Statements

    Control Statements

    Loops

    Insert Update Delete & Select

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    55/75

    Insert, Update, Delete & Select

    Block Structure:

    Begin

    Insert/update/Delete statement;

    Commit/Rollback;

    End;

    Select:Syntax:-

    Select col1,col2into var1,var2 from table_name where condition.

    Cursors

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    56/75

    Cursors

    A cursor is a mechanism by which you can assign a

    name to a "select statement" and manipulate the

    information within that SQL statement.

    PL/SQL supports two kinds of cursors

    1. Implicit Cursors

    2. Explicit Cursors.

    Implicit Cursors

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    57/75

    Implicit Cursors

    PL/SQL defines Implicit Cursors for all recently executed

    DML statements.

    Attributes:1. SQL%FOUND

    2. SQL%NOTFOUND

    3. SQL% ROWCOUNT

    Explicit Cursors

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    58/75

    Explicit Cursors

    Explicit cursors are SELECT statements that are

    DECLARE explicitly in the declaration section of the

    current block or in a package specification.

    OPEN, FETCH, and CLOSE are used in the execution or

    exception sections of the programs.

    Creating Cursor

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    59/75

    Creating Cursor

    Declare a Cursor

    OPEN Statement

    FETCH Statement

    CLOSE Statement

    Explicit Cursor Attributes

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    60/75

    Explicit Cursor Attributes

    %FOUND

    %NOTFOUND

    %ROWCOUNT

    %ISOPEN

    Cursor for loop

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    61/75

    Cursor for loop

    The cursor for Loop can be used to process multiple records. There are two benefits with

    cursor for Loop

    1. It implicitly declares a %ROWTYPE variable, also uses it as LOOP index2. Cursor For Loop itself opens a cursor, read records then closes the cursor

    automatically. Hence OPEN, FETCH and CLOSE statements are not necessary in it.

    Example

    declarecursor c1 is select * from dept;

    begin

    for row in c1

    loop

    dbms_output.put_line(row.deptno||' '||row.dname||' '||row.loc);

    end loop;

    end;

    Exception Handling

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    62/75

    Exception Handling

    Pre-defined Exceptions: When an exception occurs (is raised) in a PL/SQL block, its execution section immediately

    terminates. Control is passed to the exception section.

    Every exception in PL/SQL has an error number and error message; some exceptions also have

    names.Error Named Exception

    ORA-00001 DUP_VAL_ON_INDEX

    ORA-01001 INVALID_CURSOR

    ORA-01012 NOT_LOGGED_ON

    ORA-01017 LOGIN_DENIED

    ORA-01403 NO_DATA_FOUND

    ORA-01410 SYS_INVALID_ROWID

    ORA-01422 TOO_MANY_ROWS

    ORA-01476 ZERO_DIVIDE

    ORA-01722 INVALID_NUMBER

    ORA-06500 STORAGE_ERROR

    ORA-06502 VALUE_ERROR

    ORA-06511 CURSOR_ALREADY_OPEN

    ORA-06530 ACCESS_INTO_NULL

    Exception Handling

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    63/75

    Exception Handling

    User-Defined Exceptions

    PL/SQL lets you define exceptions of your own. Unlike predefined

    exceptions, user-defined exceptions must bedeclaredand must be raised

    explicitly by RAISE statements.

    Ex:-

    DECLARE

    out_of_balance EXCEPTION;

    BEGIN

    IF ... THEN

    RAISEout_of_balance; -- raise the exception

    END IF;EXCEPTION

    WHEN out_of_balance THEN

    -- handle the error RAISE;

    END;

    WHEN OTHERS Cl

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    64/75

    WHEN OTHERS Clause

    The WHEN OTHERS clause is used to trap all remaining exceptionsthat have not been handled by yourNamed System Exceptions and

    Named Programmer-Defined Exceptions.

    If present it should be the last exception handler.

    Functions

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    65/75

    Functions

    Functions can return a value to the caller

    Functions can be directly referenced in queries

    The value is returned through the use of the return

    keyword.

    Syntax:CREATE [OR REPLACE] FUNCTION function_name

    [ (parameter [,parameter]) ] RETURN return_datatype

    IS | AS

    [declaration_section]

    BEGIN

    executable_section

    [EXCEPTIONexception_section]

    END [function_name];

    Stored procedures

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    66/75

    Stored procedures

    A stored procedure is a named PL/SQL block, which is

    stored in the database and can be invoked from differentenvironments that can access database.

    Syntax :CREATE [OR REPLACE] PROCEDURE procedure_name

    [ (parameter [,parameter]) ]IS

    [declaration_section]BEGIN

    executable_section

    [EXCEPTIONexception_section]

    END [procedure_name];

    Functions

    Parameters

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    67/75

    Parameters

    When you create a procedure or function, you maydefine parameters. There are three types of parametersthat can be declared:

    1. IN- The parameter can be referenced by the

    procedure or function. The value of the parameter cannot be overwritten by the procedure or function.

    2. OUT- The parameter can not be referenced by theprocedure or function, but the value of the parameter canbe overwritten by the procedure or function.

    3. IN OUT- The parameter can be referenced by theprocedure or function and the value of the parameter canbe overwritten by the procedure or function.

    Packages

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    68/75

    Packages

    A package is a group of procedures, functions, variablesand SQL statements created as a single unit. It is used

    to store together related objects.

    Package Specificationacts as an interface to thepackage. Declaration of types, variables, constants,

    exceptions, cursors and subprograms is done in

    Package specifications.

    Package bodyis used to provide implementation for thesubprograms, queries for the cursors declared in the

    package specification or spec.

    Packages

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    69/75

    Packages

    Advantages:

    It allows you to group together related items, types and

    subprograms as a PL/SQL module.

    When a procedure in a package is called entire

    package is loaded, though it happens to be expensivefirst time the response is faster for subsequent calls.

    Package allows us to create types, variable and

    subprograms that are private or public

    Packages

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    70/75

    Packages

    Syntax:

    The package specificationCreate or Replace PACKAGE package_name IS

    [Declaration of variables and types]

    [Specifications of cursors]

    [Specifications of modules]

    END [ package_name];

    The package body

    PACKAGE BODY package_name IS

    Specified members definitions..

    END [package_name];

    Triggers

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    71/75

    Triggers

    Triggers are programs that execute in response tochanges in table data or certain database events.

    Typesof triggering events:

    DML events fire when an INSERT, UPDATE, or DELETE

    statement executes.

    Creating Triggers

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    72/75

    Creating Triggers

    Syntax:-

    CREATE [OR REPLACE] TRIGGER trigger_name

    BEFORE | AFTER | INSTEAD OF } trigger_event ON {table_or_view_reference |

    [REFERENCING [OLD AS old] [NEW AS new] [FOR EACH ROW ][WHEN trigger_condition]

    trigger_body;

    Example:- The following trigger restricts doing operations on Sundays on emp table.

    create or replace trigger sun_trig before insert or update or delete on emp for each rowdeclare

    d varchar2(3);

    begin

    d:=to_char (sysdate,'dy');

    if d=sun' thenraise_application_error(-20010,'Such operations are not allowed in Sundays, try only on weekdays...!');

    end if;

    end;

    Useful websites

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    73/75

    Useful websites

    http://www.ss64.com/orad/index.html

    http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/

    sql_elements.htm

    http://www.lc.leidenuniv.nl/awcourse/oracle/appdev.920/a96590/adg

    09dyn.htm#26799

    http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/sql_

    elements6a.htm#19762

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    74/75

  • 8/10/2019 SSTL Oracle SST Prst Ver1.0

    75/75