a
Transcript of a
PageNo:
EXERCISE 1
ASSIGNMENT 1:
AIM: Creating tables(Using Constraints while creating tables).
Syntax:
CREATE TABLE <Table_Name>
(
Column_Name1 <datatype> [Default exp] [Constraints],
Column_Name2 <datatype> [Default exp] [Constraints],
.
.
Column_NameN <datatype> [Default exp] [Constraints].
[Table Constraints….]
);
Examples:
1) Create Sailors Table
SQL> CREATE TABLE sailors
(
sid NUMBER(10),
sname VARCHAR2(15) NOT NULL,
rating NUMBER(3) NOT NULL,
age NUMBER(3,1) NOT NULL,
PRIMARY KEY (sid)
);
SQL> DESC sailors;
Output:
Table Colum n Data Type Le ngth Prec isi on Scale P rimary Key Nul lable Default Com me nt
SAILORS SI D Numbe r - 10 0 1 - - -
SNAME Varc har2 15 - - - - -
RATI NG Numbe r - 3 0 - - -
AGE Numbe r - 3 0 - - -
2) Create Boats Table
SQL> CREATE TABLE boats (
bid NUMBER(10),
color VARCHAR2(15),
bname VARCHAR2(15),
PRIMARY KEY(bid) );
Date:
PageNo:
SQL> DESC boats;
Table Colum n Data T ype Le ngth P rec ision Scale Primary K ey Nul lable Default Comme nt
BOATS BID Number - 10 0 1 - - -
COLOR Varchar2 15 - - - - -
BNAME Varchar2 15 - - - - -
2) Create Reserves Table
SQL> CREATE TABLE reserves (
sid NUMBER(10),
bid NUMBER(10),
day DATE,
PRIMARY KEY(sid,bid,day),
FOREIGN KEY(sid) REFERENCES sailors(sid),
FOREIGN KEY(bid) REFERENCES boats(bid) );
Output:
Table Column Data Type Le ngt h Prec ision Scale P rimary Key Nul lable Defaul t Comme nt
RESERVES SID Number - 10 0 1 - - -
BID Number - 10 0 2 - - -
DAY Date 7 - - 3 - - -
ASSIGNMENT 2:
AIM: Altering tables.
Syntax:
ALTER TABLE Table_Name
[ADD (column specification)]
[MODIFY (column specification)]
[DROP constraintsname [CASCADE]| column [CASCADE CONSTRAINTS]]
[DROP UNUSED COLUMN [column]]
[SET UNUSED column]
[ENABLE | DISABLE constraint=name];
Examples:
1) Add a new column
SQL> ALTER TABLE boats ADD (email VARCHAR2(30));
SQL> DESC boats;
PageNo:
Output:
Tabl e Column Data Type Length Precision Scale Primary Key Nullable Default Comment
BOATS BID Number - 10 0 1 - - -
COLOR Varchar2 15 - - - - -
BNAME Varchar2 15 - - - - -
EMAIL Varchar2 30 - - - - -
2) Modify a column
SQL> ALTER TABLE boats MODIFY (email VARCHAR2(40) );
SQL> DESC boats;
Output:
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
BOATS BID Number - 10 0 1 - - -
COLOR Varchar2 15 - - - - -
BNAME Varchar2 15 - - - - -
EMAIL Varchar2 40 - - - - -
3) Drop a column
SQL> ALTER TABLE boats DROP (email);
Output:
Table Column Data Type Length Precision Scale Primary Key Nullable Default Comment
BOATS BID Number - 10 0 1 - - -
COLOR Varchar2 15 - - - - -
BNAME Varchar2 15 - - - - -
EMAIL Varchar2 40 - - - - -
ASSIGNMENT 3:
AIM: Droping of tables.
Syntax:
DROP TABLE Table_Name[CASCADE CONSTRAINTS];
Examples:
1) Drop a table
SQL > DROP TABLE boats;
Table droped
ASSIGNMENT4
AIM: Inserting rows into tables or create records in tables.
Syntax: INSERT INTO <table_name> (col1,col2,…..,col n) VALUES (val1,val2,…..,valn);
PageNo:
Example:
1) Inserting Rows in to sailors table:
SQL> INSERT INTO sailors(sid,sname,rating,age) VALUES(22,’dustin’,7,45.0);
SQL> INSERT INTO sailors(sid,sname,rating,age) VALUES(29,’brutus’,1,33.0);
:
:
SQL> INSERT INTO sailors(sid,sname,rating,age) VALUES(95,’bob’,3,63.5);
SQL> SELECT * FROM sailors;
Output:
SID SNAM E RATING AGE
22 dustrin 7 45
29 brutus 1 33
31 lubber 8 55
32 andy 8 25
68 rusty 10 35
69 horako 7 35
71 zorba 9 16
74 horation 3 35
85 art 7 25
95 bob 3 63
2) Inserting Rows in to boats table:
SQL > INSERT INTO boats(bid,bname,color) VALUES (101,’interlake’,’blue’);
SQL > INSERT INTO boats(bid,bname,color) VALUES (102,’interlake’,’red’);
SQL > INSERT INTO boats(bid,bname,color) VALUES (103,’clipper’,’green’);
SQL > INSERT INTO boats(bid,bname,color) VALUES (104,’marine’,’red’);
SQL> SELECT * FROM boats;
Output:
BID BNAM E COLOR
101 interlake blue
102 interlake red
103 clipper green
104 marine red
3) Inserting Rows in to reserves table:
SQL> INSERT INTO reserves(sid,bid,day) VALUES(22,101,’10/oct/98’);
SQL> INSERT INTO reserves(sid,bid,day) VALUES(22,102,’10/oct/98’);
:
SQL> INSERT INTO reserves(sid,bid,day) VALUES(74,103,’09/aug/98’);
SQL> SELECT * FROM reserves;
PageNo:
Output:
SID BID DAY
22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
31 102 11-OCT-98
31 103 11-JUN-98
31 104 11-DEC-98
64 101 09-MAY-98
64 102 09-AUG-98
74 103 09-AUG-98
ASSIGNMENT 5:
AIM: selecting data from tables by using select command.
Syntax:
SELECT < list of attributes > from <List of Table_Names> where <condition>;
Examples:
1) Find the names and ages of sailors?
Solution:
SQL> select sname,age from sailors;
Output:
SNAM E AGE
dustrin 45
brutus 33
lubber 55
andy 25
rusty 35
horako 35
zorba 16
horation 35
art 25
Bob 63
2) Find all sailors with a rating above 7?
Solution:
SQL> select sname from sailors where rating>7;
Output:
SNAM E
lubber
andy
rusty
zorba
PageNo:
3) Find the names of sailors who are reserved boat no. 103?
Solution:
SQL> select sname from sailors,reserves where bid=103 and sailors.sid=reserves.sid;
Output:
4) Find the sid’s of sailors who have reserved a red boat?
Solution:
SQL> select sid from reserves,boats where boats.color='red' and boats.bid=reserves.bid;
Output:
SID
22
31
31
64
5) Find the snames of sailors who have reserves a red boat?
Solution:
SQL> select sname from sailors,reserves,boats where boats.color='red' and reserves.bid=boats.bid and
sailors.sid=reserves.sid;
Output:
5) Find the color of boat reserved by the sailor 'lubber'?
Solution:
SQL> select color from sailors,reserves,boats where sailors.sname='lubber' and reserves.bid=boats.bid
and sailors.sid=reserves.sid;
Output:
SNAM E
dustin
lubber
horitean
PageNo:
EXCERSICE-2
ASSIGNMENT 1:
AIM:Queries(along with sub queries) using any,all,in,exists,not exists,union,intersect,except,constraints.
Syntax:
UNION: <Query1> UNION <Query2> INTERSECT: <Query1> INTERSECT <Query2> MINUS: <Query1> MINUS <Query2> ANY: <Query> IN (<Sub Query>) ALL: <Query> ALL (<Sub Query>) IN: <Query> IN (<Sub Query>) NOT IN: <Query> NOT IN (<Sub Query>) EXISTS: <Query> EXISTS (<Sub Query>) NOT EXISTS: <Query> NOT EXISTS (<Sub Query>
Examples
IN:
1) Find the names of sailors who have reserved boat no is 103?
Solution:
select sname from sailors where sid in (select sid from reserves where bid=103);
Output:
NOT IN:
2) Find the names of sailors who have not reserved boat no is 103?
Solution:
select sname from sailors where sid not in (select sid from reserves where bid=103);
Date:
PageNo:
Output:
INTERSECT:
3) Find the names of sailors who are reserves both red and green boats?
Solution:
SQL> select sname from sailors s,boats b,reserves r where b.color='red' and s.sid=r.sid and r.bid =b.bid
intersect
select sname from sailors s ,boats b,reserves r where b.color='green' and s.sid=r.sid and r.bid=b.bid;
Output:
UNION:
4) Find the names of sailors who are reserves red or green boats?
Solution:
select sname from sailors s,boats b,reserves r where b.color='red' and s.sid=r.sid and r.bid =b.bid
union
select sname from sailors s ,boats b,reserves r where b.color='green' and s.sid=r.sid and r.bid=b.bid;
Output:
PageNo:
MINUS:
5) Find the names of sailors who are reserves red boat but not green boat?
Solution:
select sname from sailors s,boats b,reserves r where b.color='red' and s.sid=r.sid and r.bid =b.bid
minus
select sname from sailors s ,boats b,reserves r where b.color='green' and s.sid=r.sid and r.bid=b.bid;
Output:
PageNo:
EXCERSICE-3
ASSIGNMENT 1:
AIM: Queries using Aggregate functions.
Syntax:
AVG:
AVG([DISTINCT/ALL]n);
COUNT:
COUNT (*/[DISTINCT/ALL]expr);
SUM:
SUM([DISTINCT/ALL]n);
MAX:
MAX([DISTINCT/ALL]expr);
MIN:
MIN([DISTINCT/ALL]expr);
Examples:
SOURCE TABLE:
SID SNAME RATING AGE
22 dustrin 7 45
29 brutus 1 33
31 lubber 8 55
32 andy 8 25
68 rusty 10 35
69 horako 7 35
71 zorba 9 16
74 horation 3 35
85 art 7 25
95 bob 3 63
1) Find the average age of sailors with a rating of 7?
Solution:
SQL> SELECT avg(age)as avg
FROM sailor s
WHERE rating=7;
Output:
Date:
PageNo:
2) Find the number of different sailors names?
Solution:
SQL>SELECT count(distinct s.sname)as count
FROM sailors s;
Output:
COUNT
10
3) Find total rating in sailors table?
Solution:
SQL>SELECT sum(rating)as ttl_rating
FROM sailors;
Output:
4) Find the name and age of the oldest sailor?
Solution:
SQL> SELECT s.sname,s.age
FROM sailors s
WHERE s.age=(SELECT MAX(s1.age) FROM sailors s1);
Output:
SNAME AGE
bob 63
5) Find the names of sailors who are older than the oldest sailor with a rating of 10?
Solution:
SQL> SELECT MIN(age)AS min_age
FROM sailors WHERE rating=10;
Output:
PageNo:
ASSIGNMENT 2:
AIM: Queries using group clause.
Syntax:
SELECT columns FROM table(s)
[WHERE condition]
[GROUP BY expr,[expr]…]
[HAVING condition]
[ORDER BY expr]
Examples:
1)Find the number of sailors for each rating?
Solution:
SQL> SELECT rating,COUNT(*)No_Of_sailors
FROM sailors
GROUP BY rating;
Output:
2) Find the rating having at least two sailors?
Solution:
SQL> SELECT rating,COUNT(*)No_Of_sailors
FROM sailors
GROUP BY rating
HAVING COUNT (*)>1;
Output:
PageNo:
3) Find the age of youngest sailor for each rating level?
Solution:
SQL> select min(age),rating from sailors group by rating;
Output:
ASSIGNMENT 3:
AIM: Queries for creating and dropping views.
Syntax for create a view:
CREATE OR REPLACE VIEW<view_name>[attribute,[attribute,[…]]]AS<sql query>;
Syntax for delete a view:
DROP VIEW<view_name>;
Examples:
1) Create a view for referring the attributes sid and sname in sailors table.
Solution:
SQL> CREATE OR REPLACE VIEW sailors_view
AS (SELECT sid,sname FROM sailors);
Output:
View created.
To display the content of view:
Query:
SELECT * FROM sailors_view;
PageNo:
Output:
SID SNAME
22 dustrin
29 brots
31 lubber
32 andy
68 rusty
69 horako
71 zorba
74 horation
85 art
95 bob
2) Write a query for deleting the above view.
Solution:
SQL>DROP VIEW sailors_view;
Output: View Dropped.
To display the content of view:
Query:
SQL>SELECT * FROM sailors-view;
Output:
ORA-00942: table or view does not exist
PageNo:
EXCERSICE-4
ASSIGNMENT 1:
AIM: Write Queries using conversion functions.
Syntax:
TO_CHAR function:
Syntax: TO_CHAR(Number,Format,’nlsparam’)
TO_NUMBER function:
TO_NUMBER(char,format,’nlsparam’);
TO_date function:
TO_DATE(char,format,’nlsparam’);
Examples:
1.Convert the number 10012 to character?
Solution:
SQL> SELECT TO_CHAR(10012) FROM DUAL;
Output:
2. Convert the system date FROM date to character of the form ‘dd-mon-yyyy’?
Solution:
SQL> SELECT TO_CHAR(SYSDATE,'dd-mm-yyyy') FROM DUAL;
Output:
3.Convert the character ‘1002’ to number?
Solution:
SQL> SELECT TO_NUMBER(‘1002’) FROM DUAL;
Output:
4. Convert the date 05-march-2009 to ‘DD-MON-YYYY’ format;
Solution:
SQL> SELECT TO_DATE (’05-MAR-2009’,’DD-MON-YYYY’) FROM DUAL;
Output:
Date:
PageNo:
ASSIGNMENT 2:
AIM: Write Queries using string functions.
Syntax:
LOWER(Column/Exception)
LPAD(col/Expr,m)
RPAD(col/expr,m)
UPPER(Column/Exception)
INITCAP (Column/Exception)
SUBSTR(Col/Expr,m,n)
LENGTH (Col/expr)
INSTR (Column/Expr,Char)
LTRIM (char,set)
RTRIM (char,set)
CONCAT(Col/expr,Col/Expr)
Examples:
SQL> SELECT LOWER (‘KA USHIK COLLEGE OF ENGINEERINGISNO.1’) FROM DUAL;
Output:
SQL> SELECT UPPER (‘kaUShik college OF ENgINeeRING is No.1’) FROM DUAL;
Output:
SQL> SELECT CONCAT(‘KAUSHIKCOLLEGE’,’OF ENGINEERING’) FROM DUAL;
Output:
SQL> SELECT LPAD (‘KAUSHIK COLLEGE OF ENGINEERING’,40,’1’) FROM DUAL;
Output:
PageNo:
SQL> SELECT RPAD (‘KAUSHIKCOLLEGE OF ENGINEERING’,40,’0’) FROM DUAL;
Output:
SQL> SELECT LTRIM ('0102K0AUSHIK','102K') FROM DUAL;
Output:
SQL> SELECT RTRIM (‘KAUSH10K011’,’012’) FROM DUAL;
Output:
SQL> SELECT INIT CAP (‘KAUSHIK COLLEGE OF ENGINEERING’) FROM DUAL;
Output:
SQL> SELECT LENGTH (‘KAUSHIK COLLEGE OF ENGINEERING’) FROM DUAL;
Output:
SQL> SELECT SUBSTR (‘KAUSHIK COLLEGE OF ENGINEERING’,11,20)FROM DUAL;
Output:
SQL> SELECT INSTR ('KAUSHIK COLLEGE OF ENGINEERING','O') FROM DUAL;
Output:
PageNo:
ASSIGNMENT 3:
AIM: Write queries using date functions.
Syntax:
SYSDATE: Displays the current system date.
NEXT_DAY: Display the next given day date FROM given date.
NEXT_DAY(date,’DAY’);
ADD_MONTHS: Add ‘n’ months to the given date.
ADD_MONTHS(date,n);
LAST_DAY : This will displays the last day of the given month.
LAST_DAY(day);
MONTHS_BETWEEN: This will gives the months between two dates.
MONTHS_BETWEEN(date1,date2);
TRUNC : It will truncate the date according to the given date.
TRUNC(Date,’format’);
ROUND: Returns the rounded date according to given format.
ROUND(date,’format’);
TO_CHAR: This function converts the date to character format.
TO_CHAR(date,’format’);
TO_DATE: This function converts the character to date.
TO_DATE(char,’format’);
LEAST: It returns the least day in given dates.
LEAST(date1[,date2[,date2[,. . . .]]]);
GREATEST: It returns the great day in the given dates.
GREATEST(date1[,date2[,date2[,. . . .]]]);
Examples:
SQL> SELECT SYSDATE FROM DUAL;
Output:
SQL> SELECT NEXT_DAY(SYSDATE,’MON’) FROM DUAL;
Output:
PageNo:
SQL> SELECT ADD_MONTHS(SYSDATE,2) FROM DUAL;
Output:
SQL> SELECT LAST_DAY (SYSDATE) FROM DUAL;
Output:
SQL> SELECT MONTHS_BETWEEN(’24-APRIL-2009’,SYSDATE)FROM DUAL;
Output:
SQL> SELECT LEAST(’24-APRIL-2009’,SYSDATE)FROM DUAL;
Output:
SQL> SELECT GREATEST ('20-APRIL-2001',SYSDATE)FROM DUAL;
Output:
SQL> SELECT GREATEST ('26-APRIL-2001',sysdate)FROM DUAL
Output:
PageNo:
SQL> SELECT TO_CHAR(SYSDATE,'dd-mm-yyyy') FROM DUAL;
Output:
SQL> SELECT TO_DATE (’05-MAR-2009’,’DD-MON-YYYY’) FROM DUAL;
Output:
PageNo:
EXERCISE-5
ASSIGNMENT 1:
AIM: Write simple PL/SQL program which includes declaration, executable and exception handling
sections.
Program : Write a PL/SQL program to display the given student details?
Solution:
DECLARE
sname student.name%type;
srollno student.rollno%type;
smarks student.marks%type;
BEGIN
srollno := &srollno;
SELECT rollno,name,marks INTO srollno,sname,smarks FROM student WHERE rollno=srollno;
DBMS_OUTPUT.PUT_LINE('Name : '||sname);
DBMS_OUTPUT.PUT_LINE('Number : '||srollno);
DBMS_OUTPUT.PUT_LINE('Marks : '||smarks);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No Records Found');
END;
Output:-
Date:
PageNo:
PageNo:
ASSIGNMENT 2:
AIM: Write a PL/SQL to insert date into students table use commit, save point; roll back.
Program: Write a PL/SQL to insert new records into student table with savepoints?
Solution:
BEGIN
INSERT INTO student VALUES (529,'kiran', 100);
SAVEPOINT a;
INSERT INTO student VALUES (545,'maunisha', 70);
SAVEPOINT b;
INSERT INTO student VALUES (584,'sushma',100);
SAVEPOINT c;
ROLLBACK TO b;
COMMIT;
END;
Output:-
SQL> select * from student;
PageNo:
EXERCISE-6
AIM: Creation of simple PL/SQL program which includes declaration, executable and exception
handling sections.
Program: Write a PL/SQL to find biggest number for a given three numbers using IF-ELSE statement?
Solution:
DECLARE
a NUMBER;
b NUMBER;
c NUMBER;
BEGIN
a:=&a; b:=&b; c:=&c;
IF ((A>B) AND (A>C)) THEN
DBMS_OUTPUT.PUT_LINE('A IS MAXIMUM');
ELSIF ((B>A) AND (B>C)) THEN
DBMS_OUTPUT.PUT_LINE('B IS MAXIMUM');
ELSE
DBMS_OUTPUT.PUT_LINE('C IS MAXIMUM');
END IF;
END;
Output:-
Date:
PageNo:
AIM: Insert date into students table use commit, save point; roll back in PL/SQL block
Program: Write a PL/SQL to print one, two, three for a given three numbers using CASE statement?
Solution:
DECLARE
num NUMBER;
BEGIN
num := #
CASE
WHEN num = 1 THEN
DBMS_OUTPUT.PUT_LINE('One');
WHEN num = 2 THEN
DBMS_OUTPUT.PUT_LINE('Two');
WHEN num = 3 THEN
DBMS_OUTPUT.PUT_LINE('Three');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Out Of Range!');
END;
Output:-
PageNo:
EXERCISE-7
AIM: Program development using WHILE LOOPs, numeric FOR LOOPs, NESTED LOOPS
using ERROR HANDLING, BUILT-IN exceptions, USER defined exceptions, RAISE-
APPLICATION ERROR.
Program 1: Write PL/SQL to find the sum of N numbers by using WHILE loop?
DECLARE
num NUMBER;
endval NUMBER;
total NUMBER DEFAULT 0;
BEGIN
endval:=&endval;
num:=1;
WHILE (num <= endval) LOOP
total:=total+num;
num:=num+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The sum of first ' || endval ||' is : '||total);
END;
Output:
Date:
PageNo:
Program 2: Write PL/SQL to find the sum of N numbers by using FOR loop?
Solution:
DECLARE
num NUMBER;
total NUMBER;
BEGIN
num:=# total:=0;
FOR i IN 1 .. num LOOP
total:=total+i;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum of first ' || num||' numbers is =:'||total);
END;
Output:
Program 3: Write PL/SQL to print first 3 numbers by using REVERSE FOR loop?
Solution:
BEGIN
FOR i IN REVERSE 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
Output:-
SQL> /
3
2
1
PageNo:
Program 4: Write a PL/SQL program to find the division of two numbers, using Built-In exceptions.
Solution:
DECLARE
a NUMBER;
b NUMBER;
c NUMBER;
BEGIN
a := &a; b := &b;
c := a / b;
DBMS_OUTPUT.PUT_LINE('The value of '|| a || '/' || b ||' is : ' || c);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE ('Divided by Zero is not possible.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('Invalid Inputs!');
END;
Output:-
PageNo:
Program: Write a PL/SQL program to check the marks details, using User Defined exceptions?
Solution:
DECLARE
Invalid_Marks EXCEPTION;
marks NUMBER;
BEGIN
marks := :marks;
IF (marks > 100) OR (marks <0) THEN
RAISE Invalid_Marks;
ELSE
DBMS_OUTPUT.PUT_LINE('Marks : '|| marks);
END IF;
EXCEPTION
WHEN Invalid_Marks THEN
DBMS_OUTPUT.PUT_LINE('Marks are out of range!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Invalid input!');
END;
Output:
PageNo:
Program: Write a PL/SQL program to check the marks details, using RAISE_APPLICATION error?
Solution:
DECLARE
marks NUMBER;
BEGIN
marks := :marks;
IF(marks < 0) THEN
RAISE_APPLICATION_ERROR(-20001, ' Marks Value is less than Zero.');
ELSE
IF (marks > 100) THEN
RAISE_APPLICATION_ERROR(-20002, 'Marks Value is grater than 100.');
ELSE
DBMS_OUTPUT.PUT_LINE('Marks : '|| marks);
END IF;
END IF;
END;
Output:-
PageNo:
EXERCISE-8
AIM: Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
Program1: Write a program to find sum and average of given three numbers, using procedures?
Solution:
Procedure for calculating total:
CREATE OR REPLACE PROCEDURE calTotal(num1 NUMBER,num2 NUMBER,num3 NUMBER)
IS
total NUMBER;
BEGIN
total := num1+num2+num3;
DBMS_OUTPUT.PUT_LINE('The sum of given numnbers is::' || total);
END calTotal;
Run:
Procedure for calculating average:
CREATE OR REPLACE PROCEDURE calAvg (m1 NUMBER,m2 NUMBER,m3 NUMBER) IS
Sum1 NUMBER;
Avg1 NUMBER;
BEGIN
Sum1:=m1+m2+m3;
Avg1:=Sum1/3;
DBMS_OUTPUT.PUT_LINE('The average of given marks is::'|| Avg1);
END calAvg;
Run:
Date:
PageNo:
Main Program:
DECLARE
m1 NUMBER(3);
m2 NUMBER(3);
m3 NUMBER(3);
BEGIN
m1:=&m1;
m2:=&m2;
m3:=&m3;
calTotal(m1,m2,m3);
calAvg(m1,m2,m3);
END;
Output:
PageNo:
Program: Write a PL/SQL program to find sum of two no’s using IN, OUT parameters in procedures?
Procedure:
CREATE OR REPLACE PROCEDURE calSum(A IN NUMBER, B IN NUMBER, C OUT NUMBER)
IS
BEGIN
C := A + B;
END;
Run:
Main Program:
DECLARE
N1 NUMBER;
N2 NUMBER;
result NUMBER;
BEGIN
N1 := &N1;
N2 := &N2;
calSum(N1,N2,result);
DBMS_OUTPUT.PUT_LINE ('Sum is: ' || result);
END;
Output:
PageNo:
Program: Write a PL/SQL program to find the square of the given number using INOUT parameter?
Procedure:
CREATE OR REPLACE PROCEDURE double (num IN OUT NUMBER) IS
BEGIN
num := num * num;
END;
Run:
Main Program:
DECLARE
result number;
BEGIN
result := 7;
DBMS_OUTPUT.PUT_LINE('Before Call result Is: ' || result);
double(result);
DBMS_OUTPUT.PUT_LINE('After Call result Is: ' || result);
END;
Output:
PageNo:
EXERCISE-9
AIM: Programs development using stored functions, invoke functions in SQL statements and
write complex functions.
Program: Write a PL/SQL program to find sum of two no’s using functions?
Function:
CREATE OR REPLACE FUNCTION add_two (A NUMBER,B NUMBER)
RETURN INT IS
BEGIN
RETURN (A + B);
END;
Output:-
Function created.
Main Program:
BEGIN
DBMS_OUTPUT.PUT_LINE(’RESULT IS: ’ || add_two(12,34));
END;
Output:-
SQL> /
RESULT IS: 46
PL/SQL procedure successfully completed.
SQL>
Program: Write a PL/SQL program to print the details of student using functions?
Function:
CREATE OR REPLACE FUNCTION display (regdno student.rollno%type)return number is
srollno student.rollno%type;
sname student.name%type;
ssub1 student.sub1%type;
ssub2 student.sub2%type;
BEGIN
select rollno,name,sub1,sub2 into srollno,sname,ssub1,ssub2 from student where rollno=regdno;
DBMS_OUTPUT.PUT_LINE('Student Rollno= ' || srollno);
Date:
PageNo:
DBMS_OUTPUT.PUT_LINE('Student Name= ' || sname);
DBMS_OUTPUT.PUT_LINE('Student Sub1= ' || ssub1);
DBMS_OUTPUT.PUT_LINE('Student sub2= ' || ssub2);
return 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 0;
END
Output:
Function created.
Main Program:
DECLARE
num student.rollno%type;
ret number;
BEGIN
num := :num;
ret := display(num);
if ret=0 then
DBMS_OUTPUT.PUT_LINE ('data not found');
end if;
END;
Output:-
PageNo:
EXERCISE-10
AIM: Programs development using creation of package specification, package body private
objects, packages and cursors and calling stored packages.
Program: Write a PL?SQL program to perform basic mathematical operations using packages?
Solution:
Package Specification:
CREATE OR REPLACE PACKAGE arthop IS
PROCEDURE adds(a NUMBER,b NUMBER);
PROCEDURE sub(a NUMBER,b NUMBER);
PROCEDURE mul(a NUMBER,b NUMBER);
PROCEDURE DIV(a NUMBER,b NUMBER);
END arthop;
Run Package:
SQL>/
Package created.
Package Body:
CREATE OR REPLACE PACKAGE BODY arthop IS
PROCEDURE adds(a NUMBER,b NUMBER) IS
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE('The addition result is::'||c);
END adds;
PROCEDURE sub(a NUMBER,b NUMBER) IS
c NUMBER;
BEGIN
c:=a-b;
DBMS_OUTPUT.PUT_LINE ('The subtraction result is::' || c );
END sub;
PROCEDURE mul(a NUMBER,b NUMBER) IS
c NUMBER;
BEGIN
c:=a*b;
DBMS_OUTPUT.PUT_LINE('The multiplication result is::'||c);
Date:
PageNo:
END mul;
PROCEDURE DIV(A NUMBER,B NUMBER) IS
c NUMBER;
Div_Zero EXCEPTION;
BEGIN
IF b=0 THEN
RAISE Div_Zero;
ELSE
c:=a/b;
DBMS_OUTPUT.PUT_LINE('The division result is::'||c);
END IF;
EXCEPTION
WHEN Div_Zero THEN
DBMS_OUTPUT.PUT_LINE('b value should be greater than 0');
END div;
END arthop;
Run Package Body:
SQL> /
Package body created.
SQL>
Main Program:
DECLARE
n1 NUMBER;
n2 NUMBER;
n3 NUMBER;
ch NUMBER;
BEGIN
n1 := :n1;
n2 := :n2;
ch := :choise_Add_1_sub_2_mul_3_div_4;
CASE
WHEN ch=1 THEN
arthop.adds(n1,n2);
WHEN ch=2 THEN
arthop.sub(n1,n2);
PageNo:
WHEN ch=3 THEN
arthop.mul(n1,n2);
WHEN ch=4 THEN
arthop.div(n1,n2);
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Invalid Operation or choise');
END;
Output:-
PageNo:
Program: Write a PL?SQL program to add two numbers using packages (function overloading)?
Solution:
Package Specification:
CREATE OR REPLACE PACKAGE rrr IS
PROCEDURE add1(a IN NUMBER,b IN NUMBER,c OUT NUMBER);
FUNCTION add2(a1 NUMBER, b1 NUMBER) RETURN NUMBER;
FUNCTION add2(a1 NUMBER, b1 NUMBER, c1 NUMBER) RETURN NUMBER;
END RRR;
Run Package:
SQL>/
Package created.
Package Body:
CREATE OR REPLACE PACKAGE BODY rrr IS
PROCEDURE add1(a IN NUMBER,b IN NUMBER,c OUT NUMBER) IS
BEGIN
c :=a+b;
END add1;
FUNCTION add2(a1 NUMBER, b1 NUMBER) RETURN NUMBER IS
tot NUMBER;
BEGIN
tot := a1+b1;
RETURN tot;
END add2;
FUNCTION add2(a1 NUMBER, b1 NUMBER, c1 NUMBER) RETURN NUMBER IS
tot NUMBER;
BEGIN
tot := a1+b1+c1;
RETURN tot;
END add2;
END rrr;
Run Package Body:
SQL> /
Package body created.
SQL>
PageNo:
Main Program:
DECLARE
n1 NUMBER;
n2 NUMBER;
n3 NUMBER;
n4 NUMBER;
n5 NUMBER;
BEGIN
n1 := :n1;
n2 := :n2;
rrr.add1(n1,n2,n3);
n4:= rrr.add2(n1,n2);
n5 := rrr.add2(n1,n2,n3)
DBMS_OUTPUT.PUT_LINE(‘Sum of two numbers using procedure = ’ || n3);
DBMS_OUTPUT.PUT_LINE(‘Sum of two numbers using function = ’ || n4);
DBMS_OUTPUT.PUT_LINE(‘Sum of three numbers using function=’ || n5);
END;
Output:
PageNo:
EXERCISE-11
AIM: Develop programs using feature parameters in a CURSOR, FOR UPDATE CURSORS
WHERE CURRENT of clause and CURSOR variables.
Program: Write a PL/SQL program to display one student details by using CURSORS?
Solution:
CREATE OR REPLACE PROCEDURE student_details(no IN student.rollno%type) IS
std_rec student%rowtype;
CURSOR c2 IS SELECT * from student where rollno=no;
BEGIN
OPEN c2;
LOOP
FETCH c2 INTO std_rec;
IF c2%NOTFOUND THEN
EXIT;
END IF;
DBMS_OUTPUT.PUT_LINE(‘Name = ‘ || std_rec.name);
DBMS_OUTPUT.PUT_LINE(‘RollNo = ‘ || std_rec.rollno);
DBMS_OUTPUT.PUT_LINE(‘Sub1 marks = ‘ || std_rec.sub1);
DBMS_OUTPUT.PUT_LINE(‘Sub2 marks = ‘ || std_rec.sub2);
CLOSE c2;
END;
Run:
SQL> /
Procedure created.
SQL>
Main Program:
DECLARE
no INTEGER(5);
BEGIN
no:=&no;
student_details(no);
END;
Date:
PageNo:
Output:
Program: Write a PL/SQL program to display all the student details by using CURSORS?
Solution:
CREATE OR REPLACE PROCEDURE student_details IS
std_rec student%rowtype;
CURSOR c2 IS SELECT * from student;
i number;
BEGIN
OPEN c2;
i :=1;
LOOP
FETCH c2 INTO std_rec;
IF c2%NOTFOUND THEN
EXIT;
END IF;
DBMS_OUTPUT.PUT_LINE('-----Student ' ||i||' Details ------');
DBMS_OUTPUT.PUT_LINE('Name = ' || std_rec.name);
DBMS_OUTPUT.PUT_LINE('RollNo = ' || std_rec.rollno);
DBMS_OUTPUT.PUT_LINE('Sub1 marks = ' || std_rec.sub1);
DBMS_OUTPUT.PUT_LINE('Sub2 marks = ' || std_rec.sub2);
i := i+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('');
DBMS_OUTPUT.PUT_LINE('Total ' || c2%rowcount || ' Students are found in the DataBase ');
CLOSE c2;
END;
PageNo:
Run :
SQL> /
Procedure created.
SQL>
Main Program:
DECLARE
BEGIN
student_details();
END;
Output:
PageNo:
EXERCISE-12
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
Program: Create a trigger before insert on student table and check for valid marks which is inserted.
Solution:
CREATE OR REPLACE TRIGGER check_marks BEFORE INSERT ON student FOR EACH ROW
BEGIN
IF :NEW.sub1<0 OR :NEW.sub2<0 THEN
RAISE_APPLICATION_ERROR(-20003,'Marks are less than ZERO');
ELSIF :NEW.sub1>100 OR :NEW.sub2>100 THEN
RAISE_APPLICATION_ERROR(-20003,'Marks are greater than 100');
END IF;
END
Run:
SQL> /
Trigger created.
SQL>
Output:
Date:
PageNo:
Program: Create a trigger before insert on student table and update total marks.
Solution:
CREATE OR REPLACE TRIGGER add_marks BEFORE INSERT ON student FOR EACH ROW
BEGIN
:NEW.total := :NEW.sub1 + :NEW.sub2;
END;
Run:
SQL> /
Trigger created.
SQL>
Output:
Program: Create a trigger after insert on student table and update std_db_log table with operation?
Solution:
CREATE OR REPLACE TRIGGER insert_std_log AFTER INSERT ON student FOR EACH ROW
BEGIN
INSERT INTO std_db_log VALUES (SYSDATE,USER,'new record inserted');
END;
Run:
SQL> /
Trigger created.
SQL>
PageNo:
Output:
Program: Create a trigger after update on student table and update std_db_log table with operation?
Solution:
CREATE OR REPLACE TRIGGER update_std_log AFTER UPDATE ON student FOR EACH ROW
BEGIN
INSERT INTO std_db_log VALUES (SYSDATE,USER,'record Updated');
END;
Run:
SQL> /
Trigger created.
SQL>
Output:
PageNo:
Program: Create a trigger after delete on student table and update std_db_log table with operation?
Solution:
CREATE OR REPLACE TRIGGER delete_std_log AFTER DELETE ON student FOR EACH ROW
BEGIN
INSERT INTO std_db_log VALUES (SYSDATE,USER,'record deleted');
END;
Run:
SQL> /
Trigger created.
SQL>
Output:
PageNo: