You are on page 1of 30

Practical : Basic Input/output Statements in PL\SQL

/* PROGRAM TO FIND THE SIMPLE INTEREST AND COMPOUND INTEREST */


DECLARE p number(9,2) ; n number(9,2) ; r number(9,2) ; si number(9,2) := 0; ci number(9,2) := 0; BEGIN p := &principal_amount; n := &no_of_years; r := &rate_of_interest; si := p*n*r/100; ci := p*(1+r/100)**n; dbms_output.put_line('simple interset =' ||si); dbms_output.put_line('compound interset =' ||ci); END;

OUTPUT Enter value for principal_amount: 100 old 15: p := &principal_amount; new 15: p := 100; Enter value for no_of_years: 3 old 17: n := &no_of_years; new 17: n := 3; Enter value for rate_of_interest: 9 old 19: r := &rate_of_interest; new 19: r := 9; simple interset =27 compound interset =129.5

Practical : Control Statements

If-else statements

/* PROGRAM TO CHECK IF AREA IS GREATER THAN PERIMETER USING IF ELSE */


DECLARE l number; b number; ar number; pr number; BEGIN l := &l; b := &b; ar := l*b; pr := 2*(l+b); if ar > pr then dbms_output.put_line('the area iS > its perimeter'|| 'area = '||ar||'perimeter = '||pr); else dbms_output.put_line('the area iS < its perimeter'|| ' area = '||ar||' perimeter = '||pr); end if; END;

OUTPUT Enter value for l: 3 old 13: l := &l; new 13: l := 3; Enter value for b: 5 old 15: b := &b; new 15: b := 5; the area iS < its perimeter area = 15 perimeter = 16

/* PROGRAM TO CHECK WHETHER NUMBER IS ODD OR EVEN */


DECLARE num number(10); BEGIN num:=&num; if(mod(num,2)=0)then dbms_output.put_line(num || 'is even number'); else dbms_output.put_line(num || 'is odd number'); end if; END; OUTPUT ENTER VALUE FOR NUM :10 IS EVEN NUMBER ENTER VALUE FOR NUM :15 IS ODD NUMBER PL/SQL PROCEDURE SUCESSFULLY COMPLETED. 15 10

/* PROGRAM TO FIND LARGEST OF 3 NUMBERS */


DECLARE a number(5); b number(5); c number(5); BEGIN a:=&a; b:=&b; c:=&c; if a>b then if a>c then dbms_output.put_line('A IS GREATER'); else dbms_output.put_line('C IS GREATER'); end if; else if b>c then dbms_output.put_line('B IS GREATER'); else dbms_output.put_line('C IS GREATER'); end if; end if; END; OUTPUT ENTER VALUE FOR a :ENTER VALUE FOR b :ENTER VALUE FOR c :C IS GREATER PL/SQL PROCEDURE SUCESSFULLY COMPLETED. 10 15 25

/* PROGRAM TO CHANGE NUMBER INTO WORDS */


DECLARE a number; t varchar2(10); BEGIN a :=&a; if a=1 then t := 'one'; elsif a=2 then t := 'two'; elsif a= 3 then t := 'three'; elsif a=4 then t := 'four'; elsif a=5 then t := 'five'; elsif a=6 then t := 'six'; elsif a=7 then t := 'seven'; elsif a=8 then t := 'eight'; elsif a=9 then t := 'nine'; else t := 'zero'; end if; dbms_output.put_line(a || ' = ' || t); END;

OUTPUT Enter value for a: 4 old 9: a :=&a; new 9: a :=4; 4 = four

Practical : Control Statements

Loops

while loop

/* PROGRAM TO FIND THE AREA OF CIRCLE USING WHILE LOOP */


DECLARE pi constant number(4,2):=3.14; rad number(5); area number(14,2); BEGIN rad:=3; while rad<=7 loop area:=pi*rad*rad; insert into areas values(rad,area); rad:=rad+1; end loop; END; OUTPUT SELECT * FROM AREAS; RAD 3 4 5 6 7 AREA 28.26 50.24 78.5 113.04 153.86

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO FIND THE SUM OF DIGITS OF A NUMBER */


DECLARE N number ; S NUMBER :=0; R NUMBER; BEGIN n:=&N; WHILE N<>0 LOOP R := M OD(N,10); S := S + R; N := TRUNC(N/10); end loop; dbms_output.put_line('THE SUM OF THE DIGITS = ' || S); END;

OUTPUT ENTER VALUE FOR N : 2545 THE SUM OF THE DIGITS = 16 PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO PRINT THE FIBONACCI SERIES USING FOR LOOP */


DECLARE a number(5):=0; b number(5):=1; c number(5):=0; BEGIN dbms_output.put_line (' FIBONACCI SERIES UPTO 10 NUMBERS ARE'); dbms_output.put_line (a); dbms_output.put_line (b); for m in 1..10 loop c:=a+b; dbms_output.put_line(c); a:=b; b:=c; end loop; END; OUTPUT FIBONACCI SERIES UPTO 10 NUMBERS ARE 0 1 1 2 3 5 8 13 21 34 PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO FIND THE FACTORIAL OF NUMBER */


DECLARE fact number(15):=1; n number(10); BEGIN n:=&n; for i in reverse 1..n loop fact:=fact*i; End loop; Dbms_output.put_line(FACTORIAL OF ||n || IS ||fact); END; OUTPUT ENTER VALUE FOR N :FACTORIAL OF 10 IS ENTER VALUE FOR N :FACTORIAL OF 5 IS 10 3628800 5 120

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO PRINT THE TABLE OF ANY NUMBER */


DECLARE n number(5); p number(15); BEGIN n:=&n; for i in 1..10 loop p:=i*n; dbms_output.put_line (n||' *' ||i||'='||p); end loop; END;

OUTPUT ENTER VALUE FOR N :6*1 =6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 6 * 7 = 42 6 * 8 = 48 6 * 9 = 54 6 * 10 = 60 PL/SQL PROCEDURE SUCESSFULLY COMPLETED. 6

/* PROGRAM TO PRINT THE REVERSE OF ENTERED NUMBER */


DECLARE num varchar2(10); len number(20); rev varchar2(10); BEGIN num:=&num; len:=length(num); for i in reverse 1..len loop rev:=rev ||substr(num,i,1); end loop; dbms_output.put_line('the given number is'||num); dbms_output.put_line('the reverse of number is'||rev); END; OUTPUT ENTER VALUE FOR NUM :THE GIVEN NUMBER IS THE REVERSE OF NUMBER IS 12345 12345 54321

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO FIND SUM OF FIRST N NATURAL NUMBERS */


DECLARE n number; sum number:=0; BEGIN n:=&n; for i in 1..n loop sum:=sum+i; dbms_output.put_line (i); end loop; dbms_output.put_line ('SUM OF FIRST ' || n || 'NATURAL NUMBERS IS ' || sum); END; OUTPUT ENTER VALUE FOR N :1 2 6 3 4 5 6

SUM OF FIRST 6 NATURAL NUMBERS IS 21


PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO PRINT PYRAMID OF STARS */ * *** **** **** **** ****

* ** *** ****
DECLARE i number(1):=0; j number(1):=0; k number(1):=0; BEGIN for i in 0 .. 6 loop for j in 1 .. (6-i) loop dbms_output.put (' '); end loop; for k in i .. (3*i) loop dbms_output.put ('*'); end loop; dbms_output.put_line (' '); end loop; END; OUTPUT

* ** *** ****

* *** ****** ******** ********** *************


PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Practical : Implementation of CURSORS, Types and their Attributes in PL\SQL


A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

There are two types of cursors in PL/SQL:


Implicit cursors: These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. Explicit cursors: They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row. Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

Implicit Cursors:
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements. Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.

The status of the cursor for each of these attributes are defined in the below table. Attributes %FOUND Return Value Example The return value is TRUE, if the DML SQL%FOUND statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT .INTO statement return at least one row. The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE do not affect row and if SELECT.INTO statement do not return a row. %NOTFOUND The return value is FALSE, if DML SQL%NOTFOUND statements like INSERT, DELETE and UPDATE at least one row and if SELECT .INTO statement return at least one row. The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect even one row and if SELECT .INTO statement does not return a row. %ROWCOUNT Return the number of rows affected by the SQL%ROWCOUNT DML operations INSERT, DELETE, UPDATE, SELECT

Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor.
The General Syntax for creating a cursor is as given below: CURSOR cursor_name IS select_statement;

cursor_name A suitable name for the cursor. select_statement A select query which returns multiple rows.

There are four steps in using an Explicit Cursor.


DECLARE the cursor in the declaration section. OPEN the cursor in the Execution Section. FETCH the data from cursor into PL/SQL variables or records in the Execution Section.

CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

1) Declaring a Cursor in the Declaration Section:


DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000;

In the above example we are creating a cursor emp_cur on a query which returns the records of all the employees with salary greater than 5000. Here emp_tbl in the table which contains records of all the employees. 2) Accessing the records in the cursor: Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program.

How to access an Explicit Cursor? These are the three steps in accessing the cursor. 1) Open the cursor. 2) Fetch the records in the cursor one at a time. 3) Close the cursor. In the above PL/SQL Block, the salaries of all the employees in the employee table are updated. If none of the employees salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in employee table.

/* PROGRAM TO USE OF EXPLICIT CURSOR*/


-- display empno, ename, job of employees whose deptno is 30
DECLARE cursor Deepak is select empno, ename, job from emp where deptno=30; var Deepak%rowtype; BEGIN Open Deepak; loop fetch Deepak into var; exit when Deepak%notfound; dbms_output.put_line(employee name is || var.ename); dbms_output.put_line(employee number is || var.empno); dbms_output.put_line(employee job is || var.job); end loop; close Deepak; END;

OUTPUT
Employee name is ALLEN Employee number is 7499 Employee job is SALESMAN Employee name is WARD Employee number is 7521 Employee job is SALESMAN Employee name is MARTIN Employee number is 7654 Employee job is SALESMAN Employee name is BLAKE Employee number is 7698 Employee job is MANAGER Employee name is TURNER Employee number is 7844 Employee job is SALESMAN Employee name is JAMES Employee number is 7900 Employee job is CLERK PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO USE OF CURSORS*/


-- update the salary of each employee by 20% and insert a record in the -- emprise table.
DECLARE cursor c_raise is select ename, sal from emp; name char(7); r number(7); BEGIN open c_raise; loop fetch c_raise into name,r; r:=r+20/100; insert into emprise values(name,r); exit when c_raise%notfound; end loop; close c_raise; END;

OUTPUT Select * from emprise; NAME R

SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN BLAKE 2850 CLARK 2450 SCOTT 3000 KING TURNER ADAMS 1100 JAMES 950 FORD MILLER 1300 MILLER 1300

1250

5000 1500 3000

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Practical: Implementation of Subprograms, Functions and Procedures in PL|SQL and differences between Function and Procedure.

Subprograms are named PL/SQL blocks that can take parameters and be invoked.
PL/SQL has two types of subprograms called procedures and functions. Generally, you use a procedure to perform an action and a function to compute a value.
Like unnamed or anonymous PL/SQL blocks, subprograms have a declarative part, an executable part, and an optional exception-handling part. The declarative part contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These items are local and cease to exist when you exit the subprogram. The executable part contains statements that assign values, control execution, and manipulate Oracle data. The exception-handling part contains exception handlers, which deal with exceptions raised during execution. CREATE [OR REPLACE] PROCEDURE procedure_name [{arguments} [{IN | OUT | IN OUT}] Argument type.] {IS | AS} PROCEDURE BODY;

Two types of procedures are Local procedure Stored procedure A procedure is called as a PL/SQL statement. A procedure can be called from any PL/SQL program by giving their names followed by parameters. Syntax is Procedure_name(arguments); Example to create a procedure to calculate the sum of series (1+2+3+4+ .n) CREATE OR REPLACE PROCEDURE Deepak(a in number) IS Tot number := 0; BEGIN FOR I IN 1 .. a LOOP Tot := tot + I; END LOOP; Dbms_output.put_line (the sum of series is || tot); END;

A procedure is a subprogram that performs a specific action. You write procedures using the syntax: [CREATE [OR REPLACE]] PROCEDURE procedure_name[(parameter[, parameter]...)] [AUTHID {DEFINER | CURRENT_USER}] {IS | AS} [PRAGMA AUTONOMOUS_TRANSACTION;] [local declarations] BEGIN executable statements [EXCEPTION exception handlers] END [name];

Advantages of Subprograms
Subprograms provide extensibility; that is, they let you tailor the PL/SQL language to suit your needs. For example, if you need a procedure that creates new departments, you can easily write one, as follows:
PROCEDURE create_dept (new_dname VARCHAR2, new_loc VARCHAR2) IS BEGIN INSERT INTO dept VALUES (deptno_seq.NEXTVAL, new_dname, new_loc); END create_dept;

Subprograms also provide modularity; that is, they let you break a program down into manageable, well-defined modules. This supports top-down design and the stepwise refinement approach to problem solving. In addition, subprograms promote reusability and maintainability. Once validated, a subprogram can be used with confidence in any number of applications. If its definition changes, only the subprogram is affected. This simplifies maintenance. Finally, subprograms aid abstraction, the mental process of deriving a universal from particulars. To use subprograms, you must know what they do, not how they work. Therefore, you can design applications from the top down without worrying about implementation details. Dummy subprograms (stubs) allow you to defer the definition of procedures and functions until you test and debug the main program.

/* PROGRAM TO FIND FACTORIAL OF NUMBER USING PROCEDURES*/


CREATE OR REPLACE PROCEDURE fact (n number) as f number:=n; fac number; BEGIN if (f=0) then fac:=1; else fac:=1; while (f>0) loop fac:=fac*f; f:=f-1; end loop; end if; dbms_output.put_line('factorial :'||fac); END FACT;

OUTPUT Exec fact(5); Factorial : 120 Exec fact(10); Factorial : 3628800 PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO CREATE A PROCEDURE TO PERFORM ADD, SUBTRACT, MULTIPY AND DIVISION OF TWO NUMBERS */ DECLARE a number; b number; c number; d number; e number; f number; Procedure menu (a in number, b in number, c out number, d out number, e out number, f out number) IS BEGIN c:=a+b; d:=a-b; e:=a*b; f:=a/b; END; BEGIN a:=&a; b:=&b; menu(a,b,c,d,e,f); dbms_output.put_line('Addition'|| c); dbms_output.put_line('Subtraction'||d ); dbms_output.put_line('Multiplication'|| e ); dbms_output.put_line('Division'|| f ); END; OUTPUT Enter value for a :Enter value for b :Addition 10 Subtraction 6 Multiplication 16 Division 4 PL/SQL PROCEDURE SUCESSFULLY COMPLETED. 8 2

FUNCTION
Function is a type of subprogram that can accept parameters, perform an action and return the values to the calling PL/SQL block. Functions can be called by blocks, other function & procedures. A function must have a return clause. A function is a subprogram that
computes a value. Functions and procedures are structured alike, except that functions have a RETURN clause. A function can be called in the calling block in the following way is

Variable:=function_name (function variables); Syntax to create a function is CREATE [OR REPLACE] FUNCTION function_name [{arguments} [{IN | OUT | IN OUT}] RETURN return_type.] {IS | AS} FUNCTION BODY; RETURN expression; Example to create a function to calculate area of circle CREATE OR REPLACE FUNCTION Deepak(pi number:=3.14) RETURN number IS area number; rad number; BEGIN rad := 3; While rad <= 7 LOOP area := pi * power (rad,2); rad := rad + 1; RETURN area; END LOOP; END; Actual parameters : List of variables or expressions referenced in the parameter list of a subprogram call is called as actual parameters. Formal parameters : List of variables declared in the subprogram specified and Referenced in the subprogram body is called as actual parameters.

Difference between procedure and function


PROCEDURE
A procedure is subprogram that accept Parameters, perform an action and return The values to calling PL/SQL block. It returns no value. It cannot return a value as direct output. Of function call. We use procedure to perform an action.

FUNCTION
A function is subprogram that accepts parameters, compute a Value & return that value to the caller. It returns only one value. It returns value as direct output We use function to compute a value.

Practical : Implementation of PACKAGES in PL\SQL.


A package is a schema object that groups logically related PL/SQL types, items, and subprograms. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification (spec for short) is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the spec. As Figure shows, you can think of the spec as an operational interface and of the body as a "black box." You can debug, enhance, or replace a package body without changing the interface (package spec) to the package.
Figure 9-1 Package Interface

A package is a collection of PL/SQL elements that are "packaged" or grouped together within a special BEGIN-END syntax, a kind of "meta-block." Here is a partial list of the kinds of elements you can place in a package:

Cursors Variables (scalars, records, tables, etc.) and constants Exception names and pragmas for associating an error number with an exception PL/SQL table and record TYPE statements Procedures and functions

Packages are among the least understood and most underutilized features of PL/SQL. That's a shame because the package structure is also one of the most useful constructs for building well-designed PL/SQL-based applications. Packages provide a structure to organize your modules and other PL/SQL elements. They encourage proper structured programming techniques in an environment that often befuddles the implementation of structured programming. When you place a program unit into a package you automatically create a

"context" for that program. By collecting related PL/SQL elements in a package, you express that relationship in the very structure of the code itself. Packages are often called "the poor man's objects" because they support some, but not all, object-oriented rules. The PL/SQL package is a deceptively simple, yet powerful construct. It consists of up to two distinct parts: the specification and the body.

The package specification, which defines the public interface (API) of the package: those elements that can be referenced outside of the package. The package body, which contains the implementation of the package and elements of the package you want to keep hidden from view.

Types and Layers of Packages?


Although any PL/SQL package must have the same structure and follow the same rules, there are different types of packages that will play different roles in your application. Types of Package Builtin Description A builtin package is provided to you by Oracle Corporation, built right into the PL/SQL language as installed. (A builtin package could reside in the database as stored code or could instead be imbedded in a client tool, such as Oracle Developer/2000.) Prebuilt packages are libraries of packages that are built by third parties or other developers that are installed in and used by your PL/SQL environment. The very best kind of package: the one you build yourself, or is built by your application development team.

Prebuilt Build-YourOwn (BYO)

Figure 2 shows how these different types of packages interact as layers of PL/SQL code and packages that are available to you. We describe the types further in "Types of Packages" later in this chapter.

Syntax for a package specification:


PACKAGE package_name IS [ declarations of variables and types ] [ headers of cursors ] [ headers of procedures and functions ] END [ package_name ];

You can declare variables and include headers of both cursors and modules (and only the specifications). You must have at least one declaration or header statement in the package specification.

/* PROGRAM TO CREATE A PACKAGE TO INSERT VALUES OF EMPLOYEE */


create or replace package Deepak as procedure insert (eno number, name varchar2(10),job varchar2(5),sal number); create or replace package body Deepak is procedure insert (eno number, name varchar2(10),job varchar2(5), sal number) as begin insert into emp (empno,ename,job,sal)values(eno,name,job,sal); end insert; end Deepak; DECLARE eno number; name varchar2(10); job varchar2(5); sal number; BEGIN eno:=&eno; name:=&name; job:=&job; sal:=&sal; Deepak.insert (eno, name, job, sal); END;

OUTPUT PACKAGE CREATED PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Practical : Implementation of Triggers in PL\SQL


A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. The oracle engine allows the definition of procedures that are implicity executed, when an Insert , update or delete is issued against a table from SQL*PLUS or through an application these procedures are called Database Triggers.

Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered. 1) Row level trigger - An event is triggered for each row upated, inserted or deleted. A triggers is fire each time in the row in the table is affected by triggering statement. 2) Statement level trigger - An event is triggered for each sql statement executed. A statement triggers is fire once on the behalf of the triggering statement, independent on the numbers of the rows effected.

Syntax of Triggers

The Syntax for creating a trigger is:


CREATE [OR REPLACE ] TRIGGER {BEFORE | AFTER | INSTEAD OF {INSERT [OR] | UPDATE [OR] | [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS [FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END; trigger_name } DELETE} n]

/* PROGRAM TO CREATE A TRIGGER FOR EMP TABLE WHICH MAKES ENTRY IN ENAME COLUMN IN UPPERCASE */
create or replace trigger Deepak before insert or update of ename on emp for each row BEGIN :new.ename:=upper(:new.ename); dbms_output.put_line(:new.ename); END; OUTPUT TRIGGER CREATED PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

/* PROGRAM TO CREATE A TRIGGER ON THE EMP TABLE WHICH SHOW THE OLD AS WELL AS NEW VALUE OF THE EMPLOYEE NAME AFTER ANY UPDATION ON ENAME */
create or replace trigger t2 after update or delete of ename on emp for each row BEGIN dbms_output.put_line('old name:|| : old.dname'); dbms_output.put_line('new name:|| : new.dname'); END;

OUTPUT SQL> set serveroutput on SQL> ed function SQL> @ xyz.txt 8 / Trigger created. SQL> update emp set ename ='marks' where empno=7900 2 / old name:|| : old.dname new name:|| : new.dname 1 row updated.

You might also like