40
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

RDBMS

Embed Size (px)

Citation preview

Page 1: RDBMS

Practical : Basic Input/output Statements in PL\SQL

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

DECLAREp number(9,2) ;n number(9,2) ;r number(9,2) ;si number(9,2) := 0;ci number(9,2) := 0;

BEGINp := &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: 100old 15: p := &principal_amount;new 15: p := 100;Enter value for no_of_years: 3old 17: n := &no_of_years;new 17: n := 3;Enter value for rate_of_interest: 9old 19: r := &rate_of_interest;new 19: r := 9;simple interset =27

compound interset =129.5

Page 2: RDBMS

Practical : Control Statements – If-else statements

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

DECLAREl number;b number;ar number;pr number;

BEGINl := &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: 3old 13: l := &l;new 13: l := 3;Enter value for b: 5old 15: b := &b;new 15: b := 5;

the area iS < its perimeter area = 15 perimeter = 16

Page 3: RDBMS

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

DECLAREnum number(10);

BEGINnum:=&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

10 IS EVEN NUMBER

ENTER VALUE FOR NUM :- 15

15 IS ODD NUMBER

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 4: RDBMS

/* PROGRAM TO FIND LARGEST OF 3 NUMBERS */

DECLAREa number(5);b number(5);c number(5);

BEGINa:=&a;b:=&b;c:=&c;if a>b then

if a>c thendbms_output.put_line('A IS GREATER');

elsedbms_output.put_line('C IS GREATER');

end if;else

if b>c thendbms_output.put_line('B IS GREATER');

elsedbms_output.put_line('C IS GREATER');

end if;end if;

END;

OUTPUT

ENTER VALUE FOR a :- 10

ENTER VALUE FOR b :- 15

ENTER VALUE FOR c :- 25

C IS GREATER

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 5: RDBMS

/* PROGRAM TO CHANGE NUMBER INTO WORDS */

DECLAREa number;t varchar2(10);

BEGINa :=&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: 4old 9: a :=&a;new 9: a :=4;

4 = four

Page 6: RDBMS

Practical : Control Statements – Loops – while loop

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

DECLAREpi constant number(4,2):=3.14;rad number(5);area number(14,2);

BEGINrad:=3;while rad<=7loop

area:=pi*rad*rad;insert into areasvalues(rad,area);rad:=rad+1;

end loop;

END;

OUTPUT

SELECT * FROM AREAS;

RAD AREA

3 28.264 50.245 78.56 113.047 153.86

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 7: RDBMS

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

DECLAREN number ;S NUMBER :=0;R NUMBER;

BEGINn:=&N;WHILE N<>0 LOOP

R := MOD(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 : 2545THE SUM OF THE DIGITS = 16

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 8: RDBMS

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

DECLAREa number(5):=0;b number(5):=1;c number(5):=0;

BEGINdbms_output.put_line (' FIBONACCI SERIES UPTO 10 NUMBERS ARE');dbms_output.put_line (a);dbms_output.put_line (b);for m in 1..10loop

c:=a+b;dbms_output.put_line(c);a:=b;b:=c;

end loop;

END;

OUTPUT

FIBONACCI SERIES UPTO 10 NUMBERS ARE

0112358132134

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 9: RDBMS

/* PROGRAM TO FIND THE FACTORIAL OF NUMBER */

DECLAREfact number(15):=1; n number(10);

BEGINn:=&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 :- 10

FACTORIAL OF 10 IS 3628800

ENTER VALUE FOR N :- 5

FACTORIAL OF 5 IS 120

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 10: RDBMS

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

DECLAREn number(5);p number(15);

BEGINn:=&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

6 * 1 = 66 * 2 = 126 * 3 = 186 * 4 = 246 * 5 = 306 * 6 = 366 * 7 = 426 * 8 = 486 * 9 = 546 * 10 = 60

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 11: RDBMS

/* 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 :- 12345

THE GIVEN NUMBER IS 12345

THE REVERSE OF NUMBER IS 54321

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 12: RDBMS

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

DECLAREn number;sum number:=0;

BEGINn:=&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 :- 6

1 2 3 4 5 6

SUM OF FIRST 6 NATURAL NUMBERS IS 21

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 13: RDBMS

/* PROGRAM TO PRINT PYRAMID OF STARS */

** * *

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

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

DECLAREi number(1):=0;j number(1):=0;k number(1):=0;

BEGINfor i in 0 .. 6 loop

for j in 1 .. (6-i) loopdbms_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.

Page 14: RDBMS

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.

Page 15: RDBMS

The status of the cursor for each of these attributes are defined in the below table. 

Attributes Return Value Example

%FOUND The return value is TRUE, if the DML statements like INSERT, DELETE and UPDATE affect at least one row and if SELECT ….INTO statement return at least one row.

SQL%FOUND

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 statements like INSERT, DELETE and UPDATE at least one row and if SELECT ….INTO statement return at least one row.

SQL%NOTFOUND

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 DML operations INSERT, DELETE, UPDATE, SELECT

SQL%ROWCOUNT

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.

Page 16: RDBMS

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 employee’s 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.

Page 17: RDBMS

/* PROGRAM TO USE OF EXPLICIT CURSOR*/-- display empno, ename, job of employees whose deptno is 30

DECLAREcursor Deepak is select empno, ename, job from emp where deptno=30;var Deepak%rowtype;

BEGINOpen Deepak;loopfetch 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 ALLENEmployee number is 7499 Employee job is SALESMANEmployee name is WARDEmployee number is 7521 Employee job is SALESMANEmployee name is MARTINEmployee number is 7654Employee job is SALESMANEmployee name is BLAKEEmployee number is 7698Employee job is MANAGEREmployee name is TURNEREmployee number is 7844Employee job is SALESMANEmployee name is JAMESEmployee number is 7900Employee job is CLERK

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 18: RDBMS

/* PROGRAM TO USE OF CURSORS*/

-- update the salary of each employee by 20% and insert a record in the -- emprise table.

DECLAREcursor c_raise is select ename, sal from emp;name char(7);

r number(7);

BEGINopen c_raise;loopfetch 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 800ALLEN 1600WARD 1250JONES 2975MARTIN 1250BLAKE 2850CLARK 2450SCOTT 3000KING 5000TURNER 1500ADAMS 1100JAMES 950FORD 3000MILLER1300MILLER1300

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 19: RDBMS

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 isProcedure_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) ISTot number := 0;BEGINFOR I IN 1 .. aLOOPTot := tot + I;END LOOP;Dbms_output.put_line (‘the sum of series is ‘|| tot);END;

Page 20: RDBMS

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) ISBEGIN 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.

Page 21: RDBMS

/* 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.

Page 22: RDBMS

/* PROGRAM TO CREATE A PROCEDURE TO PERFORM ADD, SUBTRACT, MULTIPY AND DIVISION OF TWO NUMBERS */

DECLAREa 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) ISBEGIN

c:=a+b; d:=a-b;e:=a*b; f:=a/b;

END;

BEGINa:=&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 :- 8Enter value for b :- 2

Addition 10Subtraction 6Multiplication 16

Division 4

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 23: RDBMS

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 isCREATE [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 ISarea number;rad number;BEGINrad := 3;While rad <= 7LOOParea := 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.

Page 24: RDBMS

Difference between procedure and function

PROCEDURE FUNCTION

A procedure is subprogram that accept A function is subprogram that Parameters, perform an action and return accepts parameters, compute a The values to calling PL/SQL block. Value & return that value to the caller.

It returns no value. It returns only one value.

It cannot return a value as direct output. It returns value as direct output Of function call.

We use procedure to perform an action. We use function to compute a value.

Page 25: RDBMS

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

Page 26: RDBMS

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

Description

Builtin 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 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.

Build-Your-Own (BYO)

The very best kind of package: the one you build yourself, or is built by your application development team.

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 ];

Page 27: RDBMS

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.

Page 28: RDBMS

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

create or replace package Deepak asprocedure insert (eno number, name varchar2(10),job varchar2(5),sal number);

create or replace package body Deepak isprocedure insert (eno number, name varchar2(10),job varchar2(5), sal number) asbegin

insert into emp (empno,ename,job,sal)values(eno,name,job,sal);end insert;end Deepak;

DECLAREeno number;name varchar2(10);job varchar2(5);sal number;

BEGINeno:=&eno; name:=&name;job:=&job; sal:=&sal;Deepak.insert (eno, name, job, sal);

END;

OUTPUT

PACKAGE CREATED

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 29: RDBMS

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

Page 30: RDBMS

/* PROGRAM TO CREATE A TRIGGER FOR EMP TABLE WHICH MAKES ENTRY IN ENAME COLUMN IN UPPERCASE */

create or replace trigger Deepakbefore insert or update of ename on empfor each row

BEGIN:new.ename:=upper(:new.ename);dbms_output.put_line(:new.ename);

END;

OUTPUT

TRIGGER CREATED

PL/SQL PROCEDURE SUCESSFULLY COMPLETED.

Page 31: RDBMS

/* 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 t2after update or delete of ename on empfor each rowBEGIN

dbms_output.put_line('old name:|| : old.dname');dbms_output.put_line('new name:|| : new.dname');

END;

OUTPUTSQL> set serveroutput onSQL> ed functionSQL> @ xyz.txt 8 /Trigger created.SQL> update emp set ename ='marks' where empno=7900 2 /old name:|| : old.dnamenew name:|| : new.dname

1 row updated.