Top Banner
COURSE MATERAL- PL-SQL COURSE MATERAL For PL-SQL 1 COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd
97
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PL

COURSE MATERAL- PL-SQL

COURSE MATERAL

For

PL-SQL

1

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 2: PL

COURSE MATERAL- PL-SQL

It is advanced or superset of SQL.

It deals with programming.

It is called third generation programming language, since it contains all the standard rules of programming.

Difference between SQL and PL/sQL is, SQL is called Non-Procedural language since it deals with only WHAT data to be extracted, whereas PL/SQL is called Procedural language, since it deals with WHAT data to be extracted and HOW it should be displayed.

PL/SQL supports to write a program in 2 ways;

1. Anonymous block programming.

2. Stored block programming.

1. Anonymous block programming : A program which is written in nameless block. This program will be residing in Operating system since it is created in .sql file.

2. Stored block programming : A program which is written in named block and resides in database server. It includes Stored procedures, Stored functions, Stored packages and Triggers.

Advantages of PL/SQL:

1. Supports for SQL : DDL, DML, TCL, DQL, pseudo columns, functions which are used at SQL, the same can be used in PL/SQL.

2. Better performance : At SQL only 1 command is sent for execution to a server whereas at PL/SQL group of commands are stored in the form of a block and can send them for execution at once to a server, by which performance of application gets increases.

3. Portability : The program which is written in PL/SQL on one platform can easily be transfered to the other platform.

4. Tight Integration with SQL: Datatypes used at SQL, the same can be used at PL/SQL. It also provides the new datatype called Composite datatypes which includes 2 datatypes; %TYPE , %ROWTYPE

2

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 3: PL

COURSE MATERAL- PL-SQL

5. Procedural Capabilities : Input/Output statements, IF conditional statements, Looping constructs, GOTO statement etc which are used at programming languages, the same can be used at PL/SQL.

6. Modularity : A large application program can get split into small modules or blocks.

Anonymous block Programming:

This program is created in .sql file and will be available at operating system.

This program consists of 3 blocks;

1. Declaration block

2. Execution block

3. Exception block

1. Declaration block: At this block it allows a user to declare normal variables, constant variables, objects. This block is identified by a keyword called DECLARE.

2. Execution block: At this block it allows a user to write all those statements by which program gets executed. This block is identified by a keyword called BEGIN.

3. Exception block: At this block it allows a user to handle runtime errors. It is identified by a keyword called EXCEPTION.

syntax:

[DECLARE

declaration part;]

BEGIN

exection part;

[EXCEPTION

exception handlers;]

END;

3

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 4: PL

COURSE MATERAL- PL-SQL

/

Datatypes used in PL/SQL program:

1. NUMBER

2. CHAR

3. VARCHAR2

4. DATE

5. BOOLEAN : It is used only in PL/SQL program, which allows a user to store boolean value i.e. TRUE or FALSE.

Output Statement of PL/SQL:

It performs 2 tasks;

1. Displays Messages.

2. Displays Memory Values.

DBMS_OUTPUT.PUT('message'/variable); displays output and control remains on same line.

DBMS_OUTPUT.PUT_LINE('message'/variable); displays output and control gets transfer to new line.

DBMS_OUTPUT is a predefined package.

PUT , PUT_LINE are called predefined procedures;

Points to be remembered before writing a PL/SQL program;

1. Program should be written in ED and should have extension as .sql

Syntax: SQL> ED file_name

2. Before executing a program it is essential that the environment variable SERVEROUTPUT should be set to ON.

SET SERVEROUTPUT ON/OFF : default is OFF

4

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 5: PL

COURSE MATERAL- PL-SQL

3. The program has to be executed with the following procedure;

SQL> @file_name

Write a program illustrating the output statement of PL/SQL?

BEGIN

DBMS_OUTPUT.PUT('WELCOME');

DBMS_OUTPUT.PUT_LINE('THANX');

END;

/

OPERATORS:

SINGLE OR SIMPLE OPERATORS:

+,-,*,/ Arithmetic Operators

>,<,= Relational Operators

. Access Operator

% Composite datatype indicator

MULTIPLE OR COMPOUND SYMBOLS/OPERATORS:

>=,<=,<> != ^= Relational Operators

:= Assignment Operator

|| Concatination Operator

-- Single line comment

/*....*/ Multiple line comment

** Exponentiation Operator

5

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 6: PL

COURSE MATERAL- PL-SQL

<< >> Label Delimiter

.. Range Operator

Declaring Normal Variables:

A variable should be declared before it is used.

A variable can store only 1 value.

If more than 1 value is stored it gives priority to the last value.

Syntax: variable data_type[(size)][:=&var/val];

Write a program to find the sum of 2 constant values?

DECLARE

a NUMBER:=10;

b NUMBER:=39;

c NUMBER;

BEGIN

c:=a+b;

DBMS_OUTPUT.PUT_LINE(c);

DBMS_OUTPUT.PUT_LINE('SUM IS.....'||c);

DBMS_OUTPUT.PUT_LINE('SUM OF '||a||' AND '||b||' IS '||c);

DBMS_OUTPUT.PUT_LINE(a||' + '||b||' = '||c);

DBMS_OUTPUT.PUT_LINE(a+b);

END;

/

6

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 7: PL

COURSE MATERAL- PL-SQL

OUTPUT:

168

SUM IS.....168

SUM OF 76 AND 92 IS 168

76 + 92 = 168

168

Write a program to find the sum of 2 accepted values?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

c NUMBER;

BEGIN

c:=a+b;

DBMS_OUTPUT.PUT_LINE('SUM IS.....'||c);

END;

/

CONSTANT VARIABLES:

A constant variable is declared with a keyword called CONSTANT.

Declaration of constant variables and initialization should be carried out simultaneously. A constant variables cant be modified. Any number of constant variables can be declared in a single program.

Syntax:

variable CONSTANT data_type[(size)]:=value;

7

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 8: PL

COURSE MATERAL- PL-SQL

example:

DECLARE

a CONSTANT NUMBER(3):=89;

BEGIN

DBMS_OUTPUT.PUT_LINE(a);

END;

/

Write a program to find the Area of Circle?

DECLARE

r NUMBER:=&r;

pi CONSTANT NUMBER:=3.14;

aoc NUMBER;

BEGIN

-- aoc:=pi*r*r;

-- aoc:=pi*POWER(r,2);

aoc:=pi*r**2;

DBMS_OUTPUT.PUT_LINE('Area Of Circle Is......'||aoc);

END;

/

IF CONDITIONAL STATEMENTS:

This conditional statement in pl/sql is used to compare the data providing the result on boolean expression i.e. TRUE or FALSE.

8

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 9: PL

COURSE MATERAL- PL-SQL

Oracle supports to work with the following IF conditional statements;

1. Simple If conditional statement

2. IF-ELSE-IF conditional statement

3. Nested IF conditional statement

1. Simple If:

This IF conditional statement allows to write 1 true and 1 false statement or block.

Syntax:

IF condition THEN

true statement;

ELSE

false statement;

END IF;

Write a program to find the biggest of 2 values?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

BEGIN

IF a>b THEN

DBMS_OUTPUT.PUT_LINE('A IS BIG');

ELSE

DBMS_OUTPUT.PUT_LINE('B IS BIG');

9

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 10: PL

COURSE MATERAL- PL-SQL

END IF;

END;

/

Write a program to check whether a given number has perfect square or not?

DECLARE

n NUMBER:=&n;

s NUMBER;

BEGIN

s:=TRUNC(SQRT(n));

IF s*s=n THEN

DBMS_OUTPUT.PUT_LINE('IT HAS A PERFECT SQUARE');

ELSE

DBMS_OUTPUT.PUT_LINE('SORRY');

END IF;

END;

/

2. IF-ELSE-IF conditional statement:

IF condition is followed by the other if condition.

Syntax 1: Syntax 2:

IF condition1 THEN IF condition1 THEN

statements; statements;

10

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 11: PL

COURSE MATERAL- PL-SQL

ELSE ELSIF condition2 THEN

IF condition2 THEN statements;

statements; ELSIF condition3 THEN

ELSE statements;

IF condition3 THEN ELSE

statements; statements;

ELSE END IF;

statements;

END IF;

END IF;

END IF;

Write a program to find the biggest of 2 numbers or display that both are equal?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

BEGIN

IF A=B THEN

DBMS_OUTPUT.PUT_LINE('BOTH ARE EQUAL');

ELSE

IF a>b THEN

DBMS_OUTPUT.PUT_LINE('A IS BIG');

11

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 12: PL

COURSE MATERAL- PL-SQL

ELSE

DBMS_OUTPUT.PUT_LINE('B IS BIG');

END IF;

END IF;

END;

/

Write a program to find the biggest of 3 numbers or display that 3 valeus are equal?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

c NUMBER:=&c;

BEGIN

IF a=b AND b=c THEN

DBMS_OUTPUT.PUT_LINE('3 VALUES ARE EQUAL');

ELSIF a>b AND a>c THEN

DBMS_OUTPUT.PUT_LINE('A IS BIG');

ELSIF b>c THEN

DBMS_OUTPUT.PUT_LINE('B IS BIG');

ELSE

DBMS_OUTPUT.PUT_LINE('C IS BIG');

END IF;

12

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 13: PL

COURSE MATERAL- PL-SQL

END;

/

NESTED IF CONDITIONAL STATEMENT:

IF condition used within an IF condition refers to NESTED IF conditional statement.

Syntax:

IF condition1 THEN

statements;

IF condition2 THEN

statements;

ELSE

statements;

END IF;

ELSE

statements;

END IF;

Write a program to check whether a given number is odd or even only for +VE numbers?

DECLARE

n NUMBER:=&n;

BEGIN

IF n>0 THEN

DBMS_OUTPUT.PUT_LINE('IT IS +vE');

13

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 14: PL

COURSE MATERAL- PL-SQL

IF MOD(n,2)=0 THEN

DBMS_OUTPUT.PUT_LINE('IT IS EVEN');

ELSE

DBMS_OUTPUT.PUT_LINE('IT IS ODD');

END IF;

ELSE

DBMS_OUTPUT.PUT_LINE('IT IS -VE');

END IF;

END;

/

GOTO statement

It is called branching statement, since it supports to transfer the control from 1 part of a program to the other part of a program.

GOTO statement will work based on 2 concepts;

1. Label Assignment

2. Label Definition

Syntax for Label Assignment:

GOTO label_name;

Syntax for Label Definition:

<<label_name>>

statements;

example:

14

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 15: PL

COURSE MATERAL- PL-SQL

BEGIN

DBMS_OUTPUT.PUT_LINE('WELCOME');

GOTO X;

<<Y>>

DBMS_OUTPUT.PUT_LINE('FIVE');

DBMS_OUTPUT.PUT_LINE('SEVEN');

GOTO Z;

<<X>>

DBMS_OUTPUT.PUT_LINE('NINE');

GOTO Y;

<<Z>>

DBMS_OUTPUT.PUT_LINE('THANX');

END;

/

OUTPUT:

WELCOME

NINE

FIVE

SEVEN

THANX

LOOPING CONSTRUCTS

15

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 16: PL

COURSE MATERAL- PL-SQL

LOOP : It is a process of executing 1 or more statements repeatedly until a condition is satisfied.

Oracle supports to work with the following 3 Looping constructs;

1. LOOP ..... EXIT WHEN condition...... END LOOP

2. WHILE loop

3. FOR loop

LOOP....EXIT WHEN condition....END LOOP:

This looping construct will repeat the execution of 1 or more statements only when the given condition is false.

syntax:

LOOP

statements;

EXIT WHEN condition;

statements;

END LOOP;

This looping construct will terminate its working thru EXIT keyword when the given condition becomes true.

Write a program to display 1st five natural numbers using the above looping construct?

DECLARE

x NUMBER;

BEGIN

x:=1;

LOOP

16

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 17: PL

COURSE MATERAL- PL-SQL

DBMS_OUTPUT.PUT_LINE(x);

EXIT WHEN x=5;

x:=x+1;

END LOOP;

END;

/

DECLARE

x NUMBER;

BEGIN

x:=1;

LOOP

DBMS_OUTPUT.PUT_LINE(x);

EXIT WHEN x<5;

x:=x+1;

END LOOP;

END;

/

WHILE LOOPING CONSTRUCT

This looping construct will support to execute 1 or more statements repeatedly until a condition is satisfied.

Syntax:

WHILE condition

17

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 18: PL

COURSE MATERAL- PL-SQL

LOOP

statement 1;

statement 2;

......

statement n;

END LOOP;

1. Write a program to display 1st 5 natural numbers?

DECLARE

x NUMBER;

BEGIN

x:=1;

WHILE x<=5

LOOP

DBMS_OUTPUT.PUT_LINE(x);

x:=x+1;

END LOOP;

END;

/

2. Write a program to display 1st n natural numbers?

DECLARE

x NUMBER;

18

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 19: PL

COURSE MATERAL- PL-SQL

n NUMBER:=&n;

BEGIN

x:=1;

WHILE x<=n

LOOP

DBMS_OUTPUT.PUT_LINE(x);

x:=x+1;

END LOOP;

END;

/

3. Write a program to display 1st n ODD numbers?

DECLARE

x NUMBER;

n NUMBER:=&n;

BEGIN

x:=1;

WHILE x<=n*2

LOOP

DBMS_OUTPUT.PUT_LINE(x);

x:=x+2;

END LOOP;

19

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 20: PL

COURSE MATERAL- PL-SQL

END;

/

4. Write a program to display Mathematical Table Of a Given Number?

DECLARE

n NUMBER:=&n;

i NUMBER;

p NUMBER;

BEGIN

i:=1;

WHILE i<=10

LOOP

p:=n*i;

DBMS_OUTPUT.PUT_LINE(n||' * '||i||' = '||p);

i:=i+1;

END LOOP;

END;

/

5. Write a program to check whether a given number is prime or not?

6. Write a program to check whether a given number is argmstrong or not?

7. Write a program to check whether a given number is Palindrome or not?

8. Write a program to display Range of Mathematical Tables?

20

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 21: PL

COURSE MATERAL- PL-SQL

FOR LOOPING CONSTRUCT:

This looping construct will support to execute 1 or more statements based on given range of values.

Variable used at FOR looping construct does not required its declaration.

Variable need not be initialised and it does not require increment.

Variable will act like a local variable, which means it works only in that block where it is used.

Syntax:

FOR var IN [ REVERSE ] lower_bound..upper_bound

LOOP

statement 1;

statement 2;

.......

statement n;

END LOOP;

When REVERSE option is used it will make a loop work in reverse order.

Examples:

1. Write a program to display 1st 5 natural numbers using FOR looping construct?

BEGIN

FOR i IN 1..5

LOOP

DBMS_OUTPUT.PUT_LINE(i);

END LOOP;

21

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 22: PL

COURSE MATERAL- PL-SQL

END;

/

2. Write a program to display 1st n natural numbers using FOR looping construct?

DECLARE

n NUMBER:=&n;

BEGIN

FOR i IN 1..n

LOOP

DBMS_OUTPUT.PUT_LINE(i);

END LOOP;

END;

/

3. Write a program to display 1st 5 Natural Numbers in Reverse Order?

BEGIN

FOR i IN REVERSE 1..5

LOOP

DBMS_OUTPUT.PUT_LINE(i);

END LOOP;

END;

/

4. Write a program to display Reverse of a given String?

22

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 23: PL

COURSE MATERAL- PL-SQL

DECLARE

str VARCHAR2(12):='&str';

rev VARCHAR2(12);

BEGIN

rev:=' ';

FOR i IN REVERSE 1..LENGTH(str)

LOOP

rev:=rev||SUBSTR(str,i,1);

END LOOP;

DBMS_OUTPUT.PUT_LINE('REVERSE OF A STRING IS ......'||rev);

END;

/

5. Write a program to check whether a given string is palindrome or not?

DECLARE

str VARCHAR2(12):='&str';

rev VARCHAR2(12);

BEGIN

rev:=' ';

FOR i IN REVERSE 1..LENGTH(str)

LOOP

rev:=rev||SUBSTR(str,i,1);

23

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 24: PL

COURSE MATERAL- PL-SQL

END LOOP;

IF str=LTRIM(rev) THEN

DBMS_OUTPUT.PUT_LINE('IT IS PALINDROME');

ELSE

DBMS_OUTPUT.PUT_LINE('SORRY');

END IF;

END;

/

6. Write a program to count number of vowels and consonents in a given string?

DECLARE

str VARCHAR2(12):='&str';

v NUMBER;

c NUMBER;

BEGIN

v:=0;

c:=0;

FOR i IN 1..LENGTH(str)

LOOP

IF SUBSTR(str,i,1) IN('A','E','I','O','U') THEN

v:=v+1;

ELSE

24

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 25: PL

COURSE MATERAL- PL-SQL

c:=c+1;

END IF;

END LOOP;

DBMS_OUTPUT.PUT_LINE('NUMBER OF VOWELS ARE.....'||v);

DBMS_OUTPUT.PUT_LINE('NUMBER OF CONSONENTS ARE ......'||c);

END;

/

INTERACTING WITH DATABASE USING PL/SQL:

DATA RETRIEVAL OR QUERY LANGUAGE (DQL OR DRL):

SELECT:

This command will retrieve the data from a database into buffer variables.

It supports to retrieve data of all the columns or required columns from a table.

This statement will support to retrieve only 1 row at a time.

If multiple rows are selected leads to runtime error.

If no rows are selected also leads to runtime error.

Syntax:

SELECT */col1,col2,col3,...... INTO rec_var/var1,var2,var3,......

FROM <table1[,table2,table3,..........]>

WHERE condition(s)

GROUP BY col1[,col2,col3,.........]

HAVING condition(s);

25

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 26: PL

COURSE MATERAL- PL-SQL

COMPOSITE DATATYPES:

1. %TYPE : This composite datatype will support to get the datatype and size of a column to a program variable. If any changes are made to the logical structure of a table, the program will remain independent of those changes.

Syntax:

var table_name.column_name%TYPE[:=val/variable];

1. Write a program to retrieve the data of a given employee number w.r.to ename,sal and deptno?

DECLARE

eno emp.empno%TYPE:=&eno;

en emp.ename%TYPE;

pay emp.sal%TYPE;

dno emp.deptno%TYPE;

BEGIN

SELECT ename,sal,deptno INTO en,pay,dno FROM emp WHERE empno=eno;

DBMS_OUTPUT.PUT_LINE(eno||' '||en||' '||pay||' '||dno);

END;

/

2. %ROWTYPE : This composite datatype will support to store 1 row which is extracted from a table. The row extracted gets accessed using columns names of a table preceeded by variable.

Syntax:

var table_name%ROWTYPE;

Example:

DECLARE

26

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 27: PL

COURSE MATERAL- PL-SQL

eno emp.empno%TYPE:=&eno;

erec emp%ROWTYPE;

BEGIN

SELECT * INTO erec FROM emp WHERE empno=eno;

DBMS_OUTPUT.PUT_LINE(eno||' '||erec.ename||' '||erec.sal||' '||erec.deptno);

END;

/

DATA MANIPULATION LANGUAGE (DML):

INSERT:

Write a program to insert a new record which includes empno,ename,sal and deptno?

DECLARE

eno emp.empno%TYPE:=&eno;

en emp.ename%TYPE:='&en';

pay emp.sal%TYPE:=&pay;

dno emp.deptno%TYPE:=&dno;

i NUMBER;

j NUMBER;

BEGIN

SELECT COUNT(*) INTO i FROM emp WHERE empno=eno;

SELECT COUNT(*) INTO j FROM emp WHERE deptno=dno;

IF eno IS NULL THEN

27

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 28: PL

COURSE MATERAL- PL-SQL

DBMS_OUTPUT.PUT_LINE('CANT STORE NULL VALUE');

ELSIF i>0 THEN

DBMS_OUTPUT.PUT_LINE('EMPLOYEE ALREADY EXISTS');

ELSIF j=0 THEN

DBMS_OUTPUT.PUT_LINE('INVALID DEPTNO');

ELSIF pay<800 THEN

DBMS_OUTPUT.PUT_LINE('INVALID SALARY');

ELSE

INSERT INTO EMP(EMPNO,ENAME,SAL,DEPTNO) VALUES(ENO,EN,PAY,DNO);

COMMIT;

DBMS_OUTPUT.PUT_LINE('ROW INSERTED SUCCESSFULLY');

END IF;

END;

/

UPDATE:

Write a program to update the salary by incrementing only if salary is more than 500 and if employee exists?

DECLARE

eno emp.empno%TYPE:=&eno;

incr NUMBER(7):=&incr;

i NUMBER;

BEGIN

28

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 29: PL

COURSE MATERAL- PL-SQL

SELECT COUNT(*) INTO i FROM emp WHERE empno=eno;

IF i=0 THEN

DBMS_OUTPUT.PUT_LINE('EMPLOYEE DOES NOT EXIST');

ELSIF incr<500 THEN

DBMS_OUTPUT.PUT_LINE('INVALID INCREMENT');

ELSE

UPDATE emp SET sal=sal+incr WHERE empno=eno;

COMMIT;

DBMS_OUTPUT.PUT_LINE('ROW UPDATE SUCCESSFULLY');

END IF;

END;

/

DELETE:

1. Write a program to delete a record from emp table based on given employee number if the employee exists?

DECLARE

eno emp.empno%TYPE:=&eno;

i NUMBER;

BEGIN

SELECT COUNT(*) INTO i FROM emp WHERE empno=eno;

IF i=0 THEN

DBMS_OUTPUT.PUT_LINE('EMPLOYEE DOES NOT EXIST');

29

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 30: PL

COURSE MATERAL- PL-SQL

ELSE

DELETE FROM EMP WHERE EMPNO=ENO;

COMMIT;

DBMS_OUTPUT.PUT_LINE('ROW DELETED SUCCESSFULLY');

END IF;

END;

/

2. Write a program to delete the rows from emp table based on given department number?

DECLARE

dno emp.deptno%TYPE:=&dno;

i NUMBER;

BEGIN

SELECT COUNT(*) INTO i FROM emp WHERE deptno=dno;

IF i=0 THEN

DBMS_OUTPUT.PUT_LINE('DEPARTMENT DOES NOT EXIST');

ELSE

DELETE FROM EMP WHERE DEPTNO=DNO;

COMMIT;

DBMS_OUTPUT.PUT_LINE(i||' ROWS ARE DELETED');

END IF;

END;

30

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 31: PL

COURSE MATERAL- PL-SQL

/

SQL ATTRIBUTES

Oracle provides the following SQL Attributes.

1. SQL%ROWCOUNT : This attribute returns the number of rows affercted by the DML transaction.

2. SQL%FOUND : This attribute returns boolean value i.e. true or false.

It returns TRUE when DML transaction affects the table else returns with FALSE.

3. SQL%NOTFOUND : This attribute returns boolean value i.e. true or false. It returns TRUE when DML transaction does not affect the table else returns with FALSE.

example:

Write a program to delete the rows from emp table based on given department number?

DECLARE

dno emp.deptno%TYPE:=&dno;

r BOOLEAN;

BEGIN

DELETE FROM emp WHERE deptno=dno;

r:=SQL%FOUND;

IF r=TRUE THEN

DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' ROWS ARE DELETED');

ELSE

DBMS_OUTPUT.PUT_LINE('DEPTNO DOES NOT EXIST');

END IF;

END;

31

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 32: PL

COURSE MATERAL- PL-SQL

/

DECLARE

dno emp.deptno%TYPE:=&dno;

r BOOLEAN;

BEGIN

DELETE FROM emp WHERE deptno=dno;

r:=SQL%NOTFOUND;

IF r=TRUE THEN

DBMS_OUTPUT.PUT_LINE('DEPTNO DOES NOT EXIST');

ELSE

DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' ROWS ARE DELETED');

END IF;

END;

/

EXCEPTION HANDLING

Types of Errors:

1. Compile time errors : These errors will occur when the program gets compiled. It generates errors in those instructions of a program, which are not written as per the provided rules. Hence these errors are called Syntax Errors.

2. Logical Errors : Required Output and generated output when does not get match, such type of errors are called Logical Errors.

32

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 33: PL

COURSE MATERAL- PL-SQL

3. Runtime Errors : These errors occur when the program is in execution. When these errors occur the program gets terminated inbetween the execution. To handle such runtime errors and have smooth execution of a program the concept of Exception handling is used.

Exception handling is classified into 2 types;

1. Predefined Exceptions

2. User Defined Exceptions

1. Predefined Exceptions

These exceptions are provided by the software to handle runtime errors.

Oracle provides the following Exceptions with their meanings;

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

Exception Name Error No Meaning of The Exception

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

1. ZERO_DIVIDE -01476 It is to handle that runtime error, which occurs when a

number is divided by 0.

2. NO_DATA_FOUND -01403 It is to handle that runtime error which occurs when no row

is selected by the select statement of PL/SQL.

3. TOO_MANY_ROWS -01422 It is to handle that runtime error which occurs when

multiple rows are selected by the select statement of PL/SQL.

4. VALUE_ERROR -06502 It is to handle that runtime error which occurs when buffer

33

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 34: PL

COURSE MATERAL- PL-SQL

variable memory is too small to store columns data.

5. INVALID_NUMBER It is to handle that runtime error which occurs when

datatype gets mismatch.

6. CURSOR_ALREADY_OPENED -06511 It is to handle that runtime error which occurs when a

cursor gets reopened.

7. INVALID_CURSOR -01001 It is to handle that runtime error which occurs when invalid

operations are performed over a cursor.

8. OTHERS It is to handle any type of Exception

Note:

1. Exception should be handled under EXCEPTION block, based on the following syntax.

EXCEPTION

WHEN exception_name THEN

statements;

2. Exceptions in Oracle gets raised automatically.

3. When Runtime error occurs control automatically gets transfered to EXCEPTION block, searches for the related exception and handles that exception.

4. Exception block can handle more than 1 exception, based on runtime error related exception will get handle.

5. All the other unknown runtime errors which may occur in a program can be handled using OTHERS exception.

34

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 35: PL

COURSE MATERAL- PL-SQL

6. When exceptions are raised using OTHERS exception, and if related exceptions are also enclosed then priority is given to related exception.

7. When related exceptions and OTHERS exception is placed in a single program, it is with a rule that first related exception should be enclosed and then the OTHERS exception should be written.

examples:

1. Write a program to divide 2 numbers and handle necessary exception?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

c NUMBER;

BEGIN

c:=a/b;

DBMS_OUTPUT.PUT_LINE('QUOTIENT IS ......'||c);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('CANT DIVIDE THE NUMBER BY 0');

END;

/

2. Write a program to input salary and display empno,ename,job,deptno from emp table? Handle necessary exceptions.

DECLARE

pay emp.sal%TYPE:=&pay;

eno emp.empno%TYPE;

35

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 36: PL

COURSE MATERAL- PL-SQL

en emp.ename%TYPE;

des VARCHAR2(5);

dno emp.deptno%TYPE;

BEGIN

SELECT empno,ename,job,deptno INTO eno,en,des,dno FROM emp WHERE sal=pay;

DBMS_OUTPUT.PUT_LINE(eno||' '||en||' '||des||' '||pay||' '||dno);

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('NO ROW SELECTED');

WHEN TOO_MANY_ROWS THEN

DBMS_OUTPUT.PUT_LINE('MULTIPLE ROWS CANT BE SELECTED');

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE('MEM INSUFFICIENT');

END;

/

(OR)

DECLARE

pay emp.sal%TYPE:=&pay;

eno emp.empno%TYPE;

en emp.ename%TYPE;

des VARCHAR2(5);

36

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 37: PL

COURSE MATERAL- PL-SQL

dno emp.deptno%TYPE;

BEGIN

SELECT empno,ename,job,deptno INTO eno,en,des,dno FROM emp WHERE sal=pay;

DBMS_OUTPUT.PUT_LINE(eno||' '||en||' '||des||' '||pay||' '||dno);

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('NO ROW SELECTED');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('ERROR OCCURED...'||SQLCODE||' '||SQLERRM);

END;

/

USER DEFINED EXCEPTIONS

Exceptions can be created of user defined, based on 3 steps;

1. Declaration of exception

2. Raising of exception

3. Handling the exception

1. Declaration of Exception:

Exception name should be declared at the declaration block of PL/SQL program. Any number of exception names can be declared but with unique names. A keyword called EXCEPTION should be used after the exception name.

Syntax:

DECLARE

37

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 38: PL

COURSE MATERAL- PL-SQL

exception_name EXCEPTION;

2. Raising an Exception :

User defined exception should be raised manually using RAISE keyword.

Syntax:

RAISE exception_name;

3. Handling the exception:

User defined exception should be handled using EXCEPTION block.

Syntax:

WHEN exception_name THEN

statements;

Write a program to divide 2 numbers and handle the exception using user defined exception?

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

c NUMBER;

ZD EXCEPTION;

BEGIN

IF b=0 THEN

RAISE ZD;

END IF;

c:=a/b;

38

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 39: PL

COURSE MATERAL- PL-SQL

DBMS_OUTPUT.PUT_LINE('QUOTIENT IS......'||c);

EXCEPTION

WHEN ZD THEN

DBMS_OUTPUT.PUT_LINE('CANT DIVIDE THE NUMBER BY 0');

END;

/

Write a program to perform operations over bank and handle necessary exceptions?

BANK

acno ahn addr bal

1001 xyz amrpt 12000

1009 abc srngr 6500 (7700)

1003 pqr abids 4500 (2500)

1005 ijk bhel 8940

TRANS

acno tt dot amt

1009 D --- 1200

1003 W --- 2000

CREATE TABLE BANK

(ACNO NUMBER(4),AHN VARCHAR2(12),ADDR VARCHAR2(14),BAL NUMBER(8));

INSERT INTO BANK VALUES(&ACNO,'&AHN','&ADDR',&BAL);

CREATE TABLE TRANS

39

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 40: PL

COURSE MATERAL- PL-SQL

(ACNO NUMBER(4),TT VARCHAR2(3),DOT DATE,AMT NUMBER(8));

DECLARE

ano bank.acno%TYPE:=&ano;

trty trans.tt%TYPE:='&trty';

amount trans.amt%TYPE:=&amount;

s bank.bal%TYPE;

OVR_DRFT EXCEPTION;

INV_TRANS EXCEPTION;

INV_AMT EXCEPTION;

BEGIN

SELECT bal INTO s FROM bank WHERE acno=ano;

IF trty='D' OR trty='d' THEN

INSERT INTO trans VALUES (ano,trty,SYSDATE,amount);

UPDATE bank SET bal=bal+amount WHERE acno=ano;

DBMS_OUTPUT.PUT_LINE('RECORD INSERTED AND UPDATED SUCCESSFULLY');

ELSE

IF trty='W' OR trty='w' THEN

IF amount>s THEN

RAISE OVR_DRFT;

ELSE

IF amount>s-500 THEN

40

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 41: PL

COURSE MATERAL- PL-SQL

RAISE INV_TRANS;

ELSE

IF amount<100 THEN

RAISE INV_AMT;

ELSE

INSERT INTO trans VALUES(ano,trty,SYSDATE,amount);

UPDATE bank SET bal=bal-amount WHERE acno=ano;

DBMS_OUTPUT.PUT_LINE('REC INSERTED AND UPDATED SUCCESS');

END IF;

END IF;

END IF;

ELSE

DBMS_OUTPUT.PUT_LINE('INVALID TRANSACTION TYPE');

END IF;

END IF;

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('INVALID ACCOUNT NUMBER');

WHEN OVR_DRFT THEN

DBMS_OUTPUT.PUT_LINE('OVER DRAFT OF AMOUNT');

WHEN INV_TRANS THEN

41

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 42: PL

COURSE MATERAL- PL-SQL

DBMS_OUTPUT.PUT_LINE('MIN BAL SHOULD BE 500');

WHEN INV_AMT THEN

DBMS_OUTPUT.PUT_LINE('CANT WITHDRAW < 100');

END;

/

PRAGMA EXCEPTIONS

1. It is a number binded exception.

2. It is a pre call to an exception.

3. PRAGMA exceptions are declared immediately after the declaration of user defined exception name.

4. Any number of PRAGMA exceptions can be declared in a single program,but with their related user defined exception names.

Syntax:

exception_name EXCEPTION;

PRAGMA EXCEPTION_INIT(arg1,arg2);

arg1 ----- exception name

arg2 ----- error number

DECLARE

a NUMBER:=&a;

b NUMBER:=&b;

c NUMBER;

ZD EXCEPTION;

PRAGMA EXCEPTION_INIT(ZD,-01476);

42

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 43: PL

COURSE MATERAL- PL-SQL

BEGIN

c:=a/b;

DBMS_OUTPUT.PUT_LINE('QUOTIENT IS.....'||c);

EXCEPTION

WHEN ZD THEN

DBMS_OUTPUT.PUT_LINE('CANT DIVIDE THE NUMBER BY 0');

END;

/

CURSORS

Oracle provides a memory to process queries and that memory is called PRIVATE sql area.

cursors are classified into 2 types:

1. Implicit cursors (automatic cursors)

2. Explicit cursors (manual cursors)

1. Implicit cursors : These cursors will create memory automatically to process single row queries.

Oracle allocates memory, populates the data into that memory, and deallocates that memory when the task is completed. It also contains the predefined attributes in that memory to perform various tasks (SQL%FOUND,SQL%NOTFOUND,SQL%ROWCOUNT).

2. Explicit cursors: These cursors are created by a user to process multiple row queries. These cursors are created based on 4 steps;

1. Declaration of cursor

2. Opening a cursor

3. Fetching data from a cursor

4. Closing the cursor

43

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 44: PL

COURSE MATERAL- PL-SQL

1. Declaration of Cursor : A cursor variable is declared at declaration part of PL/SQL program associated with SELECT query which is used at SQL. A cursor cant be associated with a SELECT....INTO query. Any number of cursor variables can be declared associated with different queries.

syntax:

CURSOR cursor_var[(list_of_args]) IS SELECT query;

2. Opening a cursor : When a cursor gets opened, it executes the query which is associated to it and makes the data available in that cursor.

syntax:

OPEN cursor_var[(list_of_args)];

3. Fetching the data from a cursor: Data can be extracted from a cursor variable w.r.to 1 row at a time into buffer variables. It also transfers the control to the next row in a cursor making it ready for fetching.

syntax:

FETCH cursor_var IN var1,var2,.............;

4. Closing a cursor : A cursor can be closed, where it deallocates the memory.

syntax:

CLOSE cursor_var;

CURSOR ATTRIBUTES:

1. %FOUND : It returns boolean value i.e. returns true if it points to a row else returns with false.

2. %NOTFOUND : It returns boolean value i.e. returns true if it does not point to a row else returns with false.

3. %ISOPEN : It returns true if the cursor is opened else returns with false.

4. %ROWCOUNT : It returns row number which is accessed from a table.

note: these attributes should be preceeded by cursor variable when they are used in PL/SQL program.

44

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 45: PL

COURSE MATERAL- PL-SQL

1. Write a program to create explicit cursor which will access multiple rows from emp table?

DECLARE

CURSOR c1 IS SELECT ename,sal,deptno FROM emp;

en emp.ename%TYPE;

pay emp.sal%TYPE;

dno emp.deptno%TYPE;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO en,pay,dno;

EXIT WHEN c1%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(en||' '||pay||' '||dno);

END LOOP;

CLOSE c1;

END;

/

2. Write a program to create explicit cursor which supports to retrieve a required record from emp table?

DECLARE

eno emp.empno%TYPE:=&eno;

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp;

a emp.empno%TYPE;

45

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 46: PL

COURSE MATERAL- PL-SQL

b emp.ename%TYPE;

c emp.sal%TYPE;

d emp.deptno%TYPE;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO a,b,c,d;

EXIT WHEN c1%FOUND=FALSE;

IF a=eno THEN

DBMS_OUTPUT.PUT_LINE(a||' '||b||' '||c||' '||d);

END IF;

END LOOP;

CLOSE c1;

END;

/

3. Write a program to create explicit cursor which supports to store all the records of emp table and calculates for the increment of salary on deptno thru buffer variables for a required employee number.

If deptno is 10 then increment the sal by 20%

If deptno is 20 then increment the sal by 15%

If deptno is 30 then increment the sal by 10%

DECLARE

46

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 47: PL

COURSE MATERAL- PL-SQL

eno emp.empno%TYPE:=&eno;

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp;

a emp.empno%TYPE;

b emp.ename%TYPE;

c emp.sal%TYPE;

d emp.deptno%TYPE;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO a,b,c,d;

EXIT WHEN c1%FOUND=FALSE;

IF a=eno THEN

DBMS_OUTPUT.PUT_LINE('BEFORE INCREMENT');

DBMS_OUTPUT.PUT_LINE(a||' '||b||' '||c||' '||d);

c:=CASE d

WHEN 10 THEN C+C*20/100

WHEN 20 THEN C+C*15/100

WHEN 30 THEN C+C*10/100

END;

DBMS_OUTPUT.PUT_LINE('AFTER INCREMENT');

DBMS_OUTPUT.PUT_LINE(a||' '||b||' '||c||' '||d);

47

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 48: PL

COURSE MATERAL- PL-SQL

END IF;

END LOOP;

CLOSE c1;

END;

/

4. Write a program to create explicit cursor of all the records from emp table/ calculate the increment of salary of all the employees based on categories of deptno with different percentages thru buffer variables?

If deptno is 10 then increment the sal by 20%

If deptno is 20 then increment the sal by 15%

If deptno is 30 then increment the sal by 10%

DECLARE

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp;

a emp.empno%TYPE;

b emp.ename%TYPE;

c emp.sal%TYPE;

d emp.deptno%TYPE;

i NUMBER;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO a,b,c,d;

48

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 49: PL

COURSE MATERAL- PL-SQL

EXIT WHEN c1%FOUND=FALSE;

i:=CASE d

WHEN 10 THEN C+C*20/100

WHEN 20 THEN C+C*15/100

WHEN 30 THEN C+C*10/100

END;

DBMS_OUTPUT.PUT_LINE(a||' '||b||' '||c||' '||d||' '||i);

END LOOP;

CLOSE c1;

END;

/

5. Write a program to create explicit cursor which will allow a user to retrieve the records of 20 dept?

DECLARE

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp WHERE deptno=20;

a emp.empno%TYPE;

b emp.ename%TYPE;

c emp.sal%TYPE;

d emp.deptno%TYPE;

BEGIN

OPEN c1;

LOOP

49

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 50: PL

COURSE MATERAL- PL-SQL

FETCH c1 INTO a,b,c,d;

EXIT WHEN c1%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(a||' '||b||' '||c||' '||d);

END LOOP;

CLOSE c1;

END;

/

6. Write a program to create explicit cursor that retrieves all the records from emp table and handle necessary exceptions related to cursors?

DECLARE

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp;

a emp.empno%TYPE;

b emp.ename%TYPE;

c emp.sal%TYPE;

d emp.deptno%TYPE;

e BOOLEAN;

BEGIN

OPEN c1;

e:=c1%ISOPEN;

IF e=TRUE THEN

DBMS_OUTPUT.PUT_LINE('CURSOR IS OPENED');

END IF;

50

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 51: PL

COURSE MATERAL- PL-SQL

LOOP

FETCH c1 INTO a,b,c,d;

EXIT WHEN c1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(c1%ROWCOUNT||' '||a||' '||b||' '||c||' '||d);

END LOOP;

CLOSE c1;

EXCEPTION

WHEN INVALID_CURSOR THEN

DBMS_OUTPUT.PUT_LINE('SORRY CURSOR IS NOT OPENED');

END;

/

PARAMETERISED CURSOR :

At this cursor it will allow a user to pass the data extracted from 1 cursor to the other cursor thru arguments.

Parameter specification is provided at Declaration of cursor and when the cursor gets opened.

example:

Write a program to display employees information according to their departments?

Department..........................10

EMPNO ENAME

Department..........................20

EMPNO ENAME

Department..........................30

51

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 52: PL

COURSE MATERAL- PL-SQL

EMPNO ENAME

DECLARE

CURSOR c1 IS SELECT DISTINCT deptno FROM emp;

CURSOR c2(dno NUMBER) IS SELECT empno,ename FROM emp WHERE deptno=dno;

eno emp.empno%TYPE;

en emp.ename%TYPE;

dno emp.deptno%TYPE;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO dno;

EXIT WHEN c1%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE('Department...................'||dno);

DBMS_OUTPUT.PUT_LINE('EMPNO'||' '||'ENAME');

OPEN c2(dno);

LOOP

FETCH c2 INTO eno,en;

EXIT WHEN c2%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(eno||' '||en);

END LOOP;

CLOSE c2;

52

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 53: PL

COURSE MATERAL- PL-SQL

END LOOP;

CLOSE c1;

END;

/

CURSOR FOR LOOP:

Data which is available in Cursor can be accessed using FOR looping construct, which does not require opening of cursor, fetching the data from a cursor and closing a cursor.

For loop variable by default gets declared with a composite datatype i.e. %ROWTYPE. To access the data of a cursor we refer to the columns of a table preceeded by cursor variable.

Syntax:

FOR variable IN cursor_var

LOOP

statements;

END LOOP;

EXAMPLE:

DECLARE

CURSOR c1 IS SELECT empno,ename,sal,deptno FROM emp;

BEGIN

FOR x IN c1

LOOP

DBMS_OUTPUT.PUT_LINE(x.empno||' '||x.ename||' '||x.sal||' '||x.deptno);

END LOOP;

53

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 54: PL

COURSE MATERAL- PL-SQL

END;

/

REFERENCE CURSORS

A REF CURSOR is basically a data type.

A variable which is created based on such a datatype is generally called Cursor variable.

A Cursor variable can be associated with different queries at runtime.

The primary Advantage of using cursor variables is to pass the result sets to different sub programs like procedures,functions,packages etc.

Syntax:

TYPE ref_type IS REF CURSOR;

EXAMPLE:

DECLARE

TYPE r_cursor IS REF CURSOR;

c_emp r_cursor;

en emp.ename%TYPE;

pay emp.sal%TYPE;

dno dept.deptno%TYPE;

dn dept.dname%TYPE;

BEGIN

OPEN c_emp FOR SELECT ename,sal FROM emp;

LOOP

FETCH c_emp INTO en,pay;

54

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 55: PL

COURSE MATERAL- PL-SQL

EXIT WHEN c_emp%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(en||' '||pay);

END LOOP;

OPEN c_emp FOR SELECT deptno,dname FROM dept;

LOOP

FETCH c_emp INTO dno,dn;

EXIT WHEN c_emp%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(dno||' '||dn);

END LOOP;

CLOSE c_emp;

END;

/

Using Reference Cursor thru %ROWTYPE.

DECLARE

TYPE r_cursor IS REF CURSOR;

c_emp r_cursor;

erec emp%ROWTYPE;

BEGIN

OPEN c_emp FOR SELECT * FROM emp;

LOOP

FETCH c_emp INTO erec;

55

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 56: PL

COURSE MATERAL- PL-SQL

EXIT WHEN c_emp%FOUND=FALSE;

DBMS_OUTPUT.PUT_LINE(erec.ename||' '||erec.sal);

END LOOP;

CLOSE c_emp;

END;

/

SUB PROGRAMS

It is a process of splitting a large application program into small modules or blocks.

Oracle supports to create subprogram in the following ways;

1. Stored procedures

2. Stored Functions

3. Stored Packages

4. Triggers

Advantages of Subprograms:

1. Readability of a program gets enhanced.

2. Reusability.

3. Extensibility (Code in the subprogram can be increased or can be decreased)

4. Error Detection and Modification is quite easy.

5. Network Traffic gets reduces.

6. Performance gets increases.

7. provides high security for business logic.

56

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 57: PL

COURSE MATERAL- PL-SQL

STORED PROCEDURES:

Procedure is a self contained or predefined program which does not return any value.

Procedure are created as a stored block database object permanently in a database server.

Procedure can be provided with input arguments and can take some values from procedure after its execution thru output arguments into calling program.

Arguments can be set with 3 modes:

1. IN : By default arguments at procedure is set with IN mode, which will act like giving input to the procedure. The arguments set with IN mode cant be modified. IN mode arguments will act like CALL BY VALUE.

2. OUT : If arguments are set with OUT mode, it works for CALL BY REFERENCE. Any changes made to the OUT arguments will automatically reflect into the Main program variables.

3. IN OUT : It is a combination of the above 2 arguments.

Syntax:

CREATE [ OR REPLACE ] PROCEDURE proc_name(arg1 mode data_type[ ,....])

IS/AS

[local declaration;]

BEGIN

statement 1;

statement 2;

.......

statement n;

[EXCEPTION

exception handlers;]

57

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 58: PL

COURSE MATERAL- PL-SQL

END;

/

When the procedure is being created for 1st time then REPLACE option is not required, but when the same procedure requires any changes and the same object is to be created again then we REPLACE the procedure.

EXECUTION OF PROCEDURE:

A procedure which is created can be executed in 2 ways;

1. using EXEC command.

EXEC proc_name(list_of_args)

2. using Main program.

proc_name(list_of_args);

EXAMPLES:

1. Create a procedure that will find the addition of 2 numbers?

SQL> CREATE OR REPLACE PROCEDURE add_no(a IN NUMBER,b IN NUMBER)

2 IS

3 c NUMBER;

4 BEGIN

5 c:=a+b;

6 DBMS_OUTPUT.PUT_LINE('SUM IS......'||c);

7 END;

8 /

Procedure created.

58

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 59: PL

COURSE MATERAL- PL-SQL

EXECUTING A PROCEDURE USING EXEC COMMAND;

SQL> SET SERVEROUTPUT ON

SQL> EXEC add_no(19,28)

SUM IS......47

PL/SQL procedure successfully completed.

SQL> EXEC ADD_NO(156,987)

SUM IS......1143

EXECUTING A PROCEDURE USING MAIN PROGRAM.

SQL> ED PRO1

DECLARE

x NUMBER:=&x;

y NUMBER:=&y;

BEGIN

add_no(x,y);

END;

/

SQL> @PRO1

2. Create a procedure called display that provides the output using output statement of PL/SQL program?

SQL> CREATE OR REPLACE PROCEDURE DISPLAY(a VARCHAR2)

2 IS

3 BEGIN

59

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 60: PL

COURSE MATERAL- PL-SQL

4 DBMS_OUTPUT.PUT_LINE(a);

5 END;

6 /

Procedure created.

3. Create a procedure that takes 2 input arguments and return a value using output argument.

CREATE OR REPLACE PROCEDURE sum_nos(a NUMBER,b NUMBER,c OUT NUMBER)

IS

BEGIN

c:=a+b;

END;

/

SQL> ED PRO2

DECLARE

x NUMBER:=&x;

y NUMBER:=&y;

z NUMBER;

BEGIN

sum_nos(x,y,z);

display('Sum Is......'||z);

display('Thanx');

END;

60

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 61: PL

COURSE MATERAL- PL-SQL

/

SQL> @PRO2

4. Create a procedure that takes 2 values as input and provides the quotient of 2 values? Handle the exception if required?

CREATE OR REPLACE PROCEDURE DIV_NOS(a NUMBER,b NUMBER)

IS

c NUMBER;

BEGIN

c:=a/b;

DISPLAY('QUOTIENT IS......'||c);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DISPLAY('CANT DIVIDE THE NUMBER BY 0');

END;

/

SQL> EXEC DIV_NOS(12,2)

SQL> EXEC DIV_NOS(9,0)

5. Create a procedure that takes empno as input and displays ename,job,sal,deptno of that employee?Handle necessary Exceptions?

SQL> CREATE OR REPLACE PROCEDURE SRCH_EMP(ENO EMP.EMPNO%TYPE)

2 IS

3 en emp.ename%TYPE;

61

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 62: PL

COURSE MATERAL- PL-SQL

4 des emp.job%TYPE;

5 pay emp.sal%TYPE;

6 dno emp.deptno%TYPE;

7 BEGIN

8 SELECT ename,job,sal,deptno INTO en,des,pay,dno FROM emp WHERE empno=eno;

9 DISPLAY(eno||' '||en||' '||des||' '||pay||' '||dno);

10 EXCEPTION

11 WHEN NO_DATA_FOUND THEN

12 DISPLAY('NO ROW IS SELECTED');

13 WHEN TOO_MANY_ROWS THEN

14 DISPLAY('MULTIPLE ROWS CANT BE SELECTED');

15 WHEN VALUE_ERROR THEN

16 DISPLAY('MEM INSUFFICIENT');

17 END;

18 /

Procedure created.

SQL> EXEC SRCH_EMP(7788)

7788 SCOTT ANALYST 3000 20

PL/SQL procedure successfully completed.

SQL> EXEC SRCH_EMP(8009)

62

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 63: PL

COURSE MATERAL- PL-SQL

NO ROW IS SELECTED

PL/SQL procedure successfully completed.

STORED FUNCTIONS

OR

USER DEFINED FUNCTIONS

Function can be defined as,"Self contained program, which returns maximum of 1 value".

Function is also created as stored block database object permanently in a database server.

Syntax:

CREATE [ OR REPLACE ] FUNCTION func_name(list_of_args)

RETURN data_type

IS

[local declaration;]

BEGIN

statement 1;

statement 2;

......

statement n;

RETURN var/val;

END;

/

CALLING A USER DEFINED FUNCTION:

63

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 64: PL

COURSE MATERAL- PL-SQL

A user defined function, which is created can be called in 2 ways;

1. Using SELECT statement;

SELECT func_name(list_of_args) FROM dual;

2. Using main program;

var:=func_name(list_of_args);

examples:

create a function that takes 2 values as arguments and returns mutiplication of those values?

SQL> CREATE OR REPLACE FUNCTION MUL_NOS(a NUMBER,b NUMBER)

2 RETURN NUMBER

3 IS

4 c NUMBER;

5 BEGIN

6 c:=a*b;

7 RETURN c;

8 END;

9 /

Function created.

SQL> SELECT MUL_NOS(12,12) FROM DUAL;

MUL_NOS(12,12)

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

144

64

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 65: PL

COURSE MATERAL- PL-SQL

SQL> ED PRO3

DECLARE

x NUMBER:=&x;

y NUMBER:=&y;

z NUMBER;

BEGIN

z:=MUL_NOS(x,y);

DISPLAY('PRODUCT IS........'||z);

END;

/

SQL> @PRO3

Create a function that takes empno as input and returns ename?

SQL> CREATE OR REPLACE FUNCTION FIND_EMP(eno emp.empno%TYPE)

2 RETURN VARCHAR2

3 IS

4 en emp.ename%TYPE;

5 BEGIN

6 SELECT ename INTO en FROM emp WHERE empno=eno;

7 RETURN en;

8 END;

9 /

65

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 66: PL

COURSE MATERAL- PL-SQL

Function created.

SQL> SELECT FIND_EMP(7788)

2 FROM dual;

FIND_EMP(7788)

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

SCOTT

Create a function that takes n value as argument and returns Factorial of a given number?

Create a function that takes n value as argument and returns Reverse of a given number?

Create a function that takes n value as argument and check whether a given number is armstrong or not?

STORED PACKAGES

Package is defined as Collection of procedures and functions.

It also supports to enclose cursors into it.

Package is implemented using 2 concepts;

1. Package Declaration or specification

. Package Definition or Body

1. Package Specification:

At package specification it supports to enclose declaration of procedures with their names, arguments. Functions with their names, arguments and return types. Cursor with its name and query associated to it.

Syntax:

CREATE [ OR REPLACE ] PACKAGE pack_name

IS

66

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 67: PL

COURSE MATERAL- PL-SQL

BEGIN

PROCEDURE proc_name1(list_of_args);

PROCEDURE proc_name2(list_of_args);

...................

FUNCTION func_name1(list_of_args) RETURN data_type;

FUNCTION func_name2(list_of_args) RETURN data_type;

...................

CURSOR cursor_var1 IS SELECT query;

...................

END;

/

2. Package Definition or Body:

At package body respective definitions to procedures and functions are enclosed. A keyword called BODY is used to create package definition.

Syntax:

CREATE [ OR REPLACE ] PACKAGE BODY pack_name

IS

PROCEDURE proc_name1(list_of_args)

IS

[ local declaration; ]

BEGIN

statements;

67

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 68: PL

COURSE MATERAL- PL-SQL

[EXCEPTION

exception handlers;]

END;

......................

FUNCTION func_name1(list_of_args)

RETURN data_type

IS

[ local declaration; ]

BEGIN

statements;

RETURN var/val;

END;

......................

END;

/

EXECUTING PROCEDURES AND FUNCTIONS OF PACKAGE:

To execute procedures:

EXEC pack_name.proc_name1(list_of_args)

To execute functions:

SELECT pack_name.func_name1(list_of_args) FROM dual;

EXAMPLE:

68

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 69: PL

COURSE MATERAL- PL-SQL

SQL> CREATE OR REPLACE PACKAGE test_pack

2 IS

3 PROCEDURE div_nos(a NUMBER,b NUMBER);

4 FUNCTION mul_nos(a NUMBER,b NUMBER) RETURN NUMBER;

5 CURSOR c1 IS SELECT * FROM DEPT;

6 END;

7 /

Package created.

SQL> CREATE OR REPLACE PACKAGE BODY test_pack

2 IS

3 PROCEDURE div_nos(a NUMBER,b NUMBER)

4 IS

5 c NUMBER;

6 BEGIN

7 c:=a/b;

8 DISPLAY('QUOTIENT IS.....'||c);

9 EXCEPTION

10 WHEN ZERO_DIVIDE THEN

11 DISPLAY('CANT DIVIDE THE NUMBER BY 0');

12 END;

13 FUNCTION mul_nos(a NUMBER,b NUMBER)

69

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 70: PL

COURSE MATERAL- PL-SQL

14 RETURN NUMBER

15 IS

16 c NUMBER;

17 BEGIN

18 c:=a*b;

19 RETURN c;

20 END;

21 END;

22 /

Package body created.

SQL> EXEC test_pack.div_nos(5,2)

QUOTIENT IS.....2.5

PL/SQL procedure successfully completed.

SQL> EXEC test_pack.div_nos(13,0)

CANT DIVIDE THE NUMBER BY 0

PL/SQL procedure successfully completed.

SQL> SELECT test_pack.mul_nos(12,12) FROM dual;

TEST_PACK.MUL_NOS(12,12)

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

144

Write a program to access the cursor which is created in a package?

70

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 71: PL

COURSE MATERAL- PL-SQL

DECLARE

dno dept.deptno%TYPE;

dn dept.dname%TYPE;

l dept.loc%TYPE;

BEGIN

OPEN test_pack.c1;

LOOP

FETCH test_pack.c1 INTO dno,dn,l;

EXIT WHEN test_pack.c1%NOTFOUND;

DISPLAY(dno||' '||dn||' '||l);

END LOOP;

CLOSE test_pack.c1;

END;

/

VIEWING THE INFORMATION ABOUT SUBPROGRAMS:

1. USER_OBJECTS : This predefined table provides the information about different objects like tables, views, Procedures, Functions, Packages etc.

SELECT OBJECT_NAME,OBJECT_TYPE FROM USER_OBJECTS

WHERE OBJECT_TYPE='PROCEDURE' OR OBJECT_TYPE='FUNCTION';

2. USER_SOURCE : This predefined table provides the information about the code which is written for different stored block objects.

SELECT TEXT FROM USER_SOURCE;

71

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 72: PL

COURSE MATERAL- PL-SQL

SELECT TEXT FROM USER_SOURCE WHERE TYPE='PROCEDURE';

GRANT AND REVOKE THE PRIVILEGES ON STORED BLOCK OBJECTS:

GRANT:

GRANT EXECUTE ON OBJECT_NAME TO USER1[,USER2,USER3,.....]/PUBLIC;

CANCELLING THE PRIVILEGES:

REVOKE EXECUTE ON OBJECT_NAME FROM USER1[,USER2,USER3,....]/PUBLIC;

EXAMPLE:

CONN SYSTEM/MANAGER

CREATE USER SHAREEF IDENTIFIED BY AHMED;

GRANT CONNECT,RESOURCE TO SHAREEF;

CONN SCOTT/TIGER

GRANT EXECUTE ON SRCH_EMP TO SHAREEF;

GRANT EXECUTE ON MUL_NOS TO SHAREEF;

CONN SHAREEF/AHMED

EXEC SCOTT.SRCH_EMP(7788)

SELECT SCOTT.MUL_NOS(12,12) FROM DUAL;

DROPING THE STORED BLOCK OBJECTS:

SYNTAX: DROP OBJECT_TYPE OBJECT_NAME;

TO DROP PROCEDURES:

SYNTAX : DROP PROCEDURE PROC_NAME;

DROP PROCEDURE SRCH_EMP;

72

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 73: PL

COURSE MATERAL- PL-SQL

TO DROP FUNCTIONS:

SYNTAX : DROP FUNCTION FUNC_NAME;

DROP FUNCTION MUL_NOS;

TO DROP PACKAGES:

To drop a package it is essential that first package body should be dropped and then the package.

DROP PACKAGE [BODY] pack_name;

EXAMPLE:

DROP PACKAGE BODY test_pack;

DROP PACKAGE test_pack;

VIEWING THE ERRORS OF STORED BLOCK OBJECTS:

SHOW ERRORS [PROCEDURE/FUNCTION/PACKAGE/PACKAGE BODY/VIEW] object_name

By default it shows the errors of last created stored block object.

In order to view the errors of the other stored block objects, it is essential that object type should be mentioned followed by object name.

SHOW ERRORS

SHOW ERRORS PROCEDURE DISPLAY

TRIGGERS

Trigger is defined as "Stored PL/SQL program unit, which is associated to a specific table".

Triggers are executed (fired) automatically whenever invalid operations are performed over a table.

Triggers does not take arguments like procedures, functions.

Triggers are not executed manually like procedure, functions.

73

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 74: PL

COURSE MATERAL- PL-SQL

Triggering statement will be responsible for the triggers to be fired.

TYPES OF TRIGGERS:

Oracle supports to create the following 3 types of triggers.

1. DML Triggers : These triggers are fired BEFORE / AFTER the execution of DML commands like INSERT, UPDATE, DELETE.

2. DDL Triggers : These triggers are executed BEFORE / AFTER the execution of DDL commands like CREATE, ALTER, TRUNCATE, RENAME and DROP.

3. Database Triggers : These triggers are executed BEFORE / AFTER the database operations like LOG ON/ LOG OFF/ SHUTDOWN / STARTUP of database.

ADVANTAGES OF TRIGGERS:

1. Triggers can audit the transactions.

2. Triggers can derive the column values using Bind variables

3. Triggers will take the backup of the data without the notice of operators.

4. Triggers will allow to create complex business logics that cant be provided by constraints.

1. DML Triggers : These triggers are executed BEFORE / AFTER the DML operations over a associated table.

Syntax:

CREATE [OR REPLACE] TRIGGER trigger_name

BEFORE / AFTER INSERT OR UPDATE OR DELETE

ON object_name

[ FOR EACH ROW ]

[ WHEN condition ]

[ DECLARE

74

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 75: PL

COURSE MATERAL- PL-SQL

declaration part; ]

BEGIN

Trigger Constraint

Trigger Action;

END;

/

EXECUTION OF TRIGGERS:

Triggers are executed in 2 ways;

1. Statement Level Trigger : These triggers are fired on whole table.

2. Row Level Trigger : These triggers are fired over each row that gets match with trigger constraint. If a trigger is enclosed with option

FOR EACH ROW then it is called as Row level trigger.

From the above 2 types of triggers a table can be associated with maximum of 12 triggers.

I. STATEMENT LEVEL

1. BEFORE

i. INSERT

ii. UPDATE

iii. DELETE

2. AFTER

i. INSERT

ii. UPDATE

iii. DELETE

75

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 76: PL

COURSE MATERAL- PL-SQL

II. ROW LEVEL

1. BEFORE

i. INSERT

ii. UPDATE

iii. DELETE

2. AFTER

i. INSERT

ii. UPDATE

iii. DELETE

NOTE:

1. A table can be associated with any number of triggers.

2. Difference between trigger and constraint is, "constraint is associated to a column and trigger is fired towards whole table".

3. Triggers takes the backup of data using bind variables :OLD and :NEW

While Inserting:

EMPNO ENAMEJOB MGR HIREDATE SAL COMM DEPTNO

:NEW 1001 XYZ CLERK 7839 10-JAN-83 2000 300 30

While Updating:

EMPNO ENAMEJOB MGR HIREDATE SAL COMM DEPTNO

:NEW 7369 SMITH CLERK 7902 17-DEC-80 1800 NULL 20

EMPNO ENAMEJOB MGR HIREDATE SAL COMM DEPTNO

:OLD 7369 SMITH CLERK 7902 17-DEC-80 800 NULL 20

76

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 77: PL

COURSE MATERAL- PL-SQL

While Deleting:

EMPNO ENAMEJOB MGR HIREDATE SAL COMM DEPTNO

:OLD 7876 ADAMSCLERK 7788 12-JAN-83 1100 NULL 20

4. Error is provided when invalid operation is performed over a trigger associated table, using a predefined procedure called RAISE_APPLICATION_ERROR(arg1,arg2);

arg1 is user defired error number, which should be in a range of -20000 and -20999

arg2 is user defined error message, which can be of min 1 byte and max of 2048 bytes.

1. Create a statement level trigger for INSERT triggering event on EMP table where trigger should be fired if the operation is performed on emp table other than working days.

SQL> CREATE OR REPLACE TRIGGER TR1

2 AFTER INSERT ON EMP

3 BEGIN

4 IF RTRIM(TO_CHAR(SYSDATE,'DAY'))='SUNDAY' THEN

5 RAISE_APPLICATION_ERROR(-20001,'CANT INSERT THE RECORD ON SUNDAY');

6 END IF;

7 END;

8 /

Trigger created.

2. Create a statement level trigger for INSERT triggering even on EMP table where trigger should be fired if the operation is perfomred before 10am and after 17pm?

SQL> CREATE OR REPLACE TRIGGER tr2

2 AFTER INSERT ON EMP

3 BEGIN

77

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 78: PL

COURSE MATERAL- PL-SQL

4 IF TO_CHAR(SYSDATE,'HH24') NOT BETWEEN 10 AND 17 THEN

5 RAISE_APPLICATION_ERROR(-20002,'CANT INSERT THE RECORD AS TIME OUT OF RANGE');

6 END IF;

7 END;

8 /

Trigger created.

3. Create a row level trigger for UPDATE triggering event on emp table which makes a backup of updated and previous data into a new table.

EMPB

eno osal nsal dot

CREATE TABLE EMPB

(eno NUMBER(4),osal NUMBER(7,2),nsal NUMBER(7,2),dot DATE);

SQL> CREATE OR REPLACE TRIGGER TR3

2 AFTER UPDATE ON EMP

3 FOR EACH ROW

4 BEGIN

5 INSERT INTO EMPB VALUES(:NEW.EMPNO,:OLD.SAL,:NEW.SAL,SYSDATE);

6 DBMS_OUTPUT.PUT_LINE('ROW INSERTED BY TRIGGER');

7 END;

8 /

Trigger created.

78

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 79: PL

COURSE MATERAL- PL-SQL

4. Create a row level trigger for UPDATE triggering event on emp table which makes the modified data in a same table based on condition.

i.e. if modified data is more than the existing data then salary should be updated else trigger should be fired and should retain the old salary.

SQL> CREATE OR REPLACE TRIGGER TR4

2 BEFORE UPDATE ON EMP

3 FOR EACH ROW

4 BEGIN

5 IF :NEW.SAL<:OLD.SAL THEN

6 :NEW.SAL:=:OLD.SAL;

7 DBMS_OUTPUT.PUT_LINE('INVALID INCREMENT SO RETAINED WITH OLD SALARY');

8 END IF;

9 END;

10 /

Trigger created

5. Create a row level trigger for DELETE triggering event on emp table where a row deleted from dept table, related to that data all the records should be deleted from emp table?

SQL> CREATE OR REPLACE TRIGGER TR5

2 AFTER DELETE ON DEPT

3 FOR EACH ROW

4 BEGIN

5 DELETE FROM EMP WHERE DEPTNO=:OLD.DEPTNO;

6 DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' ROWS ARE DELETED');

79

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 80: PL

COURSE MATERAL- PL-SQL

7 END;

8 /

Trigger created.

DML Triggering Attributes:

INSERTING

UPDATING

DELETING

These attributes will return boolean value. if related operation is performed it returns TRUE else returns with false.

DML_EVNTS

EVNT_NAME DAT

CREATE TABLE DML_EVNTS

(EVNT_NAME VARCHAR2(12),DAT VARCHAR2(50));

SQL> CREATE OR REPLACE TRIGGER TR6

2 AFTER INSERT OR UPDATE OR DELETE

3 ON EMP

4 DECLARE

5 tn VARCHAR2(10);

6 BEGIN

7 IF INSERTING THEN

8 tn:='INSERT';

9 ELSIF UPDATING THEN

80

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 81: PL

COURSE MATERAL- PL-SQL

10 tn:='UPDATE';

11 ELSIF DELETING THEN

12 tn:='DELETE';

13 END IF;

14 INSERT INTO DML_EVNTS VALUES(tn,TO_CHAR(SYSDATE,'DD-MON-YYYY HH24:MI:SS'));

15 END;

16 /

Trigger created.

2. DDL TRIGGERS : These triggers are executed BEFORE / AFTER the DDL operation is performed over a trigger associated table. It includes CREATE,ALTER, TRUNCATE, RENAME,DROP.

Syntax:

CREATE [ OR REPLACE ] TRIGGER trigger_name

BEFORE / AFTER CREATE OR ALTER OR TRUNCATE OR RENAME OR DROP

ON SCHEMA

BEGIN

Trigger Constraint

Trigger Action;

END;

/

DDL Triggering Attributes:

ORA_DICT_OBJ_NAME : This attribute will return object name on which DDL operation is being performed.

81

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 82: PL

COURSE MATERAL- PL-SQL

ORA_DICT_OBJ_TYPE : This attribute will return object type on which DDL operation is being performed.

1. Create a DDL trigger that will restrict to drop emp table?

CREATE OR REPLACE TRIGGER tr7

AFTER DROP ON SCHEMA

BEGIN

IF ORA_DICT_OBJ_NAME='EMP' THEN

RAISE_APPLICATION_ERROR(-20012,'CANT DROP EMP TABLE');

END IF;

END;

NOTE:

TO RESTRICT DROPING OF TABLES:

IF ORA_DICT_OBJ_TYPE='TABLE' THEN

RAISE_APPLICATION_ERROR(-20015,'CANT DROP ANY TABLE');

END IF;

TO RESTRICT DROPING OF OBJECTS:

IF ORA_DICT_OBJ_TYPE='OBJECT' THEN

RAISE_APPLICATION_ERROR(-20015,'CANT DROP ANY TABLE');

END IF;

DISABLE / ENABLE THE TRIGGERS:

The triggers which are created can be disabled and back can be enabled using ALTER TRIGGER command.

SYNTAX:

82

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd

Page 83: PL

COURSE MATERAL- PL-SQL

ALTER TRIGGER trigger_name DISABLE/ENABLE;

DISABLE / ENABLE ALL TRIGGERS:

To disable or enable all the triggers which are created on a table, it is essential that ALTER TABLE command is used.

Syntax:

ALTER TABLE table_name DISABLE / ENABLE ALL TRIGGERS;

ALTER TABLE EMP DISABLE ALL TRIGGERS;

DROPING THE TRIGGERS:

Triggers are dropped automatically whenever a table is dropped.

Triggers can be dropped manually using DROP TRIGGER command.

SYNTAX:

DROP TRIGGER trigger_name;

EXAMPLE:

DROP TRIGGER tr1;

VIEWING THE INFORMATION OF TRIGGERS:

USER_TRIGGERS: This predefined table will provide the information about the triggers like trigger_name, triggering_event, table_name etc.

83

COPY RIGHTS RESERVED FOR PEERS TECHNOLOGIES (P)Ltd