Dbms Lab Record
Dbms Lab Record
Engineering
DATABASE MANAGEMENT
SYSTEMS
(Integrated Course) Lab Manual
(INT18R371)
StudentName :
RegisterNumber :
Section :
1
TABLE OF CONTENTS
1 Bonafide Certificate
Experiments
8 BUILDIN FUNCTIONS
11 CURSORS
12 TRIGGERS
13 EXCEPTION HANDLING
2
SCHOOL OF COMPUTING
BONAFIDE CERTIFICATE
StaffIn-charge HeadoftheDepartment
REGISTER NUMBER
InternalExaminer ExternalExaminer
3
EXPERIMENT EVALUATION SUMMARY
Name: RegNo:
Class: Faculty:
Marks Faculty
S.No Date Experiment (100) Signature
1 DATA DEFINITION LANGUAGE
2 DATA MANIPULATION LANGUAGE
3 TCL & DCL COMMANDS
USAGE OF SET OPERATORS AND
4.a SUBQUERIES
CURSORS
8
TRIGGERS
9
10 EXCEPTION HANDLING
4
Ex. No.: 1
DATA DEFINITION LANGUAGE
Date:
COMMANDS
1)Implementing NOT NULL and primaray key
SQL> create table customer_details2(
2 cust_id number(5) CONSTRAINT Nnull1 NOT NULL,
3 cust_last_name varchar2(20) CONSTRAINT Nnull2 NOT NULL,
4 cust_mid_name varchar2(4),
5 cust_first_name varchar2(20),
6 account_no number(5) CONSTRAINT Pkey10 PRIMARY KEY,
7 acccount_type varchar2(10) CONSTRAINT Nnull3 NOT NULL,
8 bank_branch varchar2(25) CONSTRAINT Nnull4 NOT NULL,
9 cust_email varchar2(30)
10 );
Table created.
5
SQL> create table project5(
2 project_id number(3) CONSTRAINT Pkey11 PRIMARY KEY,
3 project_name varchar2(20),
4 project_location varchar2(22)
5 );
Table created.
SQL> create table employee5(
2 employee_id number(6) CONSTRAINT Pkey12 PRIMARY KEY,
3 employee_first_name varchar2(20),
4 employee_email varchar2(35),
5 grade number(2),
6 project_no number(3) CONSTRAINT Fkey13 references project5(project-ID)
7 );
Table created.
5)Alter
SQL> ALTER TABLE customer_details2
2 ADD phone_no char(10);
Table altered.
7)Drop table
8)Truncate table
SQL>Truncate table customer_details2;
Table truncated.
6
Ex. No.:2
DATA MANIPULATION LANGUAGE
Date:
Command
1)Single row insert with values for all columns
SQL> insert into customer_details2
values(55,'roshan','s','abilesh',6548,'savings','tsi','ahfhfhggh',9790625551);
1 row created.
2)Inserting one row,few columns at a time
SQL>insert into customer_details2(cust_id,cust_last_name,cust_mid_name,cust_first_name)
values (107,’Robert’,’b’,’Dan’);
1 row created.
3)Inserting NULL value into a column
SQL> insert into customer_details(customer_id,cust_last_name) values(108,NULL);
1 row created.
4)Inserting many rows form a different table
SQL>insert into old
cust_dtails(account_no,transaction_date,total_available_balance_in_dollars)select
account_no,transaction_date,total_available_balance from customer_transaction where
total_available_balance>1000;
1 row created.
5)Deleting all rows
SQL>delete form customer_details2;
Table deleted.
6)Deleting a specific rows
SQL> DELETE FROM customer_details2 WHERE cust_id=55;
1 row deleted.
7)Updating all rows
SQL> UPDATE customer_details2 SET phone_no=9991112872;
1 row updated.
7
102 2312
8
Ex. No.: 3
TCL & DCL COMMANDS
Date:
Table created.
2. add constraints,(a) primary key for access_no (b)unique for book_name (c)check for
price>100
SQL> alter table library add constraint keyp1 primary key (access_no);
Table altered.
Table altered.
Table altered.
SQL>insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a_nam
e',&access_no,'&price_no','&publisher','&edition');
Enter value for b_name: visualjava++
Enter value for a_name: veningston
9
Enter value for access_no: 112233
Enter value for price_no: 500
Enter value for publisher: janet
Enter value for edition: 3rd
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('visualjava++
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C00592) violated
1 row created.
SQL> /
Enter value for b_name: visualc++
Enter value for a_name: beningston
Enter value for access_no: 223344
Enter value for price_no: 400
Enter value for publisher: nirmal
Enter value for edition: 3rd
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('visualc++','
ERROR at line 1:
ORA-00001: not null constraint(SCOTT.SYS_C00592) violated
1 row created.
SQL> /
Enter value for b_name: java++
Enter value for a_name: viningston
Enter value for access_no: 334455
Enter value for price_no: 490
Enter value for publisher: vinu
Enter value for edition: 1st
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into library(b_name,a_name,access_no,price_no,publisher,edition)values('java+
+','vin
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C00593) violated
1 row created.
10
SQL>select count(book_name)from library;
COUNT(BOOK_NAME)
----------------
3
5. Display the highest and the lowest price book
MAX(PRICE)
----------
500
MIN(PRICE)
----------
400
SQL> commit;
Commit complete.
11
Savepoint created.
1 row deleted.
12
Ex. No.: 4.a)
Usage of set operators and subqueries
Date:
13
1 row created.
ENROLLMENT HOUSE_NO
---------- ---------
a0001 80
a0002 18
a0003 20
a0004 30
s0001 18
s0002 14
s0003 23
s0004 24
8 rows selected.
6)List out the enrollment_no & phone_no which are in student_details but not in
staff_details.
SQL> select enrollment_no,house_no from studentdetails minus select enrollment_no,house_no
from staf
fdetails;
14
ENROLLMENT HOUSE_NO
---------- ---------
s0001 18
s0002 14
s0003 23
s0004 24
7)List out the enrollment_no & phone_no which are in staff_details but not in
student_details:
SQL> select enrollment_no,house_no from staffdetails minus select enrollment_no,house_no
from stude
ntdetails;
ENROLLMENT HOUSE_NO
---------- ---------
a0001 80
a0002 18
a0003 20
a0004 30
8)List out the house_no which are present both in staff & student_details.
SQL> select house_no from staffdetails intersect select house_no from studentdetails;
HOUSE_NO
---------
18
9)List out the student house_no and enrollement who are participating in MTA and NSS
activity
HOUSE_NO ENROLLMENT
---------------------------------------
18 s0001
14 s0002
23 s0003
24 s0004
10)give the unique house_no,enrollment of the students participating in NSS
15
HOUSE_NO ENROLLMENT
--------- ----------
18 s0001
23 s0003
11)Give the enrollment_no of the students who are in MTA but not in NSS
SQL> select enrollment_no from studentdetails where enrollment_no in(select enrollment_no
from activ
ity where activity not in'NSS'and activity in 'MTA');
ENROLLMENT
----------
s0002
ENROLLMENT
----------
s0001
s0002
s0003
13)List out enrollment_no of the students who are final years having CGPA>8
ENROLLMENT
----------
s0001
s0002
s0003
16
Ex. No.: 4.b)
Usage of set operators and subqueries
Date:
EXERCISE:
1. create a tablestaff_details with the following fields
enrollment_nodesignation,salary,house_no.
CREATE TABLE staff_details (
enrollment_no INTEGER PRIMARY KEY,
designation TEXT NOT NULL,
salary TEXT NOT NULL,
TEXT NOT NULL,
phone_no TEXT NOT NULL
);
3.Insert at least 4 rows of values in staff_details and student_details.
i.
INSERT INTO staff_details VALUES (200000001, 'staff manager', '150000', '45-
A22gv','90000404256');
INSERT INTO staff_details VALUES (300000002, 'accountant', '100000','54-
B33hc' ,'90004000678');
17
INSERT INTO staff_details VALUES (400000003, 'vice chairman', '250000','12-
Df45f','98765434333');
INSERT INTO staff_details VALUES (600000003, ' chairman', '550000','12-
D44eg','98765443233');
INSERT INTO staff_details VALUES (900000006, 'account manager', '200000','42-
D45as','98765432222');
ii.
18
5)List out the enrollment_no & house_no together in staff_details & student_details (union)
SELECT enrollment_no,house_no FROM staff_details where salary > 100000 UNION SELECT
enrollment_no,house_no FROM student_details where cgpa >= 7;
6)List out the enrollment_no & phone_no which are in student_details but not in staff_details.(USING
Minus)
SELECT enrollment_no,phone_no from staff_details WHERE phone_no not in (SELECT
enrollment_no
FROM staff_details);
7) List out the enrollment_no & phone_no which are in staff_details but not in Student_details:
SELECT enrollment_no, house_no FROM staff_details WHERE phone_no not in (SELECT
enrollment_no
FROM staff_details);
19
8)List out the house_no which are present both in staff & student_details. (intersect)
SELECT house_no FROM staff_details WHERE house_no in (SELECT house_no FROM
student_details);
ff &
****output is empty because no common house_no in staf &student_details.******
9)List out the student house_no and enrollement who are participating in MTA and NSS activity (sub query)
select distinct house_no,enrollment_no from student_details where enrollment_no in (select *
from nss) and (enrollment_no in (select * from mta));
Output:
Enrollment_no
______________________
10)give the unique house_no,enrollment of the students participating in NSS(sub query)
select distinct house_no,enrollment_no from student_details where enrollment_no in (select *
from nss);
Output:
Enrollment_no
______________________
20
Ex. No.: 5
Buildin functions
Date:
SQL has many built-in functions for performing processing on string or numeric data. Following is the list of all useful SQL
built-in functions –
SQL COUNT Function - The SQL COUNT aggregate function is used to count the number of rows in a database
table.
SQL MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum) value for a
certain column.
SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain
column.
SQL AVG Function - The SQL AVG aggregate function selects the average value for certain table column.
SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric column.
SQL SQRT Functions - This is used to generate a square root of a given number.
SQL RAND Function - This is used to generate a random number using SQL command.
SQL CONCAT Function - This is used to concatenate any string inside any SQL command.
Syntax:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Syntax:
SELECT MAX(column_name)
FROM table_name
WHERE condition;
21
SQL MIN Function :
Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
22
SQL SUM Function:
Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Syntax:
SELECT SQRT(64);
Syntax:
SELECT RAND();
23
SQL CONCAT Function :
Syntax:
CONCAT(string1, string2, ...., string_n)
24
PL/SQL
What is PL/SQL?
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of
SQL.
Oracle PL/SQL is an extension of SQL language, designed for seamless processing of
SQL statements enhancing the security, portability, and robustness of the database. This
PL/SQL online programming course explains some important aspect of PL SQL
language like block structure, data types, packages, triggers, exception handling, etc.
PL/SQL is not case sensitive so you are free to use lower case letters or upper case
letters except within string and character literals.
Anonymous Block
Function
Library
Procedure
25
Package Body
Package Specification
Trigger
Type
Type Body
Each PL/SQL program consists of SQL and PL/SQL statements which from a
PL/SQL block.
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword
DECLARE. This section is optional and is used to declare any placeholders like
variables, constants, records and cursors, which are used to manipulate data in the
execution section. Placeholders may be any of Variables, Constants and Records,
which stores data temporarily. Cursors are also declared in this section.
Execution Section:
26
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN
and ends with END. This is a mandatory section and is the section where the
program logic is written to perform any task. The programmatic constructs like loops,
conditional statement and SQL statements form the part of execution section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in
this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block
contains exceptions that cannot be handled, the Block terminates abruptly with
errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL
blocks can be nested within other PL/SQL blocks. Comments can be used to
document code.
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
DBMS_OUTPUT :
Eg:
dbms_output.put_line('Hello Reader!');
27
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data temporarily during
the execution of code. It helps you to manipulate data in PL/SQL programs. It is nothing except
a name given to a storage area. Each variable in the PL/SQL has a specific data type which
defines the size and layout of the variable's memory.
A variable should not exceed 30 characters. Its letter optionally followed by more letters, dollar
signs, numerals, underscore etc.
variable_name datatype := value;
Example:
Radius Number := 5;
Date_of_birth date;
Declaration Restrictions:
o Forward references are not allowed i.e. you must declare a constant or
variable before referencing it in another statement even if it is a declarative
statement.
val number := Total - 200;
Total number := 1000;
28
o
The first declaration is illegal because the TOTAL variable must be declared
before using it in an assignment expression.
o Variables belonging to the same datatype cannot be declared in the same
statement.
N1, N2, N3 Number;
It is an illegal declaration.
1. counter binary_integer := 0;
2. greetings varchar2(20) DEFAULT 'Hello JavaTpoint';
29
Example:
DECLARE
a integer := 30;
b integer := 40;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
Value of c: 70
Value of f: 33.333333333333333333
PL/SQL Constants
A constant is a value used in a PL/SQL block that remains unchanged throughout the program.
It is a user-defined literal value. It can be declared and used instead of actual values.
1. constant_name CONSTANT datatype := VALUE;
o Constant_name:it is the name of constant just like variable name. The constant
word is a reserved word and its value does not change.
o VALUE: it is a value which is assigned to a constant when it is declared. It can not
be assigned later.
30
Example of PL/SQL constant
Let's take an example to explain it well:
1. DECLARE
2. -- constant declaration
3. pi constant number := 3.141592654;
4. -- other declarations
5. radius number(5,2);
6. dia number(5,2);
7. circumference number(7, 2);
8. area number (10, 2);
9. BEGIN
10. -- processing
11. radius := 9.5;
12. dia := radius * 2;
13. circumference := 2.0 * pi * radius;
14. area := pi * radius * radius;
15. -- output
16. dbms_output.put_line('Radius: ' || radius);
17. dbms_output.put_line('Diameter: ' || dia);
18. dbms_output.put_line('Circumference: ' || circumference);
19. dbms_output.put_line('Area: ' || area);
20. END;
21. /
After the execution of the above code at SQL prompt, it will produce the following
result:.
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53
Pl/SQL procedure successfully completed.
31
Control Statements
PL/SQL If
PL/SQL supports the programming language features like conditional statements and iterative
statements. Its programming constructs are similar to how you use in programming languages
like Java and C++.
1. IF condition
2. THEN
3. Statement: {It is executed when condition is true}
4. END IF;
This syntax is used when you want to execute statements only when condition is TRUE.
1. IF condition
2. THEN
3. {...statements to execute when condition is TRUE...}
4. ELSE
5. {...statements to execute when condition is FALSE...}
6. END IF;
This syntax is used when you want to execute one set of statements when condition is TRUE or a
different set of statements when condition is FALSE.
1. IF condition1
2. THEN
3. {...statements to execute when condition1 is TRUE...}
4. ELSIF condition2
5. THEN
6. {...statements to execute when condition2 is TRUE...}
32
7. END IF;
This syntax is used when you want to execute one set of statements when condition1 is TRUE or
a different set of statements when condition2 is TRUE.
1. IF condition1
2. THEN
3. {...statements to execute when condition1 is TRUE...}
4. ELSIF condition2
5. THEN
6. {...statements to execute when condition2 is TRUE...}
7. ELSE
8. {...statements to execute when both condition1 and condition2 are FALSE...}
9. END IF;
1. DECLARE
2. a number(3) := 500;
3. BEGIN
4. -- check the boolean condition using if statement
5. IF( a < 20 ) THEN
6. -- if condition is true then print the following
7. dbms_output.put_line('a is less than 20 ' );
8. ELSE
9. dbms_output.put_line('a is not less than 20 ' );
10. END IF;
11. dbms_output.put_line('value of a is : ' || a);
12. END;
33
PL/SQL Case Statement
The PL/SQL CASE statement facilitates you to execute a sequence of satatements based on a
selector. A selector can be anything such as variable, function or an expression that the CASE
statement checks to a boolean value.
The CASE statement works like the IF statement, only using the keyword WHEN. A CASE
statement is evaluated from top to bottom. If it get the condition TRUE, then the corresponding
THEN calause is executed and the execution goes to the END CASE clause.
1. CASE [ expression ]
2. WHEN condition_1 THEN result_1
3. WHEN condition_2 THEN result_2
4. ...
5. WHEN condition_n THEN result_n
6. ELSE result
7. END case
1. DECLARE
2. grade char(1) := 'A';
3. BEGIN
4. CASE grade
5. when 'A' then dbms_output.put_line('Excellent');
6. when 'B' then dbms_output.put_line('Very good');
7. when 'C' then dbms_output.put_line('Good');
8. when 'D' then dbms_output.put_line('Average');
9. when 'F' then dbms_output.put_line('Passed with Grace');
10. else dbms_output.put_line('Failed');
11. END CASE;
12. END;
After the execution of above code, you will get the following result:
Excellent
PL/SQL procedure successfully completed.
34
PL/SQL Loop
The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.
1. LOOP
2. Sequence of statements;
3. END LOOP;
1. LOOP
2. Sequence of statements;
3. END LOOP;
1. LOOP
2. statements;
3. EXIT;
4. {or EXIT WHEN condition;}
5. END LOOP;
35
Example of PL/SQL EXIT Loop
Let's take a simple example to explain it well:
1. DECLARE
2. i NUMBER := 1;
3. BEGIN
4. LOOP
5. EXIT WHEN i>10;
6. DBMS_OUTPUT.PUT_LINE(i);
7. i := i+1;
8. END LOOP;
9. END;
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL Exit Loop.
36
Syntax of while loop:
1. WHILE <condition>
2. LOOP statements;
3. END LOOP;
1. DECLARE
2. i INTEGER := 1;
3. BEGIN
4. WHILE i <= 10
5. LOOP
6. DBMS_OUTPUT.PUT_LINE(i);
7. i := i+1;
8. END LOOP;
9. END;
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
PL/SQL for loop is used when when you want to execute a set of statements
for a predetermined number of times. The loop is iterated between the start
and end integer values. The counter is always incremented by 1 and once
the counter reaches the value of end integer, the loop ends.
37
Syntax of for loop:
1. FOR counter IN initial_value .. final_value
2. LOOP
3. LOOP statements;
4. END LOOP;
o initial_value : Start integer value
1. BEGIN
2. FOR k IN 1..10 LOOP
3. -- note that k was not declared
4. DBMS_OUTPUT.PUT_LINE(k);
5. END LOOP;
6. END;
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL WHILE Loop.
o You don't need to declare the counter variable explicitly because it is declared implicitly in the declaration section.
o The counter variable is incremented by 1 and does not need to be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done often.
1. DECLARE
2. VAR1 NUMBER;
3. BEGIN
38
4. VAR1:=10;
5. FOR VAR2 IN 1..10
6. LOOP
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8. END LOOP;
9. END;
Output:
10
20
30
40
50
60
70
80
90
100
1. DECLARE
2. VAR1 NUMBER;
3. BEGIN
4. VAR1:=10;
5. FOR VAR2 IN REVERSE 1..10
6. LOOP
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8. END LOOP;
9. END;
Output:
100
90
80
70
60
50
40
30
20
10
39
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
1. CREATE OR REPLACE PROCEDURE procedure_name
2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
40
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];
Table creation:
1. create table user(id number(10) primary key,name varchar2(100));
Procedure Code:
1. create or replace procedure "INSERTUSER" (id IN NUMBER, name IN VARCHAR2)
2. is
3. begin
4. insert into user values(id,name);
5. end;
6. /
Output:
Procedure created.
1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /
Now, see the "USER" table, you will see one record is inserted.
41
ID Name
101 Rahul
1. DROP PROCEDURE procedure_name;
DROP PROCEDURE pro1;
Ex: 6
1. a)create a table “billcalculator” containing
house_no,c_name,previous_reading,current_reading,unit,amount.
b)calculate and update the field units and amount with pl/sql as follows.
Calculate the units by using formulas.
i)if the unit >150 then amount is 100+unit*1.5.
ii)if the unit >50 and unit <50 then amount is 50+unit*0.5
else unit is multiplied with factor 0.5
Write a procedure which updates unit and amount.
PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference
between procedure and a function is, a function must always return a value, and
on the other hand a procedure may or may not return a value. Except this, all the
other things of PL/SQL procedure are true for PL/SQL function too.
1. CREATE [OR REPLACE] FUNCTION function_name [parameters]
2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]
3. RETURN return_datatype
4. {IS | AS}
5. BEGIN
6. < function_body >
7. END [function_name];
42
Here:
1. create or replace function adder(n1 in number, n2 in number)
2. return number
3. is
4. n3 number(8);
5. begin
6. n3 :=n1+n2;
7. return n3;
8. end;
9. /
1. DECLARE
2. x number(2);
3. BEGIN
4. x := adder(11,22);
5. dbms_output.put_line('Addition is: ' || x);
6. END;
7. /
Output:
Addition is: 33
43
Statement processed.
0.05 seconds
Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the maximum of two values.
1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;
17. END;
18. BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24. END;
25. /
Output:
44
Maximum of (23,45): 45
Statement processed.
0.02 seconds
Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers
table.
Customers
Create Function:
1. CREATE OR REPLACE FUNCTION totalCustomers
2. RETURN number
3. IS
4. total number(2) := 0;
5. BEGIN
6. SELECT count(*) into total FROM customers;
7. RETURN total;
8. END;
9. /
After the execution of above code, you will get the following result.
Function created.
45
While creating a function, you have to give a definition of what the function has to do. To use a function, you will have to call
that function to perform the defined task. Once the function is called, the program control is transferred to the called
function.
After the successful completion of the defined task, the call function returns program control back to the main program.
To call a function you have to pass the required parameters along with function name and if function returns a value then
you can store returned value. Following program calls the function totalCustomers from an anonymous block:
1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();
5. dbms_output.put_line('Total no. of Customers: ' || c);
6. END;
7. /
After the execution of above code in SQL prompt, you will get the following result.
46
Ex. No.: 6
PL / SQL basic programs
Date:
Exercises:
1. WRITE A PL/SQL PROGRAM TO SWAP TWO NUMBERS WITH OUT
TAKING THIRD VARIABLE
2. WRITE A PL/SQL PROGRAM TO FIND THE LARGEST OF TWO NUMBERS
3. WRITE A PL/SQL PROGRAM TO FIND THE TOTAL AND AVERAGE OF 6
SUBJECTS AND DISPLAY THE GRADE.
4. WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN
NUMBER IS AN ARMSTRONG NUMBER OR NOT
5. WRITE A PL/SQL PROGRAM TO FIND THE SUM OF DIGITS IN A GIVEN
NUMBER.
6. WRITE A PL/SQL PROGRAM TO DISPLAY THE NUMBER IN REVERSE
ORDER.
7. WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN
NUMBER IS PRIME OR NOT
8. WRITE A PL/SQL PROGRAM TO FIND THE FACTORIAL OF A GIVEN
NUMBER
9. WRITE A PL/SQL PROGRAM TO GENERATE FIBONACCI SERIES
10. WRITE A PL/SQL CODE BLOCK TO CALCULATE THE AREA OF A CIRCLE
FOR A VALUE OF RADIUS VARYING FROM 3 TO 7.
STORE THE RADIUS AND THE CORRESPONDING VALUES OF CALCULATED
AREA IN AN EMPTY TABLE NAMED AREAS ,CONSISTING OF TWO COLUMNS
RADIUS & AREA
QUERIES:
1)
declare
a NUMBER;
b NUMBER;
begin
a := 100;
b := 300;
dbms_output.Put_line('Before');
dbms_output.Put_line('a= ' || a ||' b = ' || b);
a := a + b;
b := a - b;
a := a - b;
dbms_output.Put_line('After');
47
dbms_output.Put_line(' a = ' || a ||' b = ' || b);
End;
2)
DECLARE
a NUMBER :=40 ;
b NUMBER := 20;
BEGIN
if(a>b) then
dbms_output.Put_line('max number is '||a);
else
dbms_output.Put_line('max number is '||b);
end if;
END;
3)
DECLARE
48
sub6 NUMBER := 50;
sumOf6 NUMBER;
avgOf6 NUMBER;
grade char(1);
BEGIN
sumOf6 := sub1+sub2+sub3+sub4+sub5+sub6;
END;
4)
declare
n number:=407;
49
s number:=0;
r number;
len number;
m number;
begin
m:=n;
len:=length(to_char(n));
while n>0
loop
r:=mod(n,10);
s:=s+power(r,len);
n:=trunc(n/10);
end loop;
if m=s
then
dbms_output.put_line('armstrong number');
else
dbms_output.put_line('not armstrong number');
end if;
End;
5)
DECLARE
n INTEGER;
temp_sum INTEGER;
r INTEGER;
BEGIN
n := 123456;
temp_sum := 0;
WHILE n <> 0 LOOP
50
r := MOD(n, 10);
temp_sum := temp_sum + r;
n := Trunc(n / 10);
END LOOP;
END;
6)
DECLARE
num number;
reverse_num number:=0;
begin
num:=98765;
while num>0
loop
reverse_num:=(reverse_num*10) + mod(num,10);
num:=trunc(num/10);
end loop;
51
7)
declare
n number;
i number;
temp number;
begin
n := 13;
i := 2;
temp := 1;
for i in 2..n/2
loop
if mod(n, i) = 0
then
temp := 0;
exit;
end if;
end loop;
if temp = 1
then
dbms_output.put_line('prime');
else
dbms_output.put_line('not prime');
end if;
End;
52
8)
declare
num number := 5;
fact number := 1;
temp number;
begin
temp := num;
while( temp>0)
loop
fact := fact*temp;
temp := temp-1;
end loop;
dbms_output.Put_line('factorial of ' || num || ' is ' || fact);
end;
9)
declare
a number :=0;
b number :=1;
temp number;
n number := 10;
53
i number;
begin
dbms_output.Put_line('fibonacci series is : ');
dbms_output.Put_line(a);
dbms_output.Put_line(b);
for i in 2..n
loop
temp := a+b;
a := b;
b := temp;
dbms_output.Put_line(temp);
end loop;
End;
10)
Declare
radius number;
area number;
begin
for radius in 3..7
loop
area :=3.14*radius*radius;
insert into circle(radius,area)values(radius,area);
end
loop;
54
end;
/
select * from circle;
55
Ex. No.: 7
PROCEDURES AND FUNCTIONS.
Date:
Table created.
1 row created.
SQL> /
Enter value for house_no: 20
Enter value for c_name: raj
Enter value for prev_rding: 50
Enter value for curr_rding: 250
Enter value for unit:
56
Enter value for amount:
old 1: insert into bill_calc
values('&house_no','&c_name','&prev_rding','&curr_rding','&unit','&
new 1: insert into bill_calc values('20','raj','50','250','','')
1 row created.
2.)a)calculate and update the field units and amount with pl/sql as follows.
Calculate the units by using formulas.
i)if the unit >150 then amount is 100+unit*1.5.
ii)if the unit >50 and unit <50 then amount is 50+unit*0.5
else unit is multiplied with factor 0.5
Write a procedure which updates unit and amount.
57
7 calculate(d.house_no,d.prev_rding,d.curr_rding);
8 end loop;
9 end;
10 /
SQL> /
Enter value for item_id: 2
Enter value for item_desc: colgate
Enter value for bal_stock: 200
old 1: insert into item_master values('&item_id','&item_desc','&bal
new 1: insert into item_master values('2','colgate','200')
1 row created.
58
Enter value for quantity: 23
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('1','hamam','23')
1 row created.
SQL> /
Enter value for item_id: 2
Enter value for item_desc: colgate
Enter value for quantity: 78
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('2','colgate','78')
1 row created.
SQL> /
Enter value for item_id: 3
Enter value for item_desc: ponds
Enter value for quantity: 45
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('3','ponds','45')
1 row created.
SQL> /
Enter value for item_id: 4
Enter value for item_desc: lizol
Enter value for quantity: 12
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('4','lizol','12')
1 row created.
59
SQL> create or replace function iii(itemsid varchar2) return number
2 is
3 cursor c1 is select item_id from item_master;
4 d c1%rowtype;
5 begin
6 for d in c1
7 loop
8 if(d.item_id=itemsid)then
9 return 0;
10 end if;
11 end loop;
12 return 1;
13 end;
14 /
Function created.
declare
itid item_master.item_id%type;
iteid item_buyed.item_id%type;
balst item_master.bal_stock%type;
quant item_buyed.quantity%type;
itemdesc item_buyed.item_desc%type;
itemdeesc item_master.item_desc%type;
cursor c is select item_id,item_desc,bal_stock from item_master;
cursor d is select item_id,item_desc,quantity from item_buyed;
retval number;
begin
retval:=0;
open d;
open c;
fetch c into itid,itemdeesc,balst;
loop
fetch d into iteid,itemdesc,quant;
retval:=iii(iteid);
if(retval=0)then
update item_master set bal_stock=balst+quant where item_id=iteid;
else if(retval=1)then
insert into item_master values(iteid,itemdesc,quant);
end if;
end if;
exit when(d% notfound);
end loop;
60
close d;
close c;
end;
/
61
Ex. No.: 8
Cursors
Date:
PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area known as context area. A
cursor is a pointer to this context area. It contains all information needed for processing the
statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains information on
a select statement and the rows of data accessed by it.
Use of Cursor:
The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike
the SQL commands which operate on all the rows in the result set at one time. Cursors are used
when the user needs to update records in a singleton fashion or in a row by row manner, in a
database table.
A cursor is used to referred to a program to fetch and process the rows returned by the SQL
statement, one at a time. There are two types of cursors:
o Implicit Cursors
o Explicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed,
if you don't use an explicit cursor for the statement.
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the
cursor attributes tell whether any rows are affected and how many have been affected. If you run
a SELECT INTO statement in PL/SQL block, the implicit cursor attribute can be used to find out
whether any row has been returned by the SELECT statement. It will return an error if there no
data is selected.
The following table specifies the status of the cursor with each of its attribute.
62
Attribute Description
63
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000
Let's execute the following program to update the table and increase salary of each customer by
5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows affected:
Create procedure:
1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that the rows are updated.
1. select * from customers;
ID NAME AGE ADDRESS SALARY
64
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000
The Explicit cursors are defined by the programmers to gain more control over the context area.
These cursors should be defined in the declaration section of the PL/SQL block. It is created on a
SELECT statement which returns more than one row.
CURSOR cursor_name IS select_statement;;
Steps:
You must follow these steps while working with an explicit cursor.
It defines the cursor with a name and the associated SELECT statement.
1. CURSOR name IS
2. SELECT statement;
65
2) Open the cursor:
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.
1. OPEN cursor_name;
It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:
FETCH cursor_name INTO variable_list;
It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.
Close cursor_name;
Explicit cursors are defined by programmers to gain more control over the context area. It is
defined in the declaration section of the PL/SQL block. It is created on a SELECT statement
which returns more than one row.
Let's take an example to demonstrate the use of explicit cursor. In this example, we are using the
already created CUSTOMERS table.
66
5 Alex 21 Paris 28000
Create procedure:
Execute the following program to retrieve the customer name and address.
1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15. END;
16. /
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
67
Ex. No.: 9
Triggers
Date:
Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired
when some events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
68
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
Example: 1
create or replace trigger trig1 after insert on item_master for each row
declare
begin
dbms_output.put_line('***User has created a row***');
end;
/
Trigger created.
Example 2
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
69
| 6 | Komal | 22 | MP | 4500.00 |
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
Ex. No.: 10
EXCEPTION HANDLING
70
An exception is an error which disrupts the normal flow of program instructions.
PL/SQL provides us the exception block which raises the exception thus
helping the programmer to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL
1. User defined exception.
2. System defined exceptions.
QUERY:
DECLARE
c_id customers.id%type := 6;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
71