You are on page 1of 21

c  c

   
 

 It is defined as procedural language+sql having

1.having conditional statements.

2.having iterative loops.


 


3Y It is procedural.
3Y It supports all the datatypes of SQL.
3Y Instead of sending ͚n͛ number of SQL statements they can be binded into PL/SQL block which
minimises network traffic.

 
 
c  

c   

 It has 3 categories in it.

1.Y eclaration
2.Y Executable statements
3.Y Exception handling

Note: eclaration and Exception blocks are optional.


  
c  

 eclare

ec 1;

ec 2;

Begin

Statement 1;

Statement 2;

Exceptions

Exec 1;

Exec 2;

End;

Save the pl/sql block as: sql> filename.sql

To run it sql>@filename.sql




1.Y Single line comments: --


2.Y Multiple line comments: /* */
DY D

^ 
 ! 

These blocks are stored directly into database, the advantage is every user who is connected to
database can access these blocks.

3Y every block is stored with some unique name

1)procedures

2)functions

3)triggers

4)packages
3Y Ôll the variables used should be declared in the declaration part itself.
3Y To display the messages on screen we use › 


dbms_output : is the package

put_line : is the function in this package which is used for displaying info on screen.

package: is a collection of procedure and functions.

put_line:

Is a function which takes single parameter as input, if at all user wants to give 2 values then we
use concatenation operator which combines 2 values and converts into single value ||.

0 "c 0

declare

i number:=&enter_val;

begin

dbms_output.put_line('val i='||i);

end;

#$0%c0#%&^c  0

1):= IS Ô ÔSSIGNMENT OPERÔTOR WITH WHICH THE VÔLUES WILL BE ÔSSIGN TO VÔRIÔBLES.

2)= IS USE FOR COMPÔRISON.

   





1.Y declare

age number:=&enter_age;

begin

if(age>=18) then

dbms_output.put_line('THE PERSON IS Ô MÔ OR');

else

dbms_output.put_line('THE PERSON IS Ô MINOR');

end if;

end;
2.Y declare

mavg number:=&enter_avg;

begin

If(mavg>=60) then

dbms_output.put_line('YOU GOT FIRST IVISION');

elsif(mavg>=50 and mavg<60) then

dbms_output.put_line('YOU GOT SECON IVISION');

elsif(mavg>=40 and mavg<50) then

dbms_output.put_line('YOU GOT THIR IVISION');

else

dbms_output.put_line('PLZ TRY ÔGÔIN');

end if;

end;



Loops are used to perform iterative operations.

PL/SQL supports 3 types of loops.

3Y While loop.
3Y Loop exit.
3Y For loop.

†


 ECLÔRE

I NUMBER;

BEGIN

I:=1;

WHILE(I<=5) LOOP

BMS_OUTPUT.PUT_LINE('VÔL I='||I);

I:=I+1;

EN LOOP;
EN;


'

ECLÔRE

I NUMBER;

BEGIN

I:=1;

LOOP

BMS_OUTPUT.PUT_LINE('VÔL I='||I);

I:=I+1;

EXIT WHEN I>5;

EN LOOP;

EN;



3Y BEGIN

FOR K IN 1..5 LOOP

BMS_OUTPUT.PUT_LINE('VÔL K='||K);

EN LOOP;

EN;

3Y BEGIN

FOR K IN REVERSE 1..5 LOOP

BMS_OUTPUT.PUT_LINE('VÔL K='||K);

EN LOOP;
EN;
c  ! 


1.Y š(
: refers to the datatype of a particular column of a table.
2.Y š)(
refers to the entire row of the table.

 

Is defined as a PL/SQL memory area or buffer used to store the records fetched by select
statement. The buffer name is the cursor name.

The adv of this concept is unlike variables the work area can store multiple rows.

 

   *(    


 

& 0' 

 )
 

+Y Implicit cursor: This cursor will be used by sql itself for processing client request.
,Y Explicit cursor.
Y Simple cursor.
Y Ref cursor.
(a)Y Strong cursor.
(b)Y Weak cursor.

we have cursor attributes which are used for getting the position of cursor in work area.

3Y š isopen: Returns true if the cursor is already open else returns false.
3Y šfound : Return true if there is any row exists at current cursor location else it returns
false.
3Y šnotfound: Works opposite to šfound i.e, it return false if there is any row exists at current
cursor location else it returns true.
3Y šrowcount: Returns total no of rows in work area.


 

 

1)define the cursor


2)define a variable which hold row at cursor

3)open cursor

4)read row into cursor variable

5)close cursor .

c  

-
  The advantage of this cursor is we can pass the parameter at runtime so that we
can have selected rows in cursor work area.

 !c  Ôre the program units which help us to write piece of code which can be called
anywhere or anytime in another pl/sql block or subprogram.

There are diff types of subprograms

+c

 Is a subprogam which will not return any value

Syntax:

Create or replace procedure <pname>(p1 type,p2 type,...) Is

Var dec

Begin

Statements

End;

,   Is a subprogram which returns single value

Syntax:

Create or replace function <fname>(p1 type,p2 type,...) Return type is

Var dec

Begin

Statements

Return type_res

End;

   Is a stored procedure or a subprogram which works similar to a procedure

but it also return a single value output9[.


syntax:

create or replace function <fname>(p1 type,p2 type,...) return return_type is

var declaration

begin

statements

exception

end;

c  
 It is a collection of procedure and functions

Note: In subprogram we write business logics

Note: Subprograms get stored into database directly

So whoever is connected to database can access subprogram

c  

Ôre used to pass some input to sub program so that we can get some dynamic output

There are 3 types of parameters

+By default all parameter are "in" type i.e, we can pass input only

,  We can get values as result by this parameter

  we can pass the values or get the result by this type of parameter.

0'


Is defined as an erroneous event which occurs during the program execution. In Oracle an
error condition is said to be an EXCEPTION.

Exceptions are of two types.


3Y Predefined exception.
3Y User defined exception.
c



'


+Y #. ()


Raises when select statement retrieves more than one row.
0'
 eclare
Bank_rec bankšrowtype;
Begin
Select * into bank_rec from bank
Where accname=͛&name͛;
opl(͚account number: ͛||bankrec.accno);
opl(͚account name: ͚||bankrec.accname);
opl(͚account balance: ͚||bankrec.amt);
opl(͚account open date: ͚||bankrec.opdate);

Exception

When too_many_rows then

opl(͚more than one row exists with the accname given͛);

End;

,Y ^/  /  


Raises when select statement doesnot found appropriate record.
0'
 eclare
No bank.accnoštype;
Begin
Select * into bank_rec from bank
Where accname=͛&name͛;
opl(͚account number: ͛||bankrec.accno);
opl(͚account name: ͚||bankrec.accname);
opl(͚account balance: ͚||bankrec.amt);
opl(͚account open date: ͚||bankrec.opdate);

Exception

When no_data_found then


opl(͚no record found with the given name͛);
End;
/
Y l
/
0

Raises when a number is divided with zero.
0'
 eclare
Ô number:=&a;
B number:=&b;
C number:=&c;
Begin
C:=a/b;
opl(a||b||c);
Exception
When zero_devide then
opl(͚a number is getting devided by a zero͛);
End;
/
rY &0  / !

Raises when a numeric datatype variable stores a pure char. Type data.

>Y  


Raises when in a variable the datavalue is more than it͛s size is inserted.

ùY * /0 //


'
Raises when a duplicate value is inserted into a column which has a primary key
constraint on it.

´



'


 This exception is externally declared by the user, raised by the user and handled by the user.

3Y When exception arises the execution of the program gets terminated and the cursor moves to
the exception part.

( ' declare


   1Exception name> exception;
  Begin
Raise exception;
Exception
<Exception handling statements>;
End;
/
0'

declare
qty_is_less_than_required exception;
qord number:=&enter_qord;
prow prodšrowtype;
prodno varchar2(5) :='&enter_pno';
begin
select * into prow from prod where pno=prodno;
if( prow.pqty<qord) then
raise qty_is_less_than_required;
end if;
update prod set pqty=pqty-qord where pno=prodno;
commit;
exception
when qty_is_less_than_required then
dbms_output.put_line('qty order is more than qty on hand');
end;

0'
//  

 Ô named exception can be associated with a particular oracle error. This gives the ability to trap
the error rather than via error handlers.

( '

  Pragma.exception_init(exception name,oracle error no.)

0'

   eclare

rec dept10šrowtype;

up_key exception;

Pragma.exception_init(dup_key,-1);

Begin

rec.deptno:=&deptno;

rec.dname:=&dname;

Insert into dept10 values(drec.deptno,drec.dname);

Exception

When dup_key then

opl(͚deptno already exists͛);

When others then

opl(sqlerrm);

End;
 
/  /


  This is used for assigning oracle error numbers to user defined messages.

( 'raise_application_error(error number,͛error message͛);

3Y Error number should be within -20000 to +20000.


3Y Error message can be upto 512 char long.

c  


 Package is defined as collection of procedures, functions, exceptions, cursors related to a


specific application. package in hard terms known as a  
.

Package has two parts in it.

1.Package specification.

2.Package body.

c  

 

It contains the declaration of procedures, functions, cursors, exceptions.

( ' create or replace package <package name> is

eclaration of exceptions

eclaration of procedures

eclaration of cursors

eclaration of functions

End;

c  
! (

It contains the definitions or the executable statements of the procedures,functions,


cursors and exceptions which are declared in the package specification.

( 'create or replace package body <package name> is

efinition of procedure

efinition of function

efinition of exception
efinition of cursor

End;

^
 +The package name should be same in both package specification and package body.

,Number of arguments and type of arguments must be same in package specification


and body for the procedures and functions.

 

To execute the procedure of a package:

Sql>@filename.sql

Sql> exec packagename.procedurename(arg values)

To exxecute the function of a package:

Sql>select packagename.functionname(arg values) from dual;

0'

c  

 

 Create or replace package bankpack is

Negativebalance exception;

Minbalance exception;

Cursor c1(no number) is select * from bank where accno=no;

Procedure accopen(no number,name varchar2(20),opendate date,opamount number);

Function withdraw(no number,tamt number) return number;

Procedure transaction(no number,trtype char,tamt number);

Procedure closeacc(no number);

Procedure translist(no number);

End;

c  
! (

 Create or replace package bogy bankpack is

Procedure accopen(no number,namevarchar2(20),opendate date,oamt number) is


Begin

If oamt<500 then

Raise minbal;

End if;

Insert into bank values(no,name,odate,oamt)

Exception

When minbal then

atabase_output.put_line(͚minimum balance should be >500͛);

End;

Function deposit(no number,tamt number)

Return number is

Ômt number;

Begin

Select openamt into amt from bank

where accno=no;

return amt+tamt;

end;

Function withdraw(no number,tamt number)

Return number is

Ômt number

Begin

Select openamt into amt from bank

Where accno=no;
If amt-500<tamt then

Raise negativebal;

Else

Return amt-tamt;

End if;

Exception

When negativebal then

opl(͚insuffecient amount in acc͛);

Return ;

End;

Procedure transaction (no number,trtype char,tamt number) is

Cb number;

Begin

If trtypein(͚w͛,͛W͛) then

Cb:=withdraw(no,tamt);

Else

Cb:=deposit(no,tamt);

End if;

Insert into banktran values(no,trtype,tamt,cb)

Update bank set opamount=cb where accno=no;

End;

Procedure closeacc(no number) is

Begin
elete from banktran where accno=no;

End;

Procedure translist(no number)

Is

Begin

For I in c1(no) loop

opl(i.accno||͛ ͚||i.trtype||͛ ͚||i.tamt||͛ ͚||i.cbal);

End loop;

End;

End;

   


+ eclare

No number:=&no;

Name varchar2(10);

Opendate date:=͛&opdate͛;

Opamt:=͛&opamt͛;

Begin

Bankpack.accopen(no,name,opdate,opamt);

opl(͚acc open͛);

End;

, declare
No number:=&no;

Ttype char:=͛&ttype͛;

Tamt number:=&tamt;

Ch char:=͛&tr-trlist-c1͛;

Begin

If ch=͛1͛ then

Bankpack.tramsaction(no,ttype,tamt);

opl(͚transaction completed͛);

Elsif ch=͛2͛ then

opl(͚no͛);

Else

Bankpack.closeacc(no);

opl(͚acc closed͛);

Endif;

End;

#


 Ô trigger is stored procedure which is executed on a table whenever a ML statement is issued
on that table. When an event occurs trigger fires.

 0  


1.Y Ôutomatic generation of data.


2.Y To enforce complex intigrity constraints eg: sysdate.
3.Y To maintain replicate tables.
4.Y To enforce complex authorizations.
5.Y For audit checks.

Ôtrigger consists of three parts.


1.Trigger statement.
2.Trigger body.
3.Trigger condition.
Note: select statement is not defined for triggers. That means 
 
)


statement.

( '
Create or replace trigger <trigger name> <before/after><insert/update/delete> on
<table name> [for each row]
[when condition]
eclare
eclarations
Begin
Executable statements;
End;
/

To select the trigger:

Sql>Select user_triggers where table_name=͛<table name>͛;

Sql>select trigger_name,trigger_type from user_triggers where


table_name=͛<tablename>͛;

)
0
#


 Fires for each row of the table.

( '

  Create or replace trigger trig1

before insert or update or delete on bank for each row

begin

dopl(͚row level trigger fired͛);

end;
 


0
#


 ( '

  Create or replace trigger trig2 before insert or update or delete on bank

Begin

opl(͚statement level trigger fired͛);

End;

^
 if u have both statement level trigger as well as row level trigger which are after then
the statement level trigger fires first.

 If it is before then the row level trigger fires first.

   

   !
 !  


 Create or replace trigger trig3 before insert on bank for each row

eclare

Ô number;

Begin

Select max(accno) into Ô from bank;

:new.accno:=Ô+100;

End;

Note: ^
) statement is used to refer the new values of an insert or replace statement.

% statement is used to refer the existing data of the table.

 ( 
 #


  Create or replace trigger trig4 after insert or update on bank for each row

Begin

If :new.opdate>sysdate then
Raise application_error(-20010,͛opening date should always be less than or
equal to the sysdate͛);

End if;

End;

#
  

 
 !


 /*to store the details of the acc number which is deleted from the bank table */

Create or replace trigger trig5before delete on bank for each row

Begin

Insert into closerec values(:old.accno,:old.accname,:old.opendate,:old.opamt);

opl(͚deleted acc. details are stored in another table͛);

End;

   


  Create or replace trigger trig6 after insert or update or delete on bank for each row

eclare

U varchar2(10);

Begin

Select user into u from dual;

If inserting then

Insert into audit1


values(u,͛inserting͛,to_date(to_char(sysdate,͛hh:mi:ss͛),͛hh:mi:ss͛));

Elsif deleting then

Insert into audit1


values(u,͛deleting͛,to_date(to_char(sysdate,͛hh:mi:ss͛),͛hh:mi:ss͛));

End if;

End;
/

"  



 When trigger statement and trigger action both are on the same table then a mutate table error
occcurs and that table can be called as mutate table.

Create or replace trigger trig7 before update on emp10 for each row

Begin

Update emp10 set sal=sal+500

Where empno=7788;

End;

&



It is used to manipulate the complex view.

Create or replace trigger trig8 instead of insert on compview for each row

Begin

Insert into dept10(deptno,dname) values (:new.deptno,:new.dname);

Insert iinto emp10(empno,ename,sal) values(:new.empno,:new.ename,:new.sal);

opl(͚complex view is updated using instead of trigger͛);

End;

You might also like