PLSQL study material

 

PL/SQL

  • It is a programming language which is used to define our own logics.
  • It is used execute block of statements at a time and increase the performance.
  • It supports variables and conditional statements and loops.
  • It supports object oriented programming and supports composite data types.
  • It supports handle the error handling mechanism.
  •  Block
    • It is one of the area which is used to write a programming logic.
    • This block is have 3 sections.
      • Declaration Section
      • Executable Section
      • Exception Section

3.     Declaration Section

§  It is one of the section which is used declare variables, cursors and exceptions and so on.

§  It is optional section.

4.     Executable Section

§  It is one of the section which is used to write a program coding.

§  It is mandatory section.

5.     Exception Section

§  It is one of the section which is used to handle the errors at runtime.

§  It is optional section.

o    There are two types of blocks are supported by pl/sql.

§  Anonymous Block

§  Named Block

3.     Anonymous Block

§  These blocks does not have a name and also does not stored in database.

 

 

 

 

4. Example :

5. Declare

6. -------------

7. Begin

8. -------------

9. -------------

10.       End;

11.       Example  1:

12.       Begin

13.       Dbms_Output.Put_Line(‘welcome to K-ONLINES.COM’ );

End;

                      

14. Named Block

§  These blocks are having a name and also stored in database.

Examples :  Procedures , Functions, Packages and Triggers etc..

§  Variable

§  It is one of thememory location which is used to store the data.

§  Generally we aredeclare the variables in declaration section.

§  These are supporteddefault and not null.
Syntax :Variable_Name Datatype ( Size );

§  Example :

§  Declare

§  A Number ( 5 );

§  B Number ( 5 )      not null :=10;

§  C Number ( 5 )      default     10;

 

Example  1:

Declare

A Varchar2(20);

Begin

A := ‘Hello EBS’;

Dbms_Output.Put_Line( A );

End;

§  Storing a value into variable

§  Using assignment operator ( := ) we storing a value into variable. Syntax :Variable_Name := value;

Example : a :=50;

§  Display Message ( or ) Varaible Value

§  We have one pre defined package which is used display the message or value in a program.
Syntax : dbms_output.put_line ( ‘message’ );
dbms_output.put_line ( variable_name );

§  Select ------ Into ------ Clause

§  This clause is used to retrieve the data from table & storing into pl/sql variables.
Syntax : select col1, col2 into var1, var2;

                         

                         

                         DataTypes

o    % Type

o    % RowType

o    RecordType ( or ) Pl/sql Record

o    IndexBy Table ( or ) Pl/sql Table

0.     %Type:

§  It is one of the datatype which is used to assign the column datatype to a variable.

§  It is used to store one value at a time.

§  It is not possible to hold more than one column values or row values.
Syntax : variable_name table_name.column_name%type;

§ Example  1:

§ Declare

§ Vno   emp.empno%type:=&n;

§ Vname emp.ename%type;

§ Begin

§ Select

§ ename into vname from emp where empno=vno;

§ Dbms_output.put_line ( ‘ employee name is : ‘ || ‘ ‘ || vname );

End;

1.     % RowType

§  It is one of the datatype which is used assign all the column datatypes of table to a variable.

§  It holds entire record of the same table.

§  Each of the time it override only one record.

§  It is not possible to capture the more than one table data.
Syntax :variable_name table_name%rowtype;

§ Example  1:

§ Declare

§ Vrow  emp%rowtype;

§ Vno   emp.empno%type:=&n;

§ Begin

§  

§ Select * into vrow from emp where empno=vno;

§ Dbms_output.put_line ( vrow.ename || ‘ ‘ || vrow.sal );

End;

2.     Record Type ( or ) Pl/Sql Record

§  Is is one of the user defined temporary data type which is used to store more than one table data ( or ) to assign more than one column datatypes.

§  They must at least contain one element.

§  Pinpoint of data is not possible.
Syntax : Type Typename is Record ( Val-1 Datatype, Val-2 Datatype,…..);
Var Typename

§ Example :

§ Declare

§ Type Rec is record ( vname emp.ename%type,

§                         Vsal     emp.sal%type,

§                     VLoc    dept.loc%type);

§ Vrec Rec;

§ Vno emp.empno%type:=&n;

§ Begin

§ Select ename,sal,loc into vrec from emp,dept where emp.deptno=dept.deptno and emp.empno=vno;

§ Dbms_output.put_line(vrec.vname||’,’||vrec.vsal||’,’||vrec.vloc);

End;

                         

                         

                         

                         

                         

                         Conditional Statements

o    If Condition

o    If Else Condition

o    Elsif Condition

o    Case Condition

4.     If Condition 
Syntax :If condition then
Statements;
End if;

5. Example  1:

6. Declare

7. A  Number ( 4 ) :=&n;

8. B  Char ( 1 );

9. Begin

10.    If a<20 then

11.    B:=’Yes’;

12.    End if;

13.    Dbms_output.put_line ( B  );

End;

14.                        If Else Condition
Syntax : If condition then
Statements ;
Else
Statements ;
End if;

15.    Example  1:

16.    Declare

17.    A Number ( 4 ) :=&n;

18.    B Char ( 10 );

19.    Begin

20.    If  a<20 then

21.    B:=’TRUE’;

22.    Else

23.    B:=’FALSE’;

24.    End if;

25.    Dbms_output.put_line ( B );

End;

26.                        Elsif Condition 
Syntax : If condition-1 then
Statements;
Elsif condition-2 then
Statements; 
Elsif condition-3 then
Statements;
Else
Statements;
End if;

27.    Example  1:

28.    Declare

29.    A Number ( 4 ) :=&n;

30.    B     Char ( 15 );

31.    Begin

32.    If a<20 then

33.    B:=’Low Value’;

34.    Elsif a>20 and a<100 then

35.    B:=’High Value’;

36.    Else

37.    B:=’Invalid Value’;

38.    End if;

39.    Dbms_output.put_line ( B );

End;

40.                        Case Condition
Syntax : Case ( column name )
When condition then
Statements;
When condition then
Statements;
Else
Statements;
End Case;

41.    Example  1:

42.    DECLARE

43.    VSAL NUMBER(10):=&N;

44.    BEGIN

45.    CASE

46.    WHEN VSAL<2000 THEN

47.    DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'LOW');

48.    WHEN VSAL>2000 THEN

49.    DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'HIGH');

50.    ELSE

51.    DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'INVALID');

52.    END CASE;

END;

                         Loops

o    Simple Loop

o    While Loop

o    For Loop

3.     Simple Loop
Syntax :
Loop
Statements;
End loop; 
Syntax :
Loop
Code;
Exit when condition;
End loop; 

4. Example  1:

5. Begin

6. Loop

7. Dbms_output.put_line ( ‘Welcome to k-onlines.com' );

8. End loop;

End;

Example 2 :

Declare

N  number(5):=1;

Begin

Loop

Dbms_output.put_line ( n );

Exit when n>=10;

N:=n+1;

End loop;

End;

Example 3 :

Declare

N number(5):=1;

Begin

Loop

Dbms_output.put_line ( n );

If n>=10 then

Exit;

End if;

N:=N+1;

End loop;

End;

9.     While Loop
Syntax : While ( Condition )
Loop
Statements;
End loop; 

10.    Example  1:

11.    Declare

12.    N     Number(4):=1;

13.    Begin

14.    While n>=10

15.    Loop

16.    Dbms_output.put_line ( N );

17.    N:=N+1;

18.    End loop;

End;

19.                        For Loop 
Syntax : For variable_name in lowerbound..outerbound
Loop
Statements;
End loop; 

20.    Example  1:

21.    Declare

22.    N number(5);

23.    Begin

24.    For   n     in 1..10

25.    Loop

26.    Dbms_output.put_line ( N );

27.    End loop;

28.    End;

Example 2 :   

Declare

N number(5);

Begin

For      n     in  reverse  1..10

Loop

Dbms_output.put_line ( N );

End loop;

End;

                         Bind Variable

o    These variables are session variable.
Syntax : variable a number;

o    Example  1:   

o    sql>     Variable V Number;

o    Sql>     Declare

o       A     number(5):=500;

o             Begin

o            :v:=a/2;

o            End;

o    Sql>     Print V;

CURSORS

o    Cursor is a buffer area which is used to process multiple records and also record by record by process.

o    There are two types

 .       Implicit Cursors

a.      Explicit Cursors

a.      Implicit Cursors

§  Sql statements returns a single record is called implicit cursors

§  Implicit cursor operations done by the system.

§  Open by the system.

§  Fetch the records by the system

§  Close by the system.

b. Example :

c. Declare

d. X  emp%rowtype;

e. Begin

f. Select * into X from emp where empno=7369;

g. Dbms_output.put_line(x.empno||’,’||x.ename);

h. End;

i.       Explicit Cursors

§  Sql statements return a multiple records is called explicit cursors

§  Explicit cursor operations done by the user.

§  Declare by the user

§  Open by the user

§  Fetch the records by the user

§  Close by the user

j. Example  1:

k. Declare

l. Cursor c1 is select ename,sal from emp;

m. V_Name     varchar2(10);

n. V_Sal      number(10);

o. Begin

p. Open C1;

q. Fetch c1 into v_name,v_sal;

r. Dbms_output.put_line(v_name||’,’||v_sal);

s. Close C1;

t. End;

u. Example 2 :

v. Declare

w. Cursor c1 is select ename,job from emp;

x. Vvname varchar2(10);

y. Job   varchar2(10);

z. Begin

aa.          Open c1;

bb.          Fetch c1 into vname,job;

cc.          Dbms_output.put_line(vname||','||job);

dd.          Fetch c1 into vname,job;

ee.          Dbms_output.put_line(vname||','||job);

ff.          Close c1;

gg.          End;

hh.          Example 3 :

ii.          Declare

jj.          Ccursor c1 is select ename,job from emp;

kk.          Vname varchar2(10);

ll.          Vjob      varchar2(10);

mm.          Begin

nn.          Open c1;

oo.          Loop

pp.          Fetch c1 into vname,vjob;

qq.          Dbms_output.put_line(vname||','||vjob);

rr.          End loop;

ss.          Close c1;

tt.          End;

                         CURSOR Attributes

o    Every explicit cursor having following four attributes

0.     %NotFound

1.     %Found

2.     %Isopen

3.     %Rowcount

o    All these cursor attributes using along with cursor name only Syntax :cursorname % attributename
Note : Except %rowcount all other cursor attribute records Boolean value return either true or false where as %rowcount return number datatupe.

b.     %NotFound

§  Returns INVALID_CURSOR if cursor is declared, but not open or if cursor has been closed.

§  Returns NULL if cursor is open, but fetch has not been executed.

§  Returns FALSE if a successful fetch has been executed.

§  Returns TRUE if no row was returned.

c. Example  1:

d. Declare

e. Ccursor c1 is select ename,job from emp;

f. Vname varchar2(10);

g. Vjob      varchar2(10);

h. Begin

i. Open c1;

j. Loop

k. Fetch c1 into vname,vjob;

l. Exit when c1%notfound;

m. Dbms_output.put_line(vname||','||vjob);

n. End loop;

o. Close c1;

p. End;

q.  

r.       %Found

§  Returns INVALID_CURSOR if cursor is declared, but not open or if cursor has been closed.

§  Returns NULL if cursor is open, but fetch has not been executed.

§  Returns TRUE if a successful fetch has been executed.

§  Returns FALSE if no row was returned.

s. Example  1:

t. Declare

u. Cursor c1 is select * from emp;

v. I emp%rowtype;

w. Begin

x. Open c1;

y. Loop

z. Fetch c1 into i;

aa.    If c1%found then

bb.    Dbms_output.put_line(i.empno||','||i.ename);

cc.    Else

dd.    Exit;

ee.    End if;

ff.    End loop;

gg.    Close c1;

hh.    End;

ii.     %IsOpen

§  Returns TRUE if the cursor is open,

§  Retuens FALSE if the cursor is closed.

jj.     

kk.    Example  1:

ll.    Declare

mm.    Cursor c1 is select * from emp;

nn.    I emp%rowtype;

oo.    Begin

pp.    Open c1;

qq.    If c1%isopen then

rr.    Dbms_output.put_line('cursor is open');

ss.    Loop

tt.    Fetch c1 into i;

uu.    If c1%found then

vv.    Dbms_output.put_line(i.ename);

ww.    Else

xx.    Exit;

yy.    End if;

zz.    End loop;

aaa.  Close c1;

bbb.  If not c1%isopen then

ccc.  Dbms_output.put_line('cursor is closed');

ddd.  End if;

eee.  End if;

fff.  End;

ggg.                    %Rowcount

§  Returns INVALID_CURSOR if cursor is declared, but not open or if cursor has been closed.

§  Returns the number of rows fetched by the cursor.

hhh.   

iii.  Example  1:

jjj.  Declare

kkk.  Cursor c1 is select * from emp;

lll.  I emp%rowtype;

mmm.  Begin

nnn.  Open c1;

ooo.  Loop

ppp.  Fetch c1 into i;

qqq.  Exit when c1%notfound;

rrr.  Dbms_output.put_line(i.empno||','||i.ename);

sss.  End loop;

ttt.  Dbms_output.put_line('Total no of employee: '|| c1%rowcount);

uuu.  Close c1;  

vvv.  End;

                         PARAMETER CURSOR

o    Passing a parameter in cursor is call it as a parameter cursor.

Syntax : Cursor cursor_name ( parameter_name ) is select * from table_name where column_name=parameter_name

Example  1:

Declare

Cursor c1 (p_deptno number) is select * from emp where deptno=p_deptno;

I emp%rowtype;

Begin

Open c1(10);

Loop

Fetch c1 into i;

Exit when c1%notfound;

Dbms_output.put_line(i.ename);

End loop;

Close c1;

End;

Example 2 :

Declare

Cursor c1 ( p_job varchar2) is select * from emp where job=p_job;

I emp%rowtype;

Begin

Open c1('MANAGER');

Loop

Fetch c1 into i;

Exit when c1%notfound;

Dbms_output.put_line(i.empno||','||i.ename||','||i.job);

End loop;

Close c1;

Open c1('CLERK');

Loop

Fetch c1 into i;

Exit when c1%notfound;

Dbms_output.put_line(i.empno||','||i.ename||','||i.job);

End loop;

Close c1;

End;

                         CURSOR WITH FOR Loop

o    In cursor for loop no need to open, fetch, close the cursor. For loop it self automatically will perform these functionalities

             Example  1:

             Declare

             Cursor c1 is select * from emp;

             I emp%rowtype;

             Begin

             For i in c1 loop

             Dbms_output.put_line(i.empno||','||i.ename);

             End loop;

             End;

                         NESTED CURSOR WITH FOR Loop

             Example 2 :

             Declare

             Cursor c1 is select * from dept;

             Cursor c2(p_deptno number) is select * from emp where deptno=p_deptno;

             Begin

             For i in c1

             Loop

             Dbms_output.put_line(i.deptno);

             For j in c2(i.deptno)

             Loop

             Dbms_output.put_line(j.empno||','||j.ename||','||j.sal);

             End loop;

             End loop;

             End;

                         

                         

                         CURSOR WITH DML Operations

             Example  1:

             Declare

             Cursor c1 is select * from emp;

             Begin

             For i in c1

             Loop

             Insert into t1 values (i.ename,i.sal);

             End loop;

             End;

             Example 2 :

             Declare

             Cursor c1 is select * from t1;

             Begin

             For i in c1

             Loop

             Delete from t1 where sal=3000;

             End loop;

             End;

             Example 3 :

             Declare

             Cursor c1 is select * from kuncham;

             Begin

             For i in c1

             Loop

             If i.job='CLERK' then

             Update kuncham set sal=i.sal+1111 where empno=i.empno;

             Elsif i.job='MANAGER' then

             Update kuncham set sal=i.sal+2222 where empno=i.empno;

             End if;

             End loop;

             End;

                         Ref Cursor

o    Ref Cursors are user define types which is used to process multiple records and also this is record by record process

o    Generally through the static cursors we are using only one select statement at a time for single active set area where as in ref cursors we are executing no of select statements dynamically for single active set area.

o    Thats why these type of cursors are also called as dynamic cursors.

o    By using ref cursors we return large amount of data from oracle database into client applications.

o    There are 2 Types

§  Strong Ref Cursor

§  Weak Ref Cursor

§  Strong Ref Cursor

§  It is one of the ref cursor which is having return type.

§  Weak Ref Cursor

§  It is one of the ref cursor which does not have a return type.

Note : In ref cursor we are executing select statements using open .... for statement.

Example 1 :

Declare

Type t1 is ref cursor;

v_t t1;

i emp%rowtype;

begin

open v_t for select * from emp where sal>2000;

loop

fetch v_t into i;

exit when v_t%notfound;

dbms_output.put_line(i.ename||' '||i.sal);

end loop;

close v_t;

end;

Example 2 :

Declare

type t1 is ref cursor;

v_t t1;

i emp%rowtype;

j dept%rowtype;

v_no number(5):=&no;

begin

if v_no=1 then

open v_t for select * from emp;

loop

fetch v_t into i;

exit when v_t%notfound;

dbms_output.put_line(i.ename||' '||i.deptno);

end loop;

close v_t;

elsif v_no=2 then

open v_t for select * from dept;

loop

fetch v_t into j;

exit when v_t%notfound;

dbms_output.put_line(j.deptno||' '||j.dname);

end loop;

close v_t;

end if;

end;

Example 3 :

create or replace package pg1

is

type t1 is ref cursor return emp%rowtype;

type t2 is ref cursor return dept%rowtype;

procedure p1 (p_t1 out t1);

procedure p2 (p_t2 out t2);

end;



create or replace package body pg1 is

procedure p1 (p_t1 out t1)

is

begin

open p_t1 for select * from emp;

end p1;

procedure p2 (p_t2 out t2)

is

begin

open p_t2 for select * from dept;

end p2;

end;



Execution

variable a refcursor

variable b refcursor

exec pg1.p1(:a);

exec pg1.p2(:b);

print a b;

                         Where Current of and For Update Clause

o    Generally when we are using update, delete statements automatically locks are generated in the data base.

o    If you want to generate locks before update, delete statements then we are using cursor locking mechanism in all data base systems.

o    In this case we must specify for update clause in cursor definition.

Syntax : Cursor Cursor_Name is select * from Table_Name where condition for update

o    If you are specifying for update clause also oracle server does not generate the lock i.e whenever we are opening the cursor then only oracle server internally uses exclusive locks.

o    After processing we must release the locks using commit statement.

o    where current of clause uniquely identifying a record in each process because where current of clause internally uses ROWID.

o    Whenever we are using where current of clause we must use for update clause.

Example :

Declare

cursor c1 is select * from k for update;

i emp%rowtype;

begin

open c1;

loop

fetch c1 into i;

exit when c1%notfound;

if i.job='CLERK' then

update k set sal=i.sal+1000 where current of c1;

end if;

end loop;

commit;

close c1;

end;

                         EXCEPTIONS

o    Exception is one of the activity which is used to handle the errors at runtime.

o    There are 3 types of exceptions

0.     Predefined Exception

1.     Userdefined Exception

2.     Unnamed Exception

2.     Predefined Exception

§  It is one of the exception which are defined by oracle.

§  There are 20 exceptions available.
Syntax : when exception1 then
statements;
when exception2 then
statements;
when others then
statements;

§  Predefined Exceptions are

1.     no_data_found

2.     too_many_rows

3.     invalid_cursor

4.     cursor_already_open

5.     invalid_number

6.     value_error

7.     zero_devide

8.     others
etc.....

9.     No_Data_Found

§  When a pl/sql block contains select ------into clause and also if requested data not available in a table oracle server returns an error.

§  Error is ora-01403 : no data found

§  To handle this error we are using no_data_found exception.

10.             

11.            Example :

12.            Declare

13.            v_ename varchar2(20);

14.            v_sal   number(10);

15.            begin

16.            select ename,sal into v_ename,v_sal from k where empno=&no;

17.            dbms_output.put_line(v_ename||' '||v_sal);

18.                    end;

19.             

20.            Example :

21.            Declare

22.            v_ename varchar2(20);

23.            v_sal   number(10);

24.            begin

25.            select ename,sal into v_ename,v_sal from k where empno=&no;

26.            dbms_output.put_line(v_ename||' '||v_sal);

27.             exception

28.            when no_data_found then

29.            dbms_output.put_line('employee does not exit');

30.            end;

     

31.                        Too_Many_Rows

§  When a select ------into clause try to return more than one record or more than one value then oracle server return an error.

§  Error is ora-01422 : exact fetch returns more than requested number of rows.

§  To handle this error we are using too_many_rows exception

32.            Example :

33.            Declare

34.            v_ename varchar2(20);

35.            v_sal   number(10);

36.            begin

37.            select ename,sal into v_ename,v_sal from k;

38.            dbms_output.put_line(v_ename||' '||v_sal);

39.                    end;

40.            Example :

41.            Declare

42.            v_ename varchar2(20);

43.            v_sal   number(10);

44.            begin

45.            select ename,sal into v_ename,v_sal from k;

46.            dbms_output.put_line(v_ename||' '||v_sal);

47.            exception

48.            when too_many_rows then

49.            dbms_output.put_line('program return more than one row');

50.            end;

     

51.                        Invalid_Cursor

§  Whenever we are performing invalid operations on the cursor server returns an error i.e if you are try to close the cursor with out opening cursor then oracle server returns an error.

§  Error is ora-01001 : invalid cursor

§  To handle this error we are using invalid_cursor exception.

52.            Example :

53.            Declare

54.            cursor c1 is select * from emp;

55.            i emp%rowtype;

56.            begin

57.            loop

58.            fetch c1 into i;

59.            exit when c1%notfound;

60.            dbms_output.put_line(i.ename||i.sal);

61.            end loop;

62.            close c1;

63.            end;

64.            Example :

65.            Declare

66.            cursor c1 is select * from emp;

67.            i emp%rowtype;

68.            begin

69.            loop

70.            fetch c1 into i;

71.            exit when c1%notfound;

72.            dbms_output.put_line(i.ename||i.sal);

73.            end loop;

74.            close c1;

75.            exception

76.            when invalid_cursor then

77.            dbms_output.put_line('first you open the cursor');

78.            end;

79.                        Cursor_Already_Open

§  When we are try to reopen the cursor without closing the cursor oracle server returns an error.

§  Error is ora-06511 : cursor already open

§  To handle this error we are using cursor_already_open exception

80.            Example :

81.            cursor c1 is select * from emp;

82.            i emp%rowtype;

83.            begin

84.            open c1;

85.            loop

86.            open c1;

87.            fetch c1 into i;

88.            exit when c1%notfound;

89.            dbms_output.put_line(i.ename||i.sal);

90.            end loop;

91.            close c1;

92.            end;

93.            Example :

94.            Declare

95.            cursor c1 is select * from emp;

96.            i emp%rowtype;

97.            begin

98.            open c1;

99.            loop

100.          open c1;

101.          fetch c1 into i;

102.          exit when c1%notfound;

103.          dbms_output.put_line(i.ename||i.sal);

104.          end loop;

105.          close c1;

106.          exception

107.          when cursor_already_open then

108.          dbms_output.put_line('cursor already open');

109.          end;

      

110.                   Invalid_Number

§  Whenever we are try to convert string type to number type oracle server return error.

§  Error is ora-01722 : invalid number

§  To handle this error we are using invalid_error exception

111.          Example :

112.          Begin

113.          insert into emp(empno,sal) values (111,'abcd');

114.          end;

115.          Example :

116.          Begin

117.          insert into emp(empno,sal) values (111,'abcd');

118.          exception

119.          when invalid_number then

120.          dbms_output.put_line('insert proper data only');

121.          end;

122.                   Value_Error

§  Whenever we are try to convert string type to number type based on the condition then oracle server returns an error

§  Whenever we are try to store large amount of data than the specified data type size in varaible declaration then oracle server return same error

§  Error is ora-06502 : numeric or value error: character to number conversion error

§  To handle this error we are using value_error exception

123.          Example :

124.          Declare

125.          z number(10);

126.          begin

127.          z:='&x'+'&y';

128.          dbms_output.put_line(z);

129.          end;

130.          Example :

131.          Declare

132.          z number(10);

133.          begin

134.          z:='&x'+'&y';

135.          dbms_output.put_line(z);

136.          exception

137.          when value_error then

138.          dbms_output.put_line('Enter the proper data only');

139.          end;

140.          Example :

141.          Declare

142.          z number(3);

143.          begin

144.          z:='abcd';

145.          dbms_output.put_line(z);

146.          end;

147.                   Zero_Devide

§  Whenever we are try to divide by zero then oracle server return a error

§  Error is ora-01476 : divisor is equal to zero

§  To handle this error we are using zero_divide exception

148. Example :

149. Declare

150. a number(10);

151. b number(10):=&b;

152. c number(10):=&c;

153. begin

154.   a:=b/c;

155. dbms_output.put_line(a);

156. end;

157. Example :

158. Declare

159. a number(10);

160. b number(10):=&b;

161. c number(10):=&c;

162. begin

163. a:=b/c;

164. dbms_output.put_line(a);

165. exception

166. when zero_divide then

167. dbms_output.put_line('c does not contain zero');

168. end;

      

§  EXCEPTION PROPAGATION

§  Exceptions are also raised in

§  Declaration Section

§  Executable Section

§  Exception Section

§  If the exceptions are raised in executable section those exceptions are handled using either inner block or an outer block.

§  Where as if exception are raised in declaration section or in exception section those exceptions are handled using outer blocks only.

§  Example :

§  Begin

§  declare

§  z varchar2(3);--:='abcd';

§  begin

§  z:='abcd';

§  dbms_output.put_line(z);

§  exception

§  when value_error then

§  dbms_output.put_line('invalid string lenght');

§  end;

§  exception

§  when value_error then

§  dbms_output.put_line('the lenght is more');

§  end;

        

3.     Userdefined Exception

§  We can also create our own exception names and also raise whenever it is necessary. these types of exceptions are called user defined exceptions.

§  These exceptions are divided into 3 steps

0.     Declare Exception

1.     Raise Exception

2.     Handle Exception

2.     Declare Exception

§  In declare section of the pl/sql program we are defining our own exception name using exception type.

Syntax : userdefinedexception_name exception

Example :

    Declare

    a   exception;

   

3.     Raise Exception

§  Whenever it is required raise user defined exception either in executable section or in exception section, in this case we are using raise keyword.

Syntax : raise userdefinedexception_name

Example :

Declare

a exception;

begin

raise a;

end;

4.     Handle Exception

§  We can also handle user defined exceptions as same as predefined exception using predefined handler.

Syntax :
when userdefinedexception_name1 then
statements;
when userdefinedexception_name2 then
statements;
----------
----------
when others then
statements;

Example :

Declare

a  exception;

begin

if to_char(sysdate,'dy')='sun' then

raise a;

end if;

exception

when z then

dbms_output.put_line('my exception raised today');

end;

Ex:

Declare

v_sal number(10);

a exception;

begin

select sal into v_sal from k where empno=7902;

if v_sal>2000 then

raise a;

else

update k set sal=sal+100 where empno=7902;

end if;

exception

when a then

dbms_output.put_line('salary alredy high');

end;

§  RIASING Predefined Exception

§  We can also raise the exception in exception section

§ Example :

§ Ddeclare

§ a1 exception;

§ a2 exception;

§ begin

§ begin

§ raise a1;

§ exception

§ when a1 then

§ dbms_output.put_line('a1 handled');

§ --raise a2;

§ end;

§ exception

§ when a2 then

§ dbms_output.put_line('a2 handled');

§ end;

§  ERROR Trapping Functions

§  There are two error trapping functions supported by oracle.

0.     SQL Code

1.     SQL Errm

2.     SQL Code : It returns numbers

3.     SQL Errm : It returns error number with error message.

§ Example :

§ Declare

§ v_sal number(10);

§ begin

§ select sal into v_sal from emp where empno=7369;

§ dbms_output.put_line(sqlcode);

§ dbms_output.put_line(sqlerrm);

end;

§  RAISE APPLICATION ERROR

§  If you want to display your own user defined exception number and exception message then we can use this raise application error

Syntax : raise_application_error ( error_number,error_message );

Error_Number : It is used to give the error numbers between -20000 to -20999

Error_Message : It is used to give the message upto 512 characters.

Example :

Declare

v_sal number(10);

a exception;

begin

select sal into v_sal from k where empno=7369;

if v_sal < 2000 then

raise a;

else

update k set sal=sal+100 where empno=7369;

end if;

exception

when a then

raise_application_error ( -20999,'salary alreday high');

end;

4.     Unnamed Exception

§  If you want to handle other than oracle 20 predefined errors we are using unnamed method.

§  Because oracle define exception names for regularly accured errors other than 20 they are not defining exception names.

§  In this case we are providing exception names and also associate this exception name with appropriate error no using exception_init function.

Syntax : pragma exception_init ( userdefined_exception_name, error_number );

§  Here pragma is a compiler directive i.e at the time of compilation only pl/sql runtime engine associate error number with exception name.

§  This function is used in declare section of the pl/sql block.

Example :

Declare

v_no number(10);

e  exception;

pragma exception_init(e,-2291);

begin

select empno into v_no from emp where empno=&no;

dbms_output.put_line(v_no);

exception

when e then

dbms_output.put_line('pragma error');

end;

                         SUB PROGRAMS

o    Sub programs are named pl/sql blocks which is used to solve particular task.

o    There are two types of sub programs supported by oracle.

0.     Procedures

1.     Functions

2.     Procedures

§  Procedures may or may not return a value.

§  Procedures return more than one value while using the out parameter.

§  Procedure can execute only 3 ways

 .       Anonymous Block

a.      Exec

b.     Call

§  Procedure can not execute in select statement.

§  Procedure internally having one time compilation process.

§  Procedure are used to improve the performance of business applications

§  Every procedure is having two parts

 .       Procedure Specification

§  In procedure specification we are specifying name of the procedure and types of the parameters.

a.      Procedure Body

§  In procedure body we are solving the actual task.

3. Example :

4. create or replace procedure p11(p_empno number) is

5. v_ename varchar2(10);

6. v_sal   number(10);

7. begin

8. select ename,sal into v_ename,v_sal from emp where empno=p_empno;

9. dbms_output.put_line(v_ename||','||v_sal);

10.       end;

§  Execute The Procedure in 3 ways

§  Method : 1 - Exec P11 ( 7902 )

§  Method : 2 - Begin
P11 ( 7902 );
end;

§  Method : 3 - Call P11 ( 7902 )

11.          Example :

12.          create or replace procedure p111(p_deptno number) is

13.          cursor c1 is select * from emp where deptno=p_deptno;

14.          i emp%rowtype;

15.          begin

16.          open c1;

17.          loop

18.          fetch c1 into i;

19.          exit when c1%notfound;

20.          dbms_output.put_line(i.ename||','||i.sal||','||i.deptno);

21.          end loop;

22.          close c1;

23.          end;

§  Parameters in Procedures

§  Parameters are used to pass the value into procedures and also return values from the procedure.

§  In this case we must use two types of parameters

a.      Formal Parameters

b.     Actual Parameters

c.      Formal Parameters

§  Formal Parameters are defined in procedure specification

§  In Formal Parameters we are defining parameter name & mode of the parameter

§  There are three types of modes supported by oracle.

a.      IN Mode

b.     OUT Mode

c.      INOUT Mode

4.     IN Mode :

§  By default procedure parameters having IN mode.

§  IN Mode is used to pass the values into procedure body.

§  This mode behaves like a constant in procedure body, through this IN Mode we can also pass default values using default or ":=" operator

§  Example :  

§  Create or replace procedure P1 ( p_deptno in number,

§  p_dname in varchar2,

§  p_loc in varchar2)

§  is

§  begin

§  insert into dept values (p_deptno,p_dname,p_loc);

§  dbms_output.put_line('record is inserted through procedure');

§  end;

       

§  There are three types of execution methods supported by in parameter.

1.     Positional Notations

2.     Named Notations

3.     Mixed Notations

1.     Positional Notations

Example : exec p1( 1, 'a','b');

2.     Named Notations

Example : exec p1 ( p_dname=>'x', p_loc=>'y', p_deptno=>2 )

3.     Mixed Notations

Example : exec p1 ( 1, p_dname=>'m', p_loc=>'n' );

5.     OUT Mode :

§  This mode is used to return values from procedure body.

§  OUT Mode internally behaves like a uninitialized variable in procedure body

6. Example :

7. Create or replace procedure p1 (a in number, b out number) is

8. begin

9. b:=a*a;

10.        dbms_output.put_line(b);

11.        end;

Note : In oracle if a subprogram contains OUT, INOUT Parameters those subprograms are executed using following two methods.

1.     Method - 1 : Using Bind Variable

2. Method - 2 : Using Annonymous Block

§  Bind Variable:

·         These variables are session variables.

·         These variables are created at host environment that's why these variables are also called as host variables.

·         These variables are not a pl/sql variables, but we can also use these variables in PL/SQL to execute subprograms having OUR Parameters.

§  Method - 1 : Bind Variable

§  Example : Variable b number;

§  exec p1 ( 10, :b);

                                       

§  Method - 2 : Annonymous Block

§  Example :Declare

§  b   number(10);

§  begin

§  p1( 5, b )

§  dbms_output.put_line( b );

§  end;

                               

Example :Develop a program for passing employee name as
 in parameter return salary of that employee using out parameter from emp table?

Prog :Create or replace procedure p1 ( p_ename in varchar2, p_sal out number ) is

    begin

    select sal  into p_sal from emp where empno=p_ename;

    end;

                               

§  Method - 1 :Bind variable

variable a number;

exec p1 ( 'KING', :a);

§  Method - 2 : Annonymous Block

Declare

a  number(10);

begin

exec p1( ' ALLEN ', a );

dbms_output.put_line( a );

end;

Example :

Develop a program for passing deptno as
a parameter return how many employees are working in a dept from emp table?

Prog :

Create or replace procedure pe2 ( p_deptno in number, p_t out number) is

begin

select count(*) into p_t from emp where deptno=p_deptno;

dbms_output.put_line(p_t);

end;

12.                        IN OUT Mode

§  This mode is used to pass the values into sub program & return the values from sub programs.

13.           Example :  

14.           Create or replace procedure p1 ( a in out number ) is

15.           begin

16.           a := a*a;

17.           dbms_output.put_line ( a );

18.           end;

     

·         Method - 1 :Bind Variable

Variable a number;

exec  :a :=10;

exec  p1 ( :a );

                 

·         Method - 2 : Annonymous Block

Declare

a  number(10) := &n;

begin

p1( a );

dbms_output.put_line ( a );

end;

Example :

Create or replace procedure pe4 ( a in out number) is

begin

select sal into a from emp where empno=a;

dbms_output.put_line( a );

end;

                 

§  PRAGMA AUTONOMOUS TRANSACTION

§  Autonomous transactions are independent transactions used in either procedures or in triggers.

§  Generally autonomous transactions are used in child procedures, These procedures are not effected from the main transactions when we are using commit or rollback.

§  Example : Create table test ( name varchar2(10));

§  Program : Create or replace procedure P1 is

§      pragma autonomous_transaction;

§      begin

§      insert into ptest values ('india');

§      commit;

§      end;

§   

§  Execute The Program: Begin

§      insert into ptest values ('usa');

§      insert into ptest values ('uk');

§      P1;

§      rollback;

§      end;

§   

§  With out Autonomous Transaction

§  Program : Create or replace procedure P1 is

§      begin

§      insert into ptest values ('india');

§      commit;

§      end;

§      Execute The Program:   Begin

§      insert into ptest values ('usa');

§      insert into ptest values ('uk');

§      P1;

§      rollback;

§      end;

     

24.                        Functions

§  Function is a named pl/sql block which is used to solve particular task and by default functions return a single value.

§  Function is allow to write multiple return statements but it execute only first return statement.

§  Function can execute in 4 ways

0.     Annonymous Block

1.     Select Statement

2.     Bind Variable

3.     Exec

§  Function also having two parts

0.     Function Specification

1.     Function Body

§  In Function Specification we are specifying name of the function and type of the parameters where as in function body we are solving the actual task.

25.          Example : Create or replace function fun1( a varchar2)

26.                return varchar2

27.                is

28.                begin

29.                return a;

30.                end;

31.              

32.          Method - 1 : Select Clause

33.                      Select fun1('hi') from dual

34.               

35.          Method - 2 :Annonymous Block

36.                Declare

37.                a   varchar2(10);

38.                begin

39.                a :=fun1('hi');

40.                dbms_output.put_line(a);

41.                end;

42.           

43.          Method - 3 : Bind Variable

44.                Variable  V  Varchar2(20);

45.                Begin

46.                :a:=fun1('hi');

47.                end;

48.               

49.          Method - 4 :      Exec

50.                            Exec Dbms_output.put_line(fun1('hi'));

51.          Example :   Create or replace function fun2 (a number)

52.                return varchar2

53.                is

54.                begin

55.                if mod(a,2)=0 then

56.                return 'even number';

57.                else

58.                return 'odd number';

59.                end if;

60.                end;

61.                  

62.          Note : We can also use user defined function in insert statement.

63.               

64.          Example :   Create table t1(sno number(10), msg varchar2(10));

65.                Insert into t1 values ( 1, fun2(5));

66.                Select * from t1;

67.           

68.           

69.          Example : Write a pl/sql stored function for passing empno as parameter return
gross salary from emp table based on following condition?

70.                Condition => gross:=basic+hra+da+pf;

71.                hra   =>    10% of Sal

72.                da    =>    20% of Sal

73.                pf    =>    10% of Sal

74.               

75.          Prog : Create or replace function fun3 (p_empno number)

76.                return number

77.                is

78.                vsal number(10);

79.                gross number(10);

80.                hra number(10);

81.                da number(10);

82.                pf number(10);

83.                begin

84.                select sal into vsal from emp where empno=p_empno;

85.                hra:=vsal*0.1;

86.                da:=vsal*0.2;

87.                pf:=vsal*0.1;

88.                gross:=vsal+hra+da+pf;

89.                return gross;

90.                end;

91.           

92.          Note :      We can also use predefined functions in user defined functions and also this user defined

93.                      functions in same table or different table.

94.           

95.          Example :   Create or replace function fm

96.                      return number

97.                      is

98.                      vsal number(10);

99.                      begin

100.                    select max(sal) into vsal from emp;

101.                    return vsal;

102.                    end;

103.         

104.        Note : If we want to return more number of values from function we are using OUT Parameter.

105.         

106.        Example :   Create or replace function fun4

107.              (p_deptno in number

108.              ,p_dname  out varchar2

109.              ,p_loc    out varchar2)

110.              return varchar2

111.              is

112.              begin

113.              select dname,loc into p_dname,p_loc from dept where deptno=p_deptno;

114.              return p_dname;

115.              end;

116.         

117.              Variable  a  varchar2(10);

118.              Variable  b  varchar2(10);

119.              Variable  c  varchar2(10);

120.                   

121.              Begin

122.              :a:=fun4 ( 10, :b, :c);

123.              end;

124.                   

125.              Print b c;

126.         

127.        Example :   Write a pl/sql stored function for passing empno,date as
parameter return number of years that employee is working based on date from emp table?

128.         

129.        Prog :      Create or replace function fun5(p_empno number,p_date date)

130.              return number

131.              is

132.              a number(10);

133.              begin

134.              select months_between(p_date,hiredate)/12 into a from emp where empno=p_empno;

135.              return (round(a));

136.              end;

137.                   

138.        Execution : Select empno,ename,hiredate,

139.              fun5(empno,sysdate)||'Years' Exp

140.              from emp where empno=7902

141.         

142.        Example : Write a pl/sql stored function for passing empno as parameter,
calculate tax based on following conditions by using emp table.

143.              Conditions:

144.            1) if annual salary >10000 then tax=10%

145.              2) if annual salary >20000 then tax=20%

146.              3) if annual salary >50000 then tax=30%

147.         

148.        Prog : Create or replace function fun7 (p_empno number)

149.              return number

150.              is

151.              vsal number(10);

152.              asal number(10);

153.              itax number(10);

154.              begin

155.              select sal into vsal from emp where empno=p_empno;

156.              asal:=vsal*12;

157.              if asal>10000 and asal<=15000 then

158.              itax:=asal*0.1;

159.              elsif asal>15000 and asal<=2000 then

160.              itax:=asal*0.2;

161.              elsif asal>20000 then

162.              itax:=asal*0.3;

163.              else

164.              itax:=0;

165.              end if;

166.              return itax;

167.              end;

                         Packages

o    Package is a database object which is used encapsulate variables, constants, procedures, cursors, functions, types in to single unit.

o    Packages does not accepts parameters, can not be nested, can not be invoked.

o    Generally packages are used to improve performance of the application because when we are calling packaged sub program first time total package automatically loaded into memory area.

o    Whenever we are calling subsequent sub program calls pl/sql run time engine calling those sub program from memory area.

o    This process automatically reduces disk I/O that's why packages improves performance of the application.

o    Packages have two types.

0.     Package Specification

1.     Package Body

o    In Package Specification we are defining global data and also declare objects, sub programs where as in Package Body we are implementing sub programs and also package body sub program internally behaves like a private sub program.

Package Specification Syntax :

Syntax :

Create or Replace Package Package_Name

Is/As

Global Variable Declaration;

Constant Declaration;

Cursor         Declaration;

Types          Declaration;

Procedure      Declaration;

Function Declaration;

End;

Package Body Syntax :

Syntax :

Create or Replace Package Body

Package_Name

Is/As

Procedure      Implementations;

Function Implementations;

End;

Invoking Packaged Subprograms

7.     Exec Package_Name.Procedure_Name ( Actual Parameters );

8.     Select Package_Name.Function_Name ( Actual Parameters ) from dual;

Package Specification

Example : Create or replace package pack1 is

     procedure pr1;

     procedure pr2;

     end;

Package Body

Example : Create or replace package body pack1 is

     procedure pr1

     is

     begin

     dbms_output.put_line('first procedure');

     end pr1;

     procedure pr2

     is

     begin

     dbms_output.put_line('second procedure');

     end pr2;

     end;

 

     Exec Pack1.pr1;

     Exec Pack2.pr2;

                         Global Variable

o    It is one of the variable which is used to define in package specification and implement in package body that variables are call it as a global variables.

                         Local Variable

o    It is one of the variable which is used to define in programs ( Procedure, Function ) and implement with in the program only.

Package Specification

Example : Create or replace package pck2 is

     g number(5):=500;

     procedure p1;

     function f1 ( a number ) return number;

     end;

Package Body

Example : create or replace package body pck2 is

     procedure p1

     is

     z number(5);

     begin

     z:=g/2;

     dbms_output.put_line(z);

     end p1;

     function f1( a number ) return number

     is

     begin

     return a*g;

     end f1;

     end;

                         Procedures Overloading

o    Overloading refers to same name can be used for different purposes i.e we are implementing overloading procedures through packages only, those procedures having same name and also different types of arguments.

Package Specification

Example :      Create or replace package pck3 is

         procedure p1(a number, b number);

         procedure p1(x number, y number);

         end;

Package Body

Example :      Create or replace package body pck3 is

         procedure p1 (a number, b number)

         is

         c number(10);

         begin

         c:=a+b;

         dbms_output.put_line(c);

         end p1;

         procedure p1 (x number, y number)

         is

         z number(10);

         begin

         z:=x+y;

         dbms_output.put_line(z);

         end p1;

         end;/

        

         Exec Pack.p1 ( a=>10, b=>20 );

         Exec Pack.p1 ( x=>100, b=>200);

                         Forward Declaration

o    Whenever we are calling procedures into another procedure then only we are using forword declaration i.e whenever we are calling local procedure into global procedure first we must implement local procedures before calling otherwise use a forward declaration in package body.

Package Specification

Example :      Create or replace package pack14 is

procedure p1;

end;

Package Body

Example :      Create or replace package body pack14 is

   procedure p2;

   procedure p1

   is

   begin

   p2;

   end;

   procedure p2

   is   

   begin

   dbms_output.put_line('local procedure');

   end p2;

   end;

                         Triggers

o    Trigger is also same as stored procedure & also it will automatically invoked whenever DML Operation performed against table or view.

o    There are two types of triggers supported by PL/SQL.

§  Statement Level Trigger

§  Row Level Trigger

o    In Statement Level Trigger, Trigger body is executed only once for DML Statements.

o    In Row Level Trigger, Trigger body is executed for each and every DML Statements.

             Syntax :

             create { or replace }   trigger trigger_name

             before / after    trigger event

             insert / update / delete on table_name

             { for each row }

             { where condition }

             { declare }

             variable declarations, cursors

             begin

             -----

             end;

Execution order in Triggers

0.     Before Statement Level

1.     Before Row Level

2.     After Row Level

3.     After Statement Level

4.     Statement Level Trigger

§  In Statement Level Trigger, Trigger body is executed only once for each DML Statement. Thats why generally statement level triggers used to define type based condition and also used to implement auditing reports. These triggers does not contain new, old qualifiers.

Q) Write a pl/sql statement level trigger on emp table not to perform DML Operations in saturday and sunday?

Program :  Create or replace trigger tr1 before insert or update or delete on tt

begin

if to_char(sysdate,'DY') in ('SAT','SUN')

then

raise_application_error(-20123,'we can not perform DMLs on sat and sunday');

end if;

end;

Q) Write a pl/sql statement level trigger on emp table not to perform DML Operation on last day of the month?

Program : create or replace trigger tt2 before insert or update or delete on tt

begin

if sysdate=last_day(sysdate) then

raise_application_error (-20111,'we can not perform dml operations on lastday ');

end if;

end;

 

Trigger Event ( or ) Trigger Predicate ClausesTrigger Event ( or ) Trigger Predicate Clauses

§  If you want to define multiple conditions on multiple tables then all database systems uses trigger events.

§  These are inserting, updating, deleting clauses

§  These clauses are used in either row level or statement level triggers.

Syntax : if inserting then
statements;
elsif updating then
statements;
elsif deleting then
statements;
end if;

Q ) Write a pl/sql statement level trigger on emp table not to perform any dml operation in any days using triggering event?

Program : create or replace trigger tr3 before insert or update or delete on tt

 begin

 if inserting then

 raise_application_error (-20121,'we can not perform inserting operation');

 elsif updating then

 raise_application_error (-20122,'we can not perfrom update operation');

 elsif deleting then

 raise_application_error (-20123,'we can not perform deleting operation');

 end if;

 end;

Example : Create table test ( msg varchar2(100));

create or replace trigger tr4 after insert or update or delete on tt

declare

a varchar2(50);

begin

if inserting then

a := 'rows inserted';

elsif updating then

a := 'rows updated';

elsif deleting then

a := 'rows deleted';

end if;

insert into testt values (a);

end;

5.     Row Level Trigger

§  In Row Level Trigger, Trigger body is executed for each row for DML Statement, Thats why we are using for each row clause in trigger specification and also data internally stored in 2 rollback segment qualifiers are OLD & NEW

§  These qualifiers are used in either trigger specification or in trigger body. when we are using these modifiers in trigger body we must use colon prefix in the qualifiers.

Syntax : old.column_name ( or ) :new.column_name.

§  When we are using these qualifiers in when clause we are not allow to use colon infront of the qualifiers.

Qualifier

Insert

Update

Delete

:new

YES

YES

NO

:old

NO

YES

YES

§  In Before Triggers, Trigger body is executed before DML Statements are effected into database.

§  In After Triggers, Trigger body is executed after DML Statements are effected into database.

§  Generally if we want to restrict invalid data entry always we are using before triggers, where as if we are performing operation on the one table those operations are effected in another table then we are using after trigger.

§  Whenever we are inserting values into new qualifiers we must use before trigger otherwise oracle server returns an error.

Q: Write a PL/SQL Row Level Trigger on emp table whenever user inserting data into a emp table sal should be more than 5000?

Program : Create or replace trigger t90 before insert on tb

for each row

begin

if :new.sal<5000 then

raise_application_error (-20123,'salary should be more than 5000');

end if;

end;

Q : Write a PL/SQL Row Level Trigger on emp, dept tables while implement on delete cascade concept without using on delete cascade clause?

Program : Create or replace trigger t1

after delete on dept

for each row

begin

delete from emp where deptno=:old.deptno;

end;

Q : Write a PL/SQL Row Level Trigger on dept table whenever updating deptno's in dept table automatically those deptno's modified into emp table?

Program : Create or replace trigger t19

after update on dept

for each row

begin

update emp set deptno=:new.deptno where deptno=:old.deptno;

end;

Q : Write a PL/SQL Row Level Trigger whenever user inserting data into ename column after inserting data must be converted into uppercase ?

Program : create or replace trigger t21

   before insert on emp

   for each row

   begin

   :new.ename:=upper(:new.ename);

   end;

Q ) Write a PL/SQL Row Level Trigger on emp table by using below conditions?

7.     whenever user inserting data those values stored in another table

8.     whenever user updating data those values stored in another table

9.     whenever user deleting data those values stored in another table

Program : First we create 3 tables which are having the same structure of emp table.

   Create or replace trigger te1

   after insert or update or delete on t01

   for each row

   begin

   if inserting then

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

   elsif updating then

   insert into e2(empno,ename) values (:old.empno,:old.ename);

   elsif deleting then

   insert into e3(empno,ename) values (:old.empno,:old.ename);

   end if;

   end;

Q : Write a PL/SQL Trigger on emp table whenever user deleting records from emp table automatically display remaining number of existing record number in bottom of the delete statment?

Program : Create or replace trigger tp1 after delete on emp

   declare

   a number(10);

   begin

   select count(*) into a from emp;

   dbms_output.put_line('remaining records are: '||a);

   end;

6.     Mutating Trigger

7. Example :

8.    Create or replace trigger tp1 after delete on emp

9.    for each row

10.          declare

11.          a number(10);

12.          begin

13.          select count(*) into a from emp;

14.          dbms_output.put_line('remaining records are: '||a);

15.          end;

§  Into a Row Level Trigger based on a table trigger body can not read data from same table and also we can not perform DML Operations on same table.

§  If we are trying to this oracle server returns an error is table is mutating.

§  This Error is called Mutating Error

§  This Trigger is called Mutating Trigger

§  This Table is called Mutating Table

§  Mutating Errors are not accured in Statement Level Trigger Because through these Statement Level Trigger when we are performing DML Operations automatically data Committed into database.

§  Where as in Row Level Trigger when we are performing transaction data is not committed and also again we are reading this data from the same table then only mutating error is accured.

§  To avoid this mutating error we are using autonomous transaction in triggers.

16.    Example : Create or replace trigger tp1 after delete on t01

17.          for each row

18.          declare

19.          pragma autonomous_transaction;

20.          a number(10);

21.          begin

22.          select count(*) into a from t01;

23.          dbms_output.put_line('remaining records are: '||a);

24.          commit;

25.          end;

26.                        DDL Triggers

§  We can also create triggers on schema level, database level. These types of triggers are called DDL Triggers or System Triggers.

§  These types of triggers are created by database administrator.

Syntax :
Create or replace trigger trigger_name 
Before / After
Create / Alter / Drop / Truncate / Rename
On Username.Schema

Q : Write a PL/SQL Trigger on scott schema not to drop emp table?

Program : Create or replace trigger td

    before drop on apps.schema

    begin

    if ora_dict_obj_name = 'T100' and

    ora_dict_obj_type = 'TABLE' then

    raise_application_error(-20121,'we can not drop this table');

    end if;

    end;

        

Collections

§  Oracle server supports following types

0.     PL/SQL Record ( or ) Record Type

1.     Index by table ( or ) PL/SQL table ( or ) Associative Arrays.

2.     Nested tables

3.     Varrays

4.     Ref Cursors

1.     Index By Table

§  This is an user defined type which is used to store multiple data items in to a single unit. Basically this is an unconstraint table

§  Generally these tables are used to improve performance of applications because these tables are stored in memory area thats why these tables are also called as memory tables.

§  Basically these table contains key value pairs i.e value field is stored in actual data and key field stored in indexes.

§  Key field values are either integer or character and also these values are either -ve or +ve.

§  These indexes key behaves like a primary key i.e does not accept duplicate and null values. basically this key datatype is binary_integer.

§  Index by table having following collection methods.

6.     exists

7.     first

8.     last

9.     prior

10.                        next

11.                        count

12.                        delete ( range of indexes )

2. Example 1 :     

3.      declare

4.      type t1 is table of number(10)

5.      index by binary_integer;

6.      v_t t1;

7.      begin

8.      v_t(1):=10;

9.      v_t(2):=20;

10.                v_t(3):=30;

11.                v_t(4):=40;

12.                v_t(5):=50;

13.                dbms_output.put_line(v_t(3));

14.                dbms_output.put_line(v_t.first);

15.                dbms_output.put_line(v_t.last);

16.                dbms_output.put_line(v_t.prior(3));

17.                dbms_output.put_line(v_t.next(4));

18.                dbms_output.put_line(v_t.count);

19.                dbms_output.put_line(v_t(5));

20.                end;

21.          Example 2:

22.                declare

23.                type t1 is table of number(10)

24.                index by binary_integer;

25.                v_t t1;

26.                begin

27.                v_t(1):=10;

28.                v_t(2):=20;

29.                v_t(3):=30;

30.                v_t(4):=40;

31.                v_t(5):=50;

32.                dbms_output.put_line(v_t.count);

33.                v_t.delete(2,3);

34.                dbms_output.put_line(v_t.count);

35.                v_t.delete;

36.                dbms_output.put_line(v_t.count);

37.                end;

Q : Write a PLSQL program to get all employee names from emp table and store it into index by table and display data from index by table?

Program :

     declare

     type t1 is table of varchar2(10)

     index by binary_integer;

     v_t t1;

     cursor c1 is select ename from emp;

     n number(5):=1;

     begin

     open c1;

     loop

     fetch c1 into v_t(n);

     exit when c1%notfound;

     n:=n+1;

     end loop;

     close c1;

     for i in v_t.first..v_t.last

     loop

     dbms_output.put_line(v_t(i));

     end loop;

     end;

Program :

     declare

     type t1 is table of varchar2(10)

     index by binary_integer;

     v_t t1;

     begin

     select ename bulk collect into v_t from emp;

     for i in v_t.first..v_t.last

     loop

     dbms_output.put_line(v_t(i));

     end loop;

     end;

Program :

     declare

     type t1 is table of date

     index by binary_integer;

     v_t t1;

     begin

     for i in 1..10

     loop

     v_t(i):=sysdate+i;

     end loop;

     for i in v_t.first..v_t.last

     loop

     dbms_output.put_line(v_t(i));

     end loop;

     end;

Q : Write a PLSQL Program to retrieve all joining dates from emp table and store it into index by table and display content from index by table?

Program :

     declare

     type t1 is table of date

     index by binary_integer;

     v_t t1;

     begin

     select hiredate bulk collect into v_t from emp;

     for i in v_t.first..v_t.last

     loop

     dbms_output.put_line(v_t(i));

     end loop;

     end;

Example :

     declare

     type t1 is table of varchar2(10)

     index by varchar2(10);

     v_t t1;

     x varchar2(10);

     begin

     v_t('a'):= 'ARUN';

     v_t('b'):= 'AJAY';

     v_t('c'):= 'ABHI';

     x :='a';

     loop

     dbms_output.put_line(v_t(x));

     x := v_t.next(x);

     exit when x is null;

     end loop;

     end;

Example :

     declare

     type t1 is table of emp%rowtype

     index by binary_integer;

     v_t t1;

     x number(5);

     begin

     select * bulk collect into v_t from emp;

     x:=1;

     loop

     dbms_output.put_line(v_t(x).empno||','||v_t(x).ename);

     x:=v_t.next(x);

     exit when x is null;

     end loop;

     end;

     ( OR )

 

Example :

     declare

     type t1 is table of emp%rowtype

     index by binary_integer;

     v_t t1;

     begin

     select * bulk collect into v_t from emp;

     for i in v_t.first..v_t.last

     loop

     dbms_output.put_line(v_t(i).empno||','||v_t(i).ename);

     end loop;

     end; 

38.                        Nested Tables

§  This is also user defined type which is used to store multiple data items in a single unit but before we are storing actual data we must initialize the data while using constructor.

§  Here constructor name is same as type name. Generally we are not allow to store index by tables permanently into database, to overcome this problem they are introduce Nested Tables to extension of the index by tables.

§  These user defined types stored permanently into database using sql.

§  In Index by tables we can not add or remove the indexes. where as in Nested tables we can add or remove the indexes using Extend, Trim collection methods.

§  In Nested tables we can allocate the memory explicitly while using Extend method

Syntax : Type type_name is Table of datatype( size );
variable_name type_name( );
Constructor_Name

Example :

     Declare

     type t1 is table of number(10);

     v t1:=t1();

     begin

     v.extend(100);

     v(100):=10;

     dbms_output.put_line(v(100));

     end;

Example :

     Declare

     type t1 is table of number(10);

     v1 t1:=t1(10,20,30,40,50);

     begin

     dbms_output.put_line(v1.first);

     dbms_output.put_line(v1.last);

     dbms_output.put_line(v1.prior(3));

     dbms_output.put_line(v1.next(3));

     dbms_output.put_line(v1.count);

     dbms_output.put_line(v1(3));

     for i in v1.first..v1.last

     loop

     dbms_output.put_line(v1(i));

     end loop;

     end;

Example :

     Declare

     type t1 is table of number(10);

     v1 t1;

     v2 t1:=t1();

     begin

     if v1 is null then

     dbms_output.put_line('v1 is null');

     else

     dbms_output.put_line('v1 is not null');

     end if;

     if v2 is null then

     dbms_output.put_line('v2 is null');

     else

     dbms_output.put_line('v2 is not null');

     end if;

     end;

Example :

     Declare

     type t1 is table of number(10);

     v t1:=t1();

     begin

     v.extend;

     v(1):=5;

     dbms_output.put_line(v(1));

     end;

Q : Write a PLSQL program to get all employee names from emp table and store it into Nested Table and display data from Nested Table?

Program  

     declare

     type t1 is table of varchar2(10);

     v t1:=t1();

     cursor c1 is select ename from emp;

     n number(10):=1;

     begin

     for i in c1

     loop

     v.extend();

     v(n):=i.ename;

     n:=n+1;

     end loop;

     for i in v.first..v.last

     loop

     dbms_output.put_line(v(i));

     end loop;

     end;

     ( OR )

Program :

     declare

     type t1 is table of varchar2(10);

     v t1:=t1();

     begin

     select ename bulk collect into v from emp;

     for i in v.first..v.last

     loop

     dbms_output.put_line(v(i));

     end loop;

     end;

Program :

     declare

     type t1 is table of emp%rowtype;

     v t1:=t1();

     begin

     select * bulk collect into v from emp;

     for i in v.first..v.last

     loop

     dbms_output.put_line(v(i).empno||','||v(i).ename||','||v(i).job);

     end loop;

     end;

39.                        Varrays

§  This is also user defined type which is used to store multiple data items in a single unit but before we are storing actual data we must initialize the data while using constructor.

§  These user defined types stored permanently into database using sql.

§  Basically we are using the Varrays for retrieving the huge data.

Syntax : Type type_name is varray( maxsize ) of datatype( size );
Variable_name Type_name := Type_name( );

Program :

Declare

type t1 is varray(50) of emp%rowtype;

v t1:=t1();

begin

select * bulk collect into v from emp;

for i in v.first..v.last

loop

dbms_output.put_line(v(i).empno||','||v(i).ename||','||v(i).job);

end loop;

end;

§  Difference b/w Index by Table, Nested Table, Varrays

Index by Table

Nested Table

Varrays

40.                                                           It is not stored permanently in database.

41.                                                           We can not add or remove indexes.

42.                                                           Indexes starting from negative to positive numbers and also having key value pairs.

43.                                                     It is stored permanently in database by using sql.

44.                                                     We can add or remove indexes using extend, trim method.

45.                                                     Indexes starting from 1.

46.                                                     It is stored permanently in database by using sql.

47.                                                     We can add or remove indexes using extend, trim method.

48.                                                     Indexes starting from 1.

§  Bulk Mechanism

§  Bulk is one of the method which is used to improve the performance of the applications.

§  Oracle introduce bulk bind process using collection i.e in this process we are putting all sql statement related values into collection and in this collection we are performing insert, update, delete at a time using for all statement.

§  In this bulk we have two actions

0.     Bulk Collect

1.     Bulk Bind

3.     Bulk Collect

§  In this clause we are used to fetch the data from resource into collection

§  This clauses used in

0.     Select ...........into............clause

1.     Cursor...........Fetch...........Statement

2.     Dml............Returning.........Clauses

2.     Bulk Collect used in select .....into .....clause Syntax : select * bulk collect into collection_name from table_name.

3. Program :

4.   Declare

5.   type t1 is table of emp%rowtype

6.   index by binary_integer;

7.   v t1;

8.   begin

9.   select * bulk collect into v from emp;

10.         for i in v.first..v.last

11.         loop

12.         dbms_output.put_line(v(i).empno||','||v(i).ename||','||v(i).job);

13.         end loop;

14.         end;

   

15.                        Bulk Collect used in cursor......fetch.......statement Syntax : fetch cursor_name bulk collect into collection_variable.

16.   Program

17.         Declare

18.         type t1 is table of varchar2(10)

19.         index by binary_integer;

20.         v1 t1;

21.         v2 t1;

22.         cursor c1 is select ename,job from emp;

23.         begin

24.         open c1;

25.         fetch c1 bulk collect into v1,v2;

26.         close c1;

27.         for i in v1.first..v1.last

28.         loop

29.         dbms_output.put_line(v1(i)||','||v2(i));

30.         end loop;

31.         end;

                           

Time Program with out BULK

  Declare

  vrow varchar2(50);

  cursor c1 is select object_name from all_objects;

  z1 number(10);

  z2 number(10);

  begin

  z1:=dbms_utility.get_time;

  open c1;

  loop

  fetch c1 into vrow;

  exit when c1%notfound;

  end loop;

  close c1;

  z2:=dbms_utility.get_time;

  dbms_output.put_line(z1);

  dbms_output.put_line(z2);

  dbms_output.put_line(z2-z1);

  end;

   

Time Program with BULK

    Declare

  type t1 is table of varchar2(50) index by binary_integer;

  v1 t1;

  cursor c1 is select object_name from all_objects;

  z1 number(10);

  z2 number(10);

  begin

  z1:=dbms_utility.get_time;

  open c1;

  loop

  fetch c1 bulk collect into v1;

  exit when c1%notfound;

  end loop;

  close c1;

  z2:=dbms_utility.get_time;

  dbms_output.put_line(z1);

  dbms_output.put_line(z2);

  dbms_output.put_line(z2-z1);

  end;

32.                        Bulk Collect used in DML..........Returning clauses. Syntax : dml statement returning column_name into variable_name;

33.   Example :

34.         Variable a varchar2(10);

35.         Update emp set sal=sal+100 where ename ='KING' returning job into :a;

36.         Print a;

Q : Write a PLSQL Stored Procedure modify salaries of the clerk from emp table and also these modified value immediately stored into index by table by using dml ...returning clause and also display content from index by table?

Program :

  Create or replace procedure p1 is

  type t1 is table of emp%rowtype

  index by binary_integer;

  v1 t1;

  begin

  update emp set sal=sal+100 where job='CLERK'

  returning empno,ename,job,mgr,hiredate,sal,comm,deptno

  bulk collect into v1;

  dbms_output.put_line('updated no:of clerks are:'||sql%rowcount);

  for i in v1.first..v1.last

  loop

  dbms_output.put_line(v1(i).ename||','||v1(i).job||','||v1(i).sal);

  end loop;

  end;

4.     Bulk Bind

§  In bulk bind process we are performing bulk of operations using collection i.e in this process we are using bulk update, bulk delete, bulk insert using forall statement.

§  Before we are using bulk bind process we are fetching data from database into collections using bulk collect clause.

Syntax : forall indexvar in collectionvar.frist..collectionvar.last

Example :

Declare

type t1 is varray(10) of number(10);

v1 t1:=t1(10,20);

begin

forall i in v1.first..v1.last

update emp set sal=sal+100 where deptno=v1(i);  

end;

Bulk Update

Program :

Declare

type t1 is table of number(5) index by binary_integer;

v1 t1;

begin

select empno bulk collect into v1 from emp;

forall i in v1.first..v1.last

update emp set sal=sal+111 where empno=v1(i);

end;

Bulk Delete

Program :

Declare

type t1 is varray(10) of number(10);

v1 t1:=t1(20,30,40);

begin

forall i in v1.first..v1.last

delete from emp where empno=v1(i);

end;

Bulk Insert

Program :

Declare

type t1 is table of number(10) index by binary_integer;

v1 t1;

begin

for i in 1..100

loop

v1(i):=i;

end loop;

forall i in v1.first..v1.last

insert into bt values (v1(i));

end;

 

Comments

Post a Comment

Popular posts from this blog

opaque schema xsd (standard file used in OIC)

DOCUMENTATION ON SANDBOX and PERSONALIZATION

SQL,PLSQL interview practice and DSA patterns