Cluster brief notes

Embed Size (px)

Citation preview

  • 8/12/2019 Cluster brief notes

    1/39

  • 8/12/2019 Cluster brief notes

    2/39

    Creation of cluster for a table

    First create the cluster,

    create cluster sampleclust (sno number(3), sname varchar2(10));

    Next create the index,

    create index idx_sampleclust on cluster sampleclust;

    Attaching the cluster to the table,

    create table sample2 (sno number(3),sname varchar2(10)) cluster

    sampleclust(sno,sname)

    Example :

    1. To display details of the Table

    select * from sample2;

    SNO SNAME

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

    100 Nithya

    101 Saloni

    102 Aruna

    1. To display details of the Table

    select * from cluster sampleclust;

    SNO SNAME

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

    100 Nithya

    101 Saloni

  • 8/12/2019 Cluster brief notes

    3/39

    102 Aruna

    1. Even if you delete any row in the table, that will not affected to thecluster

    1. delete from sample2 where sno=100;

    2. select * from sample2;

    SNO SNAME

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

    101 Saloni

    102 Aruna

    3. select * from cluster sampleclust;

    SNO SNAME

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

    100 Nithya

    101 Saloni

    102 Aruna

    4. delete from sampleclust where sno=102

    ERROR at line 1:

    ORA-00942: table or view does not exist

    Note : We can not delete any data from the clusterDrop cluster

    This command is used to drop any cluster

    Syntax : drop Cluster

  • 8/12/2019 Cluster brief notes

    4/39

    To drop any cluster

    Drop table sample2;

    Drop cluster sampleclust;

    FunctionA function is a sub program that executes a set of statements and returns a

    value to the main program. The basic difference between Functions andprocedures is, function returns a value to the calling program or main programwhere as a procedure does not return any value

    Syntax of A Function

    Create [ Or Replace ] Function < Function Name > ( Argument1 [Mode] , Argument2 [Mode] ,---) return data type

    Is / As

    Local Variables Declarations;

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

    Begin

    Executable Statements;

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

    [Exception

    Exception Handling; ]

    End;

    /

    Example : 1

    Write a program to find sum of two numbers

  • 8/12/2019 Cluster brief notes

    5/39

    Sol :

    ed function1

    Create or replace function addition(x integer, y integer) return integer

    is

    Begin

    Return x+y;

    End;

    /

    mainfunction1

    Declare

    A integer :=&a;

    B integer :=&b;

    C integer;

    Begin

    C:=addition(a,b);

    Dbms_output.put_line('sum of two numbers is '|| c );

    End;

    /

    Example : 2

    wirte a function which accepts item number and quantity and then return thetotal amount by fetching rate from the item table

    create or replace function itembill(q in number,r in number) return number

  • 8/12/2019 Cluster brief notes

    6/39

    is

    begin

    return q*r;

    end;

    /

    ed mainfunction2

    declare

    q1 number:=&quantity;

    r1 number;

    res number;

    begin

    select rate into r1 from item where itno=&itno;

    res:=itembill(q1,r1);

    dbms_output.put_line(' Total Amount is '||res);

    exception

    when no_data_found then

    dbms_output.put_line(' No Such Item Exits');

    end;

    /

    Built In Function in OracleBuilt In Function in Oracle

    SQL Functions are of two types, they are

  • 8/12/2019 Cluster brief notes

    7/39

    1. Single Rows Functions : These functions will have effect on a single row of thetable

    2. Group Functions : These functions will have effect on a group of row's

    Single Rows Functions

    1. Numerical Functions

    2. Character Functions

    3. Date and Time Functions

    4. Conversion Functions

    5. General Functions or Miscellaneous Functions

    Numerical Functions

    1. Abs : This function is used to convert any negative expression into positive

    Syntax : Abs (Numeric Expression)

    Example : Select abs(-100) from Dual ; 100

    Select abs(300-500) from Dual ; 200

    Select abs(-20*30) from Dual ; 600

    1. Exp (Exponential) :

    This Function is used to find the exponential value for the given number. Ie e tothe power of x value ( e x). where e has a constant value ie 2.7182

    Syntax : Exp(Numeric Expression)

    Example : Select exp(0) from Dual ; 1

    Select exp(1) from Dual ; 2.7182

    Select exp(2) from Dual ; 7.3890

  • 8/12/2019 Cluster brief notes

    8/39

    1. Sqrt (Square Root) : This function is used to find the square root value forthe given number

    Syntax : Sqrt ( Number )

    Example : select sqrt(2) from dual ; 1.4142

    select sqrt(16) from dual ; 4

    select sqrt(sal) from emp;

    select sqrt(4*sqrt(2)) from dual;

    1. Power : This function is used to find the power value ie x to the power of yvalue

    Syntax : Power(x,y)

    Example : select power(2,3) from dual ; 8

    select power(5,3) from dual ; 125

    select power(sal,2) from emp;

    1. Round : This function is used to round off the given numeric expressionaccording to

    specified length or precision

    Syntax : Round(Numeric Expression, Length)

    Example : select round(98.52) from dual; 99

    Select round(65.567,1) from dual ; 65.6

    Select round(65.567,2) from dual ; 65.57

    1. Ceil :This function returns the nearest integer greater than the givennumeric expression

    Syntax : Ceil(Numeric Expression)

  • 8/12/2019 Cluster brief notes

    9/39

    Example : Select ceil(-23.567) from dual ; -23

    Select ceil(23.567) from dual ; 24

    1. Floor : This function returns the nearest integer smaller than the givennumeric expression

    Syntax : Floor(Numeric Expression)

    Example : Select floor(-23.567) from dual ; -24

    Select floor(23.567) from dual ; 23

    1. Log :this function is used to find the logarithm value for the given numberand for the given base

    Syntax : Log(Number, Base Value)

    Example : select log(10,10) from dual; 1

    select log(2,10) from dual; 3.3219

    Character Functions or Text Functions or String Functions

    1. || or Concat :

    Glues or concatenates two strings together. The | symbol is called as vertical baror pipe

    Syntax : string1 || string2 ( for || Function)

    Syntax : Concat(string1 , string2) ( for concat Function)

    Example : select concat ( city, country) from location;

    is same as select city || country from location;

    1. ASCII:

    This Function Returns The Ascii Code Value Of The Left Most Character From TheGiven Character Expression

  • 8/12/2019 Cluster brief notes

    10/39

    Syntax : Ascii(Character Expression)

    Example : select Ascii(a) from dual ; 97

    select Ascii(A) from dual ; 65

    1. Chr :

    This Function Returns The Ascii Character For The Given Ascii Value

    Syntax : Chr(Ascii Value)

    Example : select chr(65) from dual ; A

    Select chr(97) from dual ; a

    1. Length :

    This Function Is Used To Find The Length Of The Given Character Expression

    Syntax : Length ( character expression )

    Example : select length ( sairam) from dual; 6

    select length (ename) from emp;

    1. Upper :

    This Function Is Used To Convert All Characters In To Upper Case

    Syntax : Upper (Character Expression)

    Example : select upper (sairam) from dual; SAIRAM

    1. Lower :

    This Function Is Used To Convert All Characters In To Lower Case

    Syntax : Lower (Character Expression)

    Example : select lower (SAIRAM) from dual; sairam

    7. Ltrim :

  • 8/12/2019 Cluster brief notes

    11/39

    This Function Removes Any Spaces From The Left Side of The String

    Syntax : Ltrim(String)

    Example : select ' sairam' from dual; --> sairam

    select Ltrim(' sairam') from dual; --> sairam

    8. Rtrim :

    This Function Removes Any Space From The Right Side of The String

    Syntax : Rtrim(String)

    Example : select 'sairam ' from dual; --> sairam

    select Rtrim('sairam ') from dual; --> sairam

    9. Trim : (Oracle 9i)

    If You Are Trimming The Exact Same Data From Both The Beginning And Then EndOf The String, Then You Can Use The Trim Function In Place Of An Ltrim/RtrimCombination

    Syntax : Trim(String)

    Example: select ' sairam ' from dual; --> sairam

    select Trim(' sairam ') from dual; --> sairam

    10. Substr : (Sub String)

    This function returns a part of the string from the specified Position to thespecified number of characters

    Syntax: Substr(String, Start Postion,Number of Characters)

    Example : select substr('disk operating system',6,9) from dual; --> operating

    11. Lpad :

    This function is used to append the given text to the left side of any

  • 8/12/2019 Cluster brief notes

    12/39

    column or String or lpad function allows you to pad the left side of a column

    with any set of Characters.

    Syntax : Lpad (,,)

    Example : select lpad(sal,7,'Rs. ') from emp;

    output

    Rs. 800

    Rs.1200

    Example : select lpad(sal,10,'Rs. ') from emp;

    output

    Rs. Rs. 800

    Rs. Rs.1200

    12. Rpad :

    This function is used to append the given text to the right side of any column or

    string or lpad function allows you to pad the left side of a column with any setof characters.

    Syntax : Rpad(,,)

    Example : select Rpad(sal,7,'Rs. ') from emp;

    output

    800Rs.

    1200Rs.

    Example : select Rpad(sal,10,'Rs. ') from emp;

    output

  • 8/12/2019 Cluster brief notes

    13/39

  • 8/12/2019 Cluster brief notes

    14/39

    SYSDATE

    14-FEB-05

    2. Add_Months :

    This function is used to add the number of months to the months part of theaccepted dates. ( we can give positive/negative values )

    Syntax : Add_Months(Date, Number)

    Example : select sysdate, add_months(sysdate,5) from dual;

    Output

    SYSDATE ADD_MONTH

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

    14-FEB-05 14-JUL-05

    3. Last_day :

    This Function Is Used To Return The Last Day Of Accepted Date (0r) Last Day Ofthe Month

    Syntax : Last_day ( date expression )

    Example : select sysdate, Last_Day(sysdate) from dual;

    Output

    SYSDATE LAST_DAY(

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

    14-FEB-05 28-FEB-05

    4. Next_Day

    This function is used to find the Next day of the given weekday name

  • 8/12/2019 Cluster brief notes

    15/39

    Syntax : Next_Day(Date Expression, Week day name)

    Example : select sysdate, next_day(sysdate, 'Monday') from dual;

    Output

    SYSDATE NEXT_DAY(

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

    14-FEB-05 21-FEB-05

    5. months_between

    This function is used to find number of months between the given two dates

    Syntax : months_between(date expression1, date expression2)

    Example : 1

    select months_between(sysdate,

    to_date('20-oct-05','dd-mon-yy')) from dual;

    MONTHS_BETWEEN(SYSDATE,TO_DATE('20-OCT-05','DD-MON-YY'))

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

    -2.432654

    To eliminate decimal points, give the following form

    select round(months_between(sysdate,

    to_date('20-oct-05','dd-mon-yy'))) from dual

    ROUND(MONTHS_BETWEEN(SYSDATE,TO_DA

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

    -2

    select round(months_between(to_date('20-oct-05','dd-mon-yy'),sysdate))

  • 8/12/2019 Cluster brief notes

    16/39

  • 8/12/2019 Cluster brief notes

    17/39

    mon dd, yy

    hh:mm:ss

    mon dd yyyy hh:mi:mm (Am or Pm)

    mm-dd-yy

    yy mm dd

    dd mon yyyy hh:mi:ss:mm (24 hour format)

    hh:mi:ss:mmm (24 hour)

    dy (to find week day number)

    day (week day name)

    dd (number of days in month)

    yyyy (year in four digits)

    yy (year of Last two digits)

    year (spelt in terms of words)

    month (month name)

    w (week number)

    Example : 1

    select sysdate,to_char(sysdate,'dd mm yy') from dual;

    SYSDATE TO_CHAR(S

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

    15-FEB-05 15 02 05

    select sysdate,to_char(sysdate,'month dd day w') from dual;

    SYSDATE TO_CHAR(SYSDATE,'MONTHDD

  • 8/12/2019 Cluster brief notes

    18/39

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

    15-FEB-05 february 15 tuesday 3

    3. To_Date : this function is used to convert any character expression into a dateexpression according to the format you specified

    Syntax : To_Date(, )

    Example :

    insert into student(jdate) values('jan-10-05')

    ERROR at line 1:

    ORA-01858: a non-numeric character was found where a numeric was expected

    insert into student(jdate) values(to_date('jan-10-05','mon-dd-yy'));

    JDATE

    ---------

    10-JAN-05

    General Functions or Miscellaneous functions

    1. show user : This function is used to show the current user name

    syntax : show user;

    Example : show user;

    Output : user is "SCOTT"

    2. uid : this function is used to show the user id of the currently active usersyntax : uid

    Example : select uid from dual;

    UID

  • 8/12/2019 Cluster brief notes

    19/39

    ----

    18

    3. Greatest : this function is used to find the maximum value from a given list ofvalues

    Syntax : Greatest(Value1,Value2,-----)

    Example :

    select greatest(10,20,40) from dual;

    GREATEST(10,20,40)

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

    40

    4. Least : this function is used to find the minimum value from a given list ofvalues

    Syntax : Least (value1,value2,-----)

    Example :

    select least(10,20,40) from dual;

    LEAST(10,20,40)

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

    10

    Stored Procedure

    A procedure is a set of instructions(usually combining sql and plsql commands)saved for calling and repeated execution

    http://c/Documents%20and%20Settings/Master/Desktop/Latest%20Folder/Oracle/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure_files/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure.htmhttp://c/Documents%20and%20Settings/Master/Desktop/Latest%20Folder/Oracle/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure_files/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure.htmhttp://c/Documents%20and%20Settings/Master/Desktop/Latest%20Folder/Oracle/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure_files/PLSQL%20in%2021%20Hours%20%20Stored%20Procedure.htm
  • 8/12/2019 Cluster brief notes

    20/39

  • 8/12/2019 Cluster brief notes

    21/39

    where Mode refers to the type of arguments such as In , Out or InOut

    Modes In Procedures And Functions

    1. IN : the In parameter lets the user to pass values to the called sub programswith in the sub program, the IN parameter acts like a constant. There fore itcannot be modified.

    1. OUT : The Out parameter lets the user returned values to the calling block.Inside the sub program the out parameter acts like a un initialized variable.Its value can not be assigned to another variable or itself

    1. INOUT : the INOUT parameter lets the user pass initial values to the calledsub program and return updated values to the calling block

    Note : the default mode of an argument is "IN"

    Show Errors :

    This Command is used to show the errors that are occurred during the procedurecreation

    Ex : when ever we create a procedure and executed, if it show procedure created

    with compilation errors, the we can see those errors using the followingstatement

    show Errors

    Example :1

    Write a procedure to show a simple message

    Sol. Steps

    1. Write the sub Program

    Ed subprocedure1

    Create or replace procedure disp is

  • 8/12/2019 Cluster brief notes

    22/39

    Begin

    Dbms_output.put_line('This is a Sub Program');

    End;

    /

    1. Next, Compile the above procedure to find errors in the procedure, withthe following statement

    @ subprocedure1

    1. Next, Write the main program

    Begin

    Dbms_output.put_line('This is Main Program');

    Disp;

    Dbms_output.put_line('Again Continuing the Main Program');

    End;

    /

    1. Next, Run the above main procedure with the following statement

    @mainprogram1

    output :

    SQL> @ mainprogram1

    This is Main ProgramThis is a Sub Program

    Again Continuing the Main Program

    PL/SQL procedure successfully completed.

  • 8/12/2019 Cluster brief notes

    23/39

    Example :2

    Write a procedure to show a message when updated any row in a particulartable

    Sol. Steps

    1. Write the sub Program

    Ed subprocedure2

    Create or replace procedure upd(d number)

    is

    Begin

    update employee set sal=sal+(sal*0.2) where empno=d;

    dbms_output.put_line(sql%rowcount||' Record Updated...');

    End;

    /

    1. Next, Compile the above procedure to find errors in the procedure, withthe following statement

    @ subprocedure2

    1. Next, Write the main program

    Begin

    upd(&empno);

    End;

    /

    1. Next, Run the above main procedure with the following statement

  • 8/12/2019 Cluster brief notes

    24/39

    @mainprogram2

    output :

    SQL> @ mainprogram2

    Enter value for empno: 7369

    old 2: upd(&empno);

    new 2: upd(7369);

    1 Record Updated...

    PL/SQL procedure successfully completed.

    Example 3:

    Create a procedure which adds the given three numbers u sing in and outparameters

    Sol. Steps

    1. Write the sub Program

    Ed subprocedure3

    Create or replace procedure sum_numbers(n1 in number, n2 in

    number, res out number)

    is

    Begin

    res:=n1+n2;End;

    /

  • 8/12/2019 Cluster brief notes

    25/39

    1. Next, Compile the above procedure to find errors in the procedure, withthe following statement

    @ subprocedure3

    1. Next, Write the main program

    Declare

    a number;

    b number;

    c number;

    Begin

    a:=&a;

    b:=&b;

    sum_numbers(a,b,c);

    dbms_output.put_line('sum of three numbers is '||c);

    End;

    /

    1. Next, Run the above main procedure with the following statement

    @mainprogram3

    output :

    SQL> @ mainprogram3Enter value for a: 10

    old 6: a:=&a;

    new 6: a:=10;

  • 8/12/2019 Cluster brief notes

    26/39

    Enter value for b: 20

    old 7: b:=&b;

    new 7: b:=20;

    sum of three numbers is30

    PL/SQL procedure successfully completed.

    Example 4:

    Create a procedure which Updates the sal with the increment value that yougive according to the given emp number

    Sol. Steps

    1. Write the sub Program

    Ed subprocedure4

    Create or replace procedure incr(eno employee.empno%type,s

    out number, i number)

    Is

    Begin

    Update employee set sal=sal+i where empno=eno;

    Dbms_output.put_line('Record Updated----');

    End;

    /1. Next, Compile the above procedure to find errors in the procedure, with

    the following statement

    @ subprocedure4

  • 8/12/2019 Cluster brief notes

    27/39

    1. Next, Write the main program

    Declare

    e number:=&empno;

    Incr_value number:=&increment;

    s employee.sal%type;

    Begin

    Select sal into s from employee where empno=e;

    Incr(e,s,incr_value);

    End;

    /

    1. Next, Run the above main procedure with the following statement

    @mainprogram4

    output :

    SQL> @ mainprogram4

    Enter value for empno: 7369

    old 2: e number:=&empno;

    new 2: e number:=7369;

    Enter value for increment: 48

    old 3: incr_value number:=&increment;

    new 3: incr_value number:=48;

    Record Updated----

    PL/SQL procedure successfully completed

  • 8/12/2019 Cluster brief notes

    28/39

    TriggerTrigger is a database object ie used to execute an action basing on an even.

    Triggers are event-based programs, which are executed when an event occurs or

    raises or fires

    Types of Triggers

    Trigger Type is defined by the type of triggering transaction and by the level atwhich the trigger is executed

    Triggers Are Of Two Types

    1. Row Level Triggers

    2. Statement Level Triggers

    Row Level Triggers

    A row trigger is fired each time a row in the table is affected by the triggeringstatement. For example, if an UPDATE statement updates multiple rows of atable, a row trigger is fired once for each row affected by the update statement. Ifthe triggering statement affects no rows, the trigger is not executed at all. Row

    triggers should be used when some processing is required whenever a triggeringstatement affects a single row in a table.

    Row level triggers are created using the "For Each Row" Clause in the CreateTrigger Command

    Statement triggers

    A statement trigger is fried once on behalf of the triggering statement,independent of the number of rows the triggering statement affects (even if notrows are affected) statement triggers should be used when a triggering statementaffects rows in a table but the processing required is completely independent ofthe number of rows affected

  • 8/12/2019 Cluster brief notes

    29/39

    Statement level triggers are the default type of trigger created via Create TriggerCommand

    Syntax:

    create or replace trigger

    {before/after/instead of}

    {insert/update/delete}

    [ of on ]

    [ for each row [when ] ]

    Declare

    variables declarations

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

    begin

    Executable statements

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

    Exception

    Exception statements

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

    end;

    / Syntax Explanation :

    or replace : Recreates the trigger if it already exists. this option can be used tochange the definition of an existing trigger without requiring the user to drop thetrigger first

  • 8/12/2019 Cluster brief notes

    30/39

    Trigger Name : is the name of the trigger to be created

    Before : Indicates that oracle fires the trigger before executing the triggerstatement

    After : Indicates that oracle fires the trigger After executing the trigger statement

    Insert : Indicates that oracle fires the trigger whenever an INSERT statement addsa row to a table.

    Delete : Indicates that oracle fires the trigger whenever a DELETE statementremoves a row from the table.

    Update : Indicates that oracle fires the trigger whenever an UPDATE statement

    changes a value in one of the columns specified in the OF clause. if the OF clauseis omitted, the oracle fires the trigger whenever an UPDATE statement changes avalue in any column of the table.

    for Each Row : Designates the trigger to be a row trigger. the oracle engine fires arow trigger once for each row that is affected by the triggering statement andmeets the optional trigger constraint defined in the When clause. if this clause isomitted the trigger is a statement trigger.

    When : specifies the trigger restriction. the trigger restriction contains a SQLcondition that must be satisfied for the oracle to fire the trigger.

    Basing on the above 2 types of triggers, they are further classified into 3 types

    1. DML Triggers

    2. DDL Triggers and

    3. Instead of Triggers

    1. DML Triggers

    These triggers are executed before or after. we apply any dml operations on atable.

  • 8/12/2019 Cluster brief notes

    31/39

    When we create a table. the trigger definition is stored in the database, which isidentified with the trigger name. the code in the trigger is processed when weapply any command on the database or table

    Examples :

    Steps for Creating a Trigger

    1. First Create a trigger, next set the server on with the following statement (setServeroutput on)

    2. Run that Trigger with the following statement

    @

    3. perform some action (ie either insert or update or delete etc)

    Statement Level Triggers

    1. Create A Trigger, Which Displays A Message When Ever You Insert A New RowIn To Sample1 Table

    Create or replace trigger instrig1 before insert on sample1

    Begin

    dbms_output.put_line('one record inserted successfully.....');

    End;

    /

    2. Create A Trigger, Which Displays A Message When Ever You Update AnExisting Row In The Table Sample1

    Create or replace trigger updtrig1 before update on sample1

    Begin

    dbms_output.put_line('one record updated successfully.....');

  • 8/12/2019 Cluster brief notes

    32/39

    End;

    /

    1. Create A Trigger, Which Displays A Message When Ever You Delete A RowFrom The Table Sample1

    Create or replace trigger deltrig1 before delete on sample1

    Begin

    dbms_output.put_line('record(s) deleted successfully.....');

    End;

    /

    Row Level Triggers

    1. Create A Trigger, Which Displays A Message When Ever You Insert A New RowInto A Table Sample1

    Create or replace trigger instrig2 before insert on sample1

    for each row

    Begin

    dbms_output.put_line(:new.sno||' record inserted successfully.....');

    End;

    /

    1. Create a trigger, which displays a message when ever you update a row inthe table sample1

    Create or replace trigger updtrig2 before update on sample1 for each row

    Begin

    dbms_output.put_line(:old.sno||' record updated to '||:new.sno);

  • 8/12/2019 Cluster brief notes

    33/39

    End;

    /

    1. Create A Trigger, Which Displays A Message When Ever You Delete A RowFrom The Table Sample1

    Create or replace trigger deltrig2 after delete on sample1 for each row

    Begin

    dbms_output.put_line(:old.sno||' record deleted successfully.....');

    End;

    /

    DDL TRIGGERS

    1. Create A Trigger, Which Displays An Error Message When Ever You Createa New Table which starts with Letter A

    Create or replace trigger ctrig1 before create on scott.schema

    Begin

    if dictionary_obj_name like 'a%' then

    raise_application_error(-20001,'object name can not start with a');

    End if;

    End;

    /

    1. Create A Trigger, Which Displays An Error Message When Ever You try todrop any Table

    Create or replace trigger prevent_drop after drop on scott.schema

    Begin

  • 8/12/2019 Cluster brief notes

    34/39

    if ora_dict_obj_type='table' then

    raise_application_error(-20001,'object can not be dropped');

    End if;

    End;

    /

    1. Create A Trigger, Which Displays An Error Message When Ever You try toAlter any Table

    create or replace trigger prevent_alter before alter on scott.schema

    begin

    if ora_dict_obj_type='TABLE' then

    Raise_Application_Error(-20001,'Object Can not be altered');

    end if;

    end;

    /

    INSTEAD OF TRIGGER

    Create a trigger, which inserts the given values in to the relevant table through aComposite view

    Create or replace trigger instrig instead of

    Insert on empdept for each row

    Begin

    if :new.deptno is not null and :new.dname is not null then

    insert into department(deptno,dname) values (:new.deptno,:new.dname);

  • 8/12/2019 Cluster brief notes

    35/39

    end if;

    if :new.empno is not null and :new.ename is not null then

    insert into employee(empno,ename) values (:new.empno,:new.ename);

    end if;

    End;

    /

    Materialized view

    A materialized view is a database object that contains the results of aquery. They are local copies of data located remotely, or are used to createsummary tables based on aggregations of a table's data.Materialized view and theQuery rewrite feature is added from ORACLE 8i.

    A materialized view log is a schema object that records changes to a mastertable's data so that a materialized view defined on the master table can be

    refreshed incrementally. If you delete any record from your Materialized view it is goanna impact

    your Source table once it is refreshed.

    Examples to the Simple Materialized views is given below .

    Eg 1 :Create materialized_view MV refresh as select * from emp;

    Execute dbms_mview.refresh(MV);

    Refresh Complete : To perform a complete refresh of a materialized view, theserver that manages the materialized view executes the materialized view'sdefining query, which essentially recreates the materialized view. To refresh thematerialized view, the result set of the query replaces the existing materializedview data. Oracle can perform a complete refresh for any materialized view.

  • 8/12/2019 Cluster brief notes

    36/39

    Depending on the amount of data that satisfies the defining query, a completerefresh can take a substantially longer amount of time to perform than a fastrefresh.

    Create Materialized_view MV Refresh complete as select * from emp;

    execute DBMS_mview.refresh(List=>MV,Method=>c);

    Refresh Fast : To perform a fast refresh , the master that manages the materializedview first identifies the changes that occurred in the master since the most recentrefresh of the materialized view and then applies these changes to thematerialized view. Fast refreshes are more efficient than complete refresheswhen there are few changes to the master because the participating server and

    network replicate a smaller amount of data.

    Create Materialized_view MV Refresh fast as select * from emp;

    execute DBMS_mview.refresh(list=>MV,Method=>F);

    Primary Key Materialized Views :

    The following statement creates the primary-key materialized view on the tableemp located on a remote database.

    SQL> CREATE MATERIALIZED VIEW mv_emp_pkREFRESH FAST START WITH SYSDATENEXT SYSDATE + 1/48WITH PRIMARY KEYAS SELECT * FROM emp@remote_db;

    Note: When you create a materialized view using the FAST option you will need tocreate a view log on the master tables(s) as shown below:

    mailto:emp@remote_db;mailto:emp@remote_db;mailto:emp@remote_db;
  • 8/12/2019 Cluster brief notes

    37/39

    SQL> CREATE MATERIALIZED VIEW LOG ON emp;Materialized view log created.

    Rowid Materialized Views :

    The following statement creates the rowid materialized view on table emplocated on a remote database:

    SQL>CREATE MATERIALIZED VIEW mv_emp_rowid REFRESH WITH ROWID ASSELECT * FROM emp@remote_db ;

    Materialized view log created.

    Creating Materialized Aggregate Views :

    CREATE MATERIALIZED VIEW sales_mv BUILD IMMEDIATE REFRESH FAST ONCOMMIT AS SELECT t.calendar_year, p.prod_id, SUM(s.amount_sold) ASsum_sales FROM times t, products p, sales s WHERE t.time_id = s.time_id ANDp.prod_id = s.prod_id GROUP BY t.calendar_year, p.prod_id;

    Creating Materialized Join Views :

    mailto:emp@remote_dbmailto:emp@remote_dbmailto:emp@remote_dbmailto:emp@remote_db
  • 8/12/2019 Cluster brief notes

    38/39

    CREATE MATERIALIZED VIEW sales_by_month_by_stateTABLESPACE examplePARALLEL 4BUILD IMMEDIATEREFRESH COMPLETEENABLE QUERY REWRITEAS SELECT t.calendar_month_desc, c.cust_state_province,

    SUM(s.amount_sold) AS sum_salesFROM times t, sales s, customers cWHERE s.time_id = t.time_id AND s.cust_id = c.cust_idGROUP BY t.calendar_month_desc, c.cust_state_province;

    Periodic Refresh of Materialized Views:

    CREATE MATERIALIZED VIEW emp_dataPCTFREE 5 PCTUSED 60TABLESPACE exampleSTORAGE (INITIAL 50K NEXT 50K)REFRESH FAST NEXT sysdate + 7AS SELECT * FROM employees;

    Automatic Refresh Times for Materialized Views

  • 8/12/2019 Cluster brief notes

    39/39