DBMS LAB Programs
DBMS LAB Programs
Q2: Add a column experience to the EMP table. experience numeric null allowed.
Q3: Modify the column width of the job field of EMP table.
Q3: Update the emp table to set the salary of all employees to Rs 50000/- who are working as
AP and lives in Delhi.
Q6. Find the name of employee who lives in Noida and salary more than 80000.
Q7. Find the name of employee and id who lives in Delhi and salary more than 80000 and less
than 100000.
Q6. Find the name of employee whose name has charater “N”.
Q7. Find the name of employee who lives in Noida and salary more than 80000.
Q8. Find the name of employee whose name has started with “M” .
Q9. Find the name of employee whose name has charater “A” at any place.
Q10. Find the name of employee whose name has minimum 4 characters.
Q11. Find the name of employee whose name has more than 4 character.
Q14. Find the name of employee who works in department 11 and live either in Delhi or
Noida.
Q15. Find the name of employee and id who works in live either in Delhi or Noida or
Ghaziabad.
Experiment: 4
d). Find the name of employee having salary more than average salary of all employee.
e). Find the name of employee having salary less than average salary of IT department
employee.
f). Find the name of employee who live in Noida and works in EE department.
g). Find the name and id of employee who works in the same department where KAMAL
works.
h). Find the name and id of employee who lives in the same city where SOHAM lives.
j). Find the name and id of employee who do not lives in NOIDA or DELHI.
k). Find the name and id of department which are not in NOIDA or GHAZIABAD.
l). Find the name and id of employee whose salary lies between 70000 and 9000 and lives in
NOIDA or DELHI.
m). Find the name of employee who lives in NOIDA and earn more the minimum salary of CS
department employee.
o). Display the information of employee in ascending order by name and descending order by
id.
Experiment: 5
c). Display the name of employee who works in CIVIL department but not in CS.
d). Display the name and id of employee who do not works in any department.
e). Display the name of employee who works in CIVIL and IT department.
f). Delete the record of employee who do not work in any department from WORKS.
Experiment: 5
4.
GROUP FUNCTIONS
A group function returns a result based on group of rows.
1. avg - Example: select avg (total) from student;
2. max - Example: select max (percentagel) from student;
2.min - Example: select min (marksl) from student;
4. sum - Example: select sum(price) from product;
COUNT FUNCTION
In order to count the number of rows, count function is used.
1. count(*) – It counts all, inclusive of duplicates and
nulls. Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
2. count(distinct col_name) – It avoids the repeated and null values.
Example: select count(distinct ordid) from order;
GROUP BY CLAUSE
This allows us to use simultaneous column name and group functions.
Example: Select max(percentage), deptname from student group by deptname;
HAVING CLAUSE
This is used to specify conditions on rows retrieved by using group by clause.
Example: Select max(percentage), deptname from student group by deptname having
count(*)>=50;
SPECIAL OPERATORS:
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between / not between – used to find between the ranges
Like / not like – used to do the pattern matching
d) Queries:
Q1: Display all the details of the records whose employee name starts with ‗A‘.
Solution:
1. Use SELECT FROM WHERE syntax. 2. select should include all in the given format.
3. from should include employee 4. where should include condition on empname like „A%‟.
Ans:
SQL> select * from emp where ename like 'A%';
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------
2Arjun ASP 2 15000
5Akalya AP 1 10000
Q2: Display all the details of the records whose employee name does not starts with ‗A‘.
Ans:
SQL> select * from emp where ename not like 'A%';
Dr.N.N.C.E CSE&IT / IV Sem DBMS Lab - LM
d) Result:
Thus the nested Queries and join Queries was performed successfully and executed.
Simple Join
a) Equi-join
Example: select * from item, cust where
item.id=cust.id; b) Non Equi-join
Example: select * from item, cust where item.id<cust.id;
Self join
Example: select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp where
x. deptno =y.deptno);
Outer Join
Example: select ename, job, dname from emp, dept where emp.deptno (+) = dept.deptno;
d) Queries:
Q1: Display all employee names and salary whose salary is greater than minimum salary
of the company and job title starts with ‗M‘.
Solution:
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result.
Ans:
SQL> select ename,sal from emp where sal>(select min(sal) from emp where job like 'A%');
ENAME SAL
-------------------- ----------
Arjun 12000
Gugan 20000
Karthik 15000
Q2: Issue a query to find all the employees who work in the same job as Arjun.
Ans:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
SQL> select ename from emp where job=(select job from emp where ename='Arjun');
ENAME
--------------
Arjun
Gugan
Q3: Issue a query to display information about employees who earn more than any
employee in dept 1.
Ans:
SQL> select * from emp where sal>(select max(sal) from emp where empno=1);
EQUI-JOIN
Q4: Display the employee details, departments that the departments are same in both the
emp and dept.
Solution:
1. Use select from clause. 2. Use equi join in select clause to get the result.
Ans:
SQL> select * from emp,dept where emp.deptno=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- ------------------ ---------- ---------- ---------- ---------- -------------- -------------
1 Mathi AP 1 10000 1 ACCOUNTING NEW YORK
2 Arjun ASP 2 12000 2 RESEARCH DALLAS
3 Gugan ASP 2 20000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 1 ACCOUNTING NEW YORK
NON-EQUIJOIN
Q5: Display the employee details, departments that the departments are not same in both
the emp and dept.
Solution:
1.Use select from clause. 2. Use non equi join in select clause to get the result.
Dr.N.N.C.E CSE&IT / IV Sem DBMS Lab - LM
Ans:
SQL> select * from emp,dept where emp.deptno!=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
---------- -------------------- ---------- ---------- ---------- ------------------------ -------------
2 Arjun ASP 2 12000 1 ACCOUNTING NEW YORK
3 Gugan ASP 2 20000 1 ACCOUNTING NEW YORK
1 Mathi AP 1 10000 2 RESEARCH DALLAS
LEFTOUT-JOIN
Tables used
SQL> select * from stud1;
Regno Name Mark2 Mark3 Result
---------- ----------- ---------- ---------- ---------------------------------------
101 john 89 80 pass
102 Raja 70 80 pass
103 Sharin 70 90 pass
104 sam 90 95 pass
SQL> select * from stud2;
NAME GRA
----------- ----------
john s
raj s
sam a
sharin a
Q6: Display the Student name and grade by implementing a left outer join.
Ans: SQL> select stud1.name,grade from stud1 left outer join stud2 on stud1.name=stud2.name;
Name Gra
----------- ----------
john s
raj s
sam a
sharin a
smith null
RIGHTOUTER-JOIN
Q7: Display the Student name, register no, and result by implementing a right outer join.
Ans:
SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud1.name
= stud2.name;
Name Regno Result
----------- ---------- --------------------------
john 101 pass
raj 102 pass
sam 103 pass
sharin 104 pass
Rollno Name Mark1 Mark2Total
---------- ---------- ---------- ---------- ----------
1 sindu 90 95 185
2 arul 90 90 180
FULLOUTER-JOIN
Q8: Display the Student name register no by implementing a full outer join.
Ans:
SQL> select stud1.name, regno from stud1 full outer join stud2 on (stud1.name= stud2.name);
Name Regno
----------- ----------
john 101
raj 102
sam 103
sharin 104
SELFJOIN
Q9: Write a query to display their employee
names Ans:
SQL> select distinct ename from emp x, dept y where
x.deptno=y.deptno; ENAME
--------------------
Arjun
Gugan
Karthik
Mathi
Q10: Display the details of those who draw the salary greater than the average salary.
Ans:
SQL> select distinct * from emp x where x.sal >= (select avg(sal) from emp);
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
11 kavitha designer 12 17000
e) Result:
Thus the nested Queries and join Queries was performed successfully and executed.
d) Queries:
Q1: Display all the dept numbers available with the dept and emp tables avoiding
duplicates.
Solution:
1. Use select from clause. 2. Use union select clause to get the result.
Ans:
SQL> select deptno from emp union select deptno from dept;
DEPTNO
----------
1
2
12
30
40
Q2: Display all the dept numbers available with the dept and emp tables.
Solution:
1. Use select from clause. 2. Use union all in select clause to get the result.
Ans:
SQL> select deptno from emp union all select deptno from dept;
DEPTNO
----------
1
2
2
1
12
1
2
30
40
9 rows selected.
Q3: Display all the dept numbers available in emp and not in dept tables and vice versa.
Solution:
1. Use select from clause.
2. Use minus in select clause to get the result.
Ans:
SQL> select deptno from emp minus select deptno from dept;
DEPTNO
----------
12
SQL> select deptno from dept minus select deptno from emp;
DEPTNO
----------
30
40
e) Result:
Thus the set operations using DML Commands was successfully performed and executed.
34
WHILE LOOP
Syntax
WHILE condition
LOOP statement1;
statement2;
END LOOP;
Example:
Declare
i number:=0;
j number:=0;
begin
while i<=100 Loop
j := j+i;
i := i+2;
end loop;
dbms_output.put_line(„the value of j is‟ ||
j); end;
/
FOR LOOP
Syntax:
FOR counter IN [REVERSE]
LowerBound..UpperBound
LOOP
statement1;
statement2;
END LOOP;
Example:
Begin
For I in 1..2
Loop
Update emp set field = value where
condition; End loop;
End;
/
Q1: write a pl/SQL program to swap two
numbers c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Declare three variables and read variables through a and b
2 Swap the values of a and b using temporary variables
3 Display the swapped results
d) Program:
SQL>edit
swapping.SQL declare
a number(10);
b number(10);
c number(10);
begin
dbms_output.put_line('THE PREV VALUES OF A AND B WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
35
a:=&a;
b:=&b;
c:=a;
a:=b;
b:=c;
dbms_output.put_line('THE VALUES OF A AND B
ARE'); dbms_output.put_line(a);
dbms_output.put_line(b);
end;
e)output:
SQL> @
swapping.SQL 19 /
Enter value for a: 5
old 6: a:=&a;
new 6: a:=5;
Enter value for b: 3
old 7: b:=&b;
new 7: b:=3;
THE PREV VALUES OF A AND B
WERE 53
THE VALUES OF A AND B
ARE 35
PL/SQL procedure successfully completed.
Q3: write a pl/SQL program to find the total and average of 6 subjects and display the
grade c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Read six numbers and calculate total and average
2 Find whether the student is pass or fail using if statement
3 Find the grade using nested elseif statement
4 Display the Grade, Percentage and Total of the student
d)Program:
SQL> edit
grade.SQL
declare
java number(10);
dbms number(10);
co number(10); se
number(10);
es number(10);
ppl number(10);
total number(10);
avgs number(10);
per number(10);
begin
dbms_output.put_line('ENTER THE
MARKS'); java:=&java;
dbms:=&dbms;
co:=&co;
se:=&se;
es:=&es;
ppl:=&ppl;
total:=(java+dbms+co+se+es+ppl);
per:=(total/600)*100;
if java<50 or dbms<50 or co<50 or se<50 or es<50 or ppl<50 then
dbms_output.put_line('FAIL');
if per>75 then
dbms_output.put_line('GRADE A');
elsif per>65 and per<75 then
dbms_output.put_line('GRADE B');
elsif per>55 and per<65 then
dbms_output.put_line('GRADE C');
else
dbms_output.put_line('INVALID INPUT');
end if;
dbms_output.put_line('PERCENTAGE IS '||per);
dbms_output.put_line('TOTAL IS '||total);
end;
e)output:
SQL> @
grade.SQL 31 /
Enter value for java: 80
old 12: java:=&java;
new 12: java:=80;
Enter value for dbms: 70
old 13: dbms:=&dbms;
new 13: dbms:=70; Enter
value for co: 89 old 14:
co:=&co;
new 14: co:=89;
Enter value for se: 72
old 15: se:=&se; new
15: se:=72; Enter
value for es: 76 old
16: es:=&es; new 16:
es:=76;
Enter value for ppl: 71
old 17: ppl:=&ppl;
new 17: ppl:=71;
GRADE A
PERCENTAGE IS 76
TOTAL IS 458
PL/SQL procedure successfully completed.
38
a:=trunc(a/10);
end loop;
dbms_output.put_line('sum is'|| sum1);
end;
e)output:
SQL> @
sumofdigits.SQL
16 /
a:=&a;
for i in 1..a
loop
if mod(a,i)=0 then
c:=c+1;
end if; end
loop; if
c=2 then
dbms_output.put_line(a ||'is a prime number');
else
dbms_output.put_line(a ||'is not a prime number');
end if;
end;
e)output:
SQL> @
prime.SQL 19 /
Enter value for a: 11
old 6: a:=&a;
new 6: a:=11;
11is a prime number
PL/SQL procedure successfully completed.
Q7: Write a PL/SQL program to find the factorial of a given
number c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Read a number for calculating factorial value.
2 Calculate the factorial of a given number using for loop
3 Display the factorial value of a given number.
d)Program:
SQL>edit
fact.SQL declare
n number;f number:=1;
begin
n:=&n;
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('the factorial is'|| f);
end;
e)output:
SQL> @
fact.SQL 12 /
Enter value for n:
5 old 5: n:=&n;
new 5: a:=5;
the factorial is 120
Q8: 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
c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Create a table named areas with radius and area
2 Initialize values to pi, radius and area
3 Calculate the area using while loop. Display the result.
d)Program:
SQL> create table areas(radius number(10),area number(6,2));
Table created.
PROGRAM
declare
pi constant number(4,2):=3.14;
radius number(5):=3; area number(6,2);
begin
while radius<7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
radius:=radius+1;
end loop;
end;
e)output:
SQL> @ AREAOFCIRCLE.SQL
13 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM AREAS;
RADIUS AREA
---------- ----------
3 28.26
4 50.24
5 78.5
6 113.04
Q9: write a PL/SQL code block that will accept an account number from the user, check if
the users balance is less than minimum balance, only then deduct rs.100/- from the balance.
This process is fired on the acct table.
c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Develop a query to Create the table acct and insert values into them
2 Develop a PL/SQL program to read the account number.
3 Check the balance for the account no. check if the users balance is less than minimum
balance, only then deduct rs.100/- from the balance
4 Update the balance changes into the acct table.
d)Program:
SQL> create table acct(name varchar2(10),cur_bal number(10),acctno number(6,2));
SQL> insert into stud values('&sname',&rollno,&marks);
SQL> select * from acct;
ACCTNO NAME CUR_BAL
---------- ---------- ----------
777 sirius 10000
765 john 1000
855 sam 500
353 peter 800
declare
mano number(5);
mcb number(6,2);
minibal constant number(7,2):=1000.00;
fine number(6,2):=100.00;
begin
mano:=&mano;
select cur_bal into mcb from acct where
acctno=mano; if mcb<minibal then
update acct set cur_bal=cur_bal-fine where
acctno=mano; end if;
end;
e)output:
SQL> @
BANKACC.SQL 13 /
Enter value for mano: 855
old 7: mano:=&mano;
new 7: mano:=855;
PL/SQL procedure successfully completed.
f)Result:
Thus the above creation of PL/SQL programs to implement various types of control
structure was successfully executed.
QUESTIONS AND ANSWERS
1. What is meant by branching in PL/SQL:
Sequence of statements can be executed on satisfying certain condition. If statements are
being used and different forms of if are:
1. Simple IF 2. If then else 3. Else if 4. Nested if
2. What are selection statements?
1. Switch case statement
3. Define iterations IN PL/SQL
Sequence of statements can be executed any number of times using loop construct.
4. Classify the iteration statements `in PL/SQL
It is broadly classified into:
1.Simple Loop
2. For Loop
3. While Loop
Experiment: 9
Title of the Exercise : PROCEDURE AND FUNCTION
Date of the Exercise :
b) PL/SQL syntax:
A procedure is a block that can take parameters (sometimes referred to as arguments) and
be invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this greatly
simplifies maintenance.
Modularized program development:
· Group logically related statements within blocks.
· Nest sub-blocks inside larger blocks to build powerful programs.
· Break down a complex problem into a set of manageable well defined logical modules
and implement the modules with blocks.
PROCEDURES
Syntax :
create or replace procedure <procedure name> (argument {in,out,inout} datatype ) {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
FUNCTIONS
Syntax:
create or replace function <function name> (argument in datatype,……) return datatype {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
Tables used:
SQL> select * from ititems;
ITEMID ACTUALPRICE ORDID PRODID
--------- ----------- -------- ---------
101 2000 500 201
102 3000 1600 202
103 4000 600 202
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(„The updated value is „||a);
6 end;
7 /
The updated value is 8
PL/SQL procedure successfully completed.
Tables used:
SQL>select * from ittrain;
TNO TFARE
--------- ------------
1001 550
1002 600
PROGRAM FOR FUNCTION AND IT‘S EXECUTION
SQL> declare
2 total number;
3 begin
4 total:=trainfn (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7 /
Train fare is Rs.550
PL/SQL procedure successfully completed.
SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
6 dbms_output.put_line(„The factorial of the given number is‟||f);
7 end;
8 /
Step
Details of the step
no.
1 Develop a query to create a table named itstudent2 and insert values into them
2 Develop a procedure p1 with regno, mark1, & mark2 as arguments.
3 Calculate the total and update the total value into the itstudent2 table
d)Program:
SQL> create table itstudent2(regno number(3),name varchar(9),mark1 number(3),mark2
number(3));
Table created.
SQL> insert into itstudent2
2 values(&a,'&b',&c,&d);
Enter value for a: 110
Enter value for b: arun
Enter value for c: 99 Enter value for d: 100
old 2: values(&a,'&b',&c,&d)
new 2: values(110,'arun',99,100)
1 row created.
SQL> /
Enter value for a: 112 Enter value for b: siva Enter value for c: 99 Enter value
for d: 90
old 2: values(&a,'&b',&c,&d)
new 2: values(112,'siva',99,90)
1 row created.
SQL> select * from itstudent2;
REGNO NAME MARK1 MARK2
110 arun 99 100
112 siva 99 90
SQL> alter table itstudent2 add(total number(5)); Table altered.
SQL> select * from itstudent2;
REGNO NAME MARK1 MARK2TOTAL
110 arun 99 100
112 siva 99 90
SQL> create or replace procedure p1(sno number,mark1 number,mark2 number) is
2 tot number(5);
3 begin
4 tot:=mark1+mark2;
5 update itstudent2 set total=tot where regno=sno;
6 end;
7 /
Procedure created.
SQL> declare
2 cursor c1 is select * from itstudent2;
3 rec itstudent2 % rowtype;
4 begin
5 open c1;
6 loop
7 fetch c1 into rec;
8 exit when c1%notfound;
9 p1(rec.regno,rec.mark1,rec.mark2);
10 end loop;
11 close c1;
12 end;
13 /
PL/SQL procedure successfully completed.
e)Output:
SQL> select * from itstudent2;
REGNO NAME MARK1 MARK2TOTAL
--------- --------- ---------- ---------- ----------
110 arun 99 100 199
112 va 99 90 189
Q2: Write a PL/SQL procedure called MULTI_TABLE that takes two numbers as parameter and
displays the multiplication of the first parameter till the second parameter.
Ans.
//p2.SQL
create or replace procedure multi_table (a number, b number) as
mul number;
begin
for i in 1. .b
loop
mul : = a * i;
dbms_output.put_line (a || „*‟ || i || „=‟ ||
mul); end loop;
end;
//pq2.SQL
declare
a number; b number;
begin
a:=&a; b:=&b; multi_table(a,b);
end;
e)Output:
SQL> @p2.SQL;
Procedure created.
SQL> @pq2.SQL;
Enter value for a: 4
old 5: a:=&a; new 5: a:=4;
Enter value for b: 3
old 6: b:=&b; new 6: b:=3;
4*1=4
4*2=8
4*3=12
Q3: Consider the EMPLOYEE (EMPNO, SALARY, ENAME) Table.
Write a procedure raise_sal which increases the salary of an employee. It accepts an employee
number and salary increase amount. It uses the employee number to find the current salary from
the EMPLOYEE table and update the salary.
Ans:
//p3.SQL
create or replace procedure raise_sal( mempno employee . empno % type, msal_percent
number ) as
begin
update employee set salary = salary + salary*msal_percent /100 where empno = mempno;
end;
/
//pq3.SQL
declare
cursor c1 is select * from emp;
rec emp % rowtype;
begin
open c1;
loop
fetch c1 into rec;
exit when c1%notfound;
raisal(rec.empno,10);
end loop;
close
c1; end;
/
e)Output:
SQL> @p3.SQL;
Procedure created.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
SQL> @pq3.SQL;
PL/SQL procedure successfully completed.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ------------- ---------- ----------
1 Mathi AP 1 11000
2 Arjun ASP 2 16500
3 Gugan ASP 1 16500
4 Karthik Prof 2 33000
5 Akalya AP 1 11000
Q4: Write a PL/SQL function CheckDiv that takes two numbers as arguments and returns the
values 1 if the first argument passed to it is divisible by the second argument, else will return the
value 0;
Ans:
//p4.SQL
create or replace function checkdiv (n1 number, n2 number) return number as res
number;
begin
if mod (n1, n2) = 0 then
res := 1;
else
res:= 0;
end if;
return res;
end;
/
//pq4.SQL
declare
a number;
b number;
49
begin
a:=&a; b:=&b; dbms_output.put_line(„result=‟||
checkdiv(a,b)); end;
/
e)Output:
SQL> @p4.SQL;
Function created.
SQL> @pq4.SQL;
Enter value for a: 4
old 5: a:=&a; new 5: a:=4;
Enter value for b: 2
old 6: b:=&b; new 6: b:=2;
result=1
Q5: Write a PL/SQL function called POW that takes two numbers as argument and return
the value of the first number raised to the power of the second .
Ans:
//p5.SQL
create or replace function pow (n1 number, n2 number) return number as
res number;
begin
select power ( n1, n2) into res from dual; return res; end;
or
create or replace function pow (n1 number, n2 number) return number as
res number : =1;
begin
for res in
1..n2 loop
res : = n1 * res;
end loop;
return res;
end;
//pq5.SQL
declare
a number;
b number;
begin
a:=&a; b:=&b;
dbms_output.put_line('power(n1,n2)='||pow(a,b));
end;
/
e)Output:
SQL> @p5.SQL;
Function created.
SQL> @ pq5.SQL;
Enter value for a: 2
old 5: a:=&a; new
5: a:=2; Enter
value for b: 3 old
6: b:=&b; new 6:
b:=3;
power(n1,n2)=8
Q6: Write a PL/SQL function ODDEVEN to return value TRUE if the number passed to it
is EVEN else will return FALSE.
Ans:
//p6.SQL
create or replace function oddeven (n number) return boolean as
begin
if mod (n, 2) = 0 then return true;
else
return false;
end if;
end;
/
//pq6.SQL
declare
a number; b boolean;
begin
a:=&a; b:=oddeven(a);
if b then
dbms_output.put_line('The given number is Even');
else
dbms_output.put_line('The given number is Odd');
end if;
end;
/
e)Output:
SQL> @p6.SQL;
Function created.
SQL> @pq6.SQL;
Enter value for a: 5
old 5: a:=&a; new 5: a:=5;
The given number is Odd
f)Result:
Thus the procedures and function for various operations was developed and executed
successfully.
TYPES OF TRIGGERS
The various types of triggers are as follows,
Before: It fires the trigger before executing the trigger statement.
After: It fires the trigger after executing the trigger statement. For
each row: It specifies that the trigger fires once per row.
For each statement: This is the default trigger that is invoked. It specifies that the trigger
fires once per statement.
VARIABLES USED IN TRIGGERS
:new
:old
These two variables retain the new and old values of the column updated in the database.
The values in these variables can be used in the database triggers for data manipulation
Sytax:
Q1: Create a trigger that insert current user into a username column of an existing table
c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Create a table itstudent4 with name and username as arguments
2 Create a trigger for each row that insert the current user as user name into a table
d)Program:
SQL> create table itstudent4(name varchar2(15),username varchar2(15));
Table created.
SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row
2 declare
3 name varchar2(20);
4 begin
5 select user into name from dual;
6 :new.username:=name;
7 end;
8 /
Trigger created.
e)Output:
SQL> insert into itstudent4 values('&name','&username');
Enter value for name: akbar
Enter value for username: ranjani
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('akbar','ranjani')
1 row created.
SQL> /
Enter value for name: suji
Enter value for username: priya
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('suji','priya')
1 row created.
SQL> select * from itstudent4;
NAME USERNAME
--------------- ---------------
akbar SCOTT
suji SCOTT
Q2: Create a Simple Trigger that does not allow Insert Update and Delete Operations on
the Table
d)Program:
Table used:
SQL> select * from itempls;
ENAME EID SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500
Trigger:
SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
3 raise_application_error(-20010,'You cannot do manipulation');
4 end;
5
6/
Trigger created.
e)Output:
SQL> insert into itempls values('aaa',14,34000);
insert into itempls values('aaa',14,34000)
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
d)Program:
Table used:
SQL> select * from itempls;
ENAME EID SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500
Trigger:
SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsal itempls.salary%type;
4 begin
5 select salary into triggsal from itempls where eid=12;
6 if(:new.salary>triggsal or :new.salary<triggsal) then
7 raise_application_error(-20100,'Salary has not been changed');
8 end if;
9 end;
10 /
Trigger created.
e)Output:
SQL> insert into itempls values ('bbb',16,45000);
insert into itempls values ('bbb',16,45000)
*
ERROR at line 1:
ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
SQL> update itempls set eid=18 where ename='zzz';
update itempls set eid=18 where ename='zzz'
*
ERROR at line 1:
ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
f)Result:
Thus the creation of triggers for various events such as insertion, updation, etc., was
performed and executed successfully.
1. What is the need for triggers? Or List the requirements needed to design a trigger.
Specifying when a trigger is to be executed.
Specify the actions to be taken when the trigger executes.
2. What is trigger?
Triggers are statements that are executed automatically by the system as the side effect of
a modification to the database. The triggers can be initiated before the event or after the
event.
Experiment: 11
Title of the Exercise : FRONT END TOOLS
Date of the Exercise :
OBJECTIVE (AIM) OF THE EXPERIMENT
To study about various Java (front end) tools
FACILITIES REQUIRED AND PROCEDURE
a) Facilities required to do the experiment:
Sl.No. Facilities required Quantity
1 System 1
2 Operating System Windows XP
3 S/W Name Java
b) Procedure
Object
• An object is a type of user interface element you create on a Java form by using a toolbox
control.
• In fact, in Java, the form itself is also an object.
• You can move, resize, and customize objects by setting object properties.
• A property is a value or characteristic held by a Java object, such as Caption or Fore
Color.
• Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.
Object. Property = Value
• Where
Object is the name of the object you‟re customizing.
Property is the characteristic you want to change.
Value is the new property setting.
• For example,
Command1.Caption = "Hello"
1.The Form Object
• The Form is where the user interface is drawn. It is central to the development of Java
applications.
• Form Properties:
o Appearance Selects 3-D or flat appearance.
o BackColor Sets the form background color.
o BorderStyle Sets the form border to be fixed or sizeable.
o Caption sets the form window title.
o Enabled If True, allows the form to respond to mouse and keyboard events;
if False, disables form.
o Font Sets font type, style, size.
o ForeColor Sets color of text or graphics.
o Picture Places a bitmap picture in the form.
o Visible If False, hides the form.
• Form Events:
• Activate Form_Activate event is triggered when form becomes the active window.
• Click Form_Click event is triggered when user clicks on form.
• DblClick Form_DblClick event is triggered when user doubleclicks on form.
• Load Form_Load event occurs when form is loaded.This is a good place to
initialize variables and set any runtime properties.
• Form Methods:
• Cls Clears all graphics and text from form. Does not clear any objects.
• Print Prints text string on the form.
• Examples
frmExample.Cls ' clears the form
frmExample.Print "This will print on the form"
2. CommandButton
• The Command Button control is use to create buttons with a variety of uses on a form.
• A command button is the most basic way to get user input while a program is running.
• By clicking a command button, the user requests that a specific action be taken in the
program.
• Java terms, clicking a command button creates an event, which must be
processed in your program.
• Command Button Properties:
• Appearance Selects 3-D or flat appearance.
• Cancel Allows selection of button with Esc key (only one button on a form can
have this property True).
• Caption String to be displayed on button.
• Default Allows selection of button with Enter key (only one button on a form can
have this property True).
• Font Sets font type, style, size.
• Command Button Events:
• Click Event triggered when button is selected either by clicking on it or by pressing the
access key.
3. Label Boxes
• Label, the simplest control in the Java toolbox, displays formatted text on a user
interface form. Typical uses for the Label control include:
• Help text
• Program splash screen headings
• Formatted output, such as names, times, and dates
• Descriptive labels for other objects, including text boxes and list boxes.
• Label Properties:
• Alignment Aligns caption within border.
• Appearance Selects 3-D or flat appearance.
• AutoSize -If True, the label is resized to fit the text specified by the caption property. If
False, the label will remain the size defined at design time and the text may be clipped.
• BorderStyle Determines type of border.
• Caption String to be displayed in box.
• Font Sets font type, style, size.
• Label Events:
• Click Event triggered when user clicks on a label.
• DblClick Event triggered when user double-clicks on a label.
4. Textbox
• A Textbox is used to display information entered at design time, by a user at run-time, or
assigned within code.
• The displayed text may be edited.
• The Textbox control is one of the most versatile tools in the Java toolbox.
• This control performs two functions:
• Displaying output (such as operating instructions or the contents of a file) on a form.
• Receiving text (such as names and phone numbers) as user input.
• Text Box Properties:
1. Appearance : Selects 3-D or flat appearance.
2. BorderStyle : Determines type of border.
3. Font : Sets font type, style, size.
4. MaxLength : Limits the length of displayed text (0 value indicates unlimited length).
5. MultiLine : Specifies whether text box displays single line or multiple lines.
6. PasswordChar :Hides text with a single character.
7.ScrollBars :Specifies type of displayed scroll bar(s).
8.SelLength :Length of selected text (run-time only).
9. SelStart :Starting position of selected text (run-time only).
10.SelText :Selected text (run-time only).
11.Tag : Stores a string expression.
12.Text :Displayed text
• Text Box Events:
1. Change :Triggered every time the Text property changes.
2. LostFocus :Triggered when the user leaves the text box. This is a good place to
examine the contents of a text box after editing.
3. KeyPress :Triggered whenever a key is pressed. Used for key trapping, as seen in last class.
5. Check Boxes
• Check boxes provide a way to make choices from a list of potential candidates.
• Some, all, or none of the choices in a group may be selected
• Check Box Properties:
• Caption :Identifying text next to box.
• Font :Sets font type, style, size.
• Value :Indicates if unchecked (0, vbUnchecked), checked (1,vbChecked), or grayed
out (2, vbGrayed).
• Check Box Events:
• Click :Triggered when a box is clicked. Value property is automatically changed by
Java.
6. Option Buttons
• Option buttons provide the capability to make a mutually exclusive choice among a
group of potential candidate choices.
• Hence, option buttons work as a group, only one of which can have a True (or selected)
value.
• Option Button Properties:
• Caption :Identifying text next to button.
• Font :Sets font type, style, size.
• Value :Indicates if selected (True) or not (False). Only one option button in a group
can be True. One button in each group of option buttons should always be initialized to
True at design time.
7. List Boxes
• A list box displays a list of items from which the user can select one or more items.
• If the number of items exceeds the number that can be displayed, a scroll bar is
automatically added.
• List Box Properties:
1. Appearance :Selects 3-D or flat appearance.
2. List :Array of items in list box.
3. ListCount :Number of items in list.
4. ListIndex :The number of the most recently selected item in list.If no item is
selected, ListIndex = -1.
5. MultiSelect :Controls how items may be selected (0-no multiple selection allowed,
1-multiple selection allowed, 2-group selection allowed).
6. Selected :Array with elements set equal to True or False, depending on whether
corresponding list item is selected.
7. Sorted :True means items are sorted in 'Ascii' order, else items appear in order added.
8. Text : Text of most recently selected item.
• List Box Events:
• Click :Event triggered when item in list is clicked.
• DblClick :Event triggered when item in list is double-clicked.Primary way used to
process selection.
• List Box Methods:
• AddItem :Allows you to insert item in list.
• Clear :Removes all items from list box.
• RemoveItem :Removes item from list box, as identified by index of item to remove.
• Examples
• lstExample.AddItem "This is an added item" ' adds text string to list
• lstExample.Clear ' clears the list box
• lstExample.RemoveItem 4 ' removes lstExample.List(4) from list box
8.Combo Boxes
• The combo box is similar to the list box.
• The differences are a combo box includes a text box on top of a list box and only allows
selection of one item.
• In some cases, the user can type in an alternate response.
• Combo Box Properties:
• Combo box properties are nearly identical to those of the list box, with the deletion of the
MultiSelect property and the addition of a Style property.
• Appearance Selects 3-D or flat appearance.
• List Array of items in list box portion.
• ListCount Number of items in list.
• ListIndex The number of the most recently selected item in list.If no item is
selected, ListIndex = -1.
• Sorted True means items are sorted in 'Ascii' order, else items appear in order added.
• Style Selects the combo box form.Style = 0, Dropdown combo; user can
change selection.Style = 1, Simple combo; user can change selection. Style = 2,
Dropdown combo; user cannot change selection.
• Text Text of most recently selected item.
• Combo Box Events:
• Click Event triggered when item in list is clicked.
• DblClick Event triggered when item in list is double-clicked. Primary way used to
process selection.
• Combo Box Methods:
• AddItem Allows you to insert item in list.
• Clear Removes all items from list box.
• RemoveItem Removes item from list box, as identified by index of item to remove.
• Examples
• cboExample.AddItem "This is an added item" ' adds text string to list
• cboExample.Clear ' clears the combo box
• cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box
9.Horizontal and Vertical Scroll Bars
• Horizontal and vertical scroll bars are widely used in Windows applications.
• Scroll bars provide an intuitive way to move through a list of information and make
great input devices.
• Scroll Bar Properties:
1. LargeChange Increment added to or subtracted from the scroll bar Value property
when the bar area is clicked.
2. Max The value of the horizontal scroll bar at the far right and the value of the
vertical scroll bar at the bottom.Can range from -32,768 to 32,767.
3. Min The other extreme value - the horizontal scroll bar at the left and the
vertical scroll bar at the top. Can range from -32,768 to 32,767.
4. SmallChange The increment added to or subtracted from the scroll bar Value property
when either of the scroll arrows is clicked.
5. Value The current position of the scroll box (thumb) within the scroll bar. If you
set this in code, Java moves the scroll box to the proper position.
10.Picture Boxes
• The picture box allows you to place graphics information on a form.
• It is best suited for dynamic environments - for example, when doing animation.
• Picture boxes lie in the top layer of the form display.
• They behave very much like small forms within a form, possessing most of the
same properties as a form.
• Picture Box Properties:
1. AutoSize If True, box adjusts its size to fit the displayed graphic.
2. Font Sets the font size, style, and size of any printing done in the picture box.
3. Picture Establishes the graphics file to display in the picture box.
Picture Box Events:
Click Triggered when a picture box is clicked.
DblClick Triggered when a picture box is double-clicked.
• Example
• picExample.Picture = LoadPicture("c:\pix\sample.bmp")
11. Frames
• Frames provide a way of grouping related controls on a form. And, in the case of option
buttons, frames affect how such buttons operate.
• Option buttons within a frame work as a group, independently of option buttons in other
frames.
• Option buttons on the form, and not in frames, work as another independent group.
• That is, the form is itself a frame by default.
• It is important to note that an independent group of option buttons is defined by physical
location within frames, not according to naming convention.
• That is, a control array of option buttons does not work as an independent group just
because it is a control array.
• It would only work as a group if it were the only group of option buttons within a frame
or on the form.
12.Shape Tool
• The shape tool can create circles, ovals, squares, rectangles, and rounded squares
and rectangles.
• Colors can be used and various fill patterns are available.
• Shape Tool Properties:
1. BackColor Determines the background color of the shape (only used when FillStyle
not Solid.
2. BackStyle Determines whether the background is transparent or opaque.
3. BorderColor Determines the color of the shape's outline.
4. BorderStyle Determines the style o the shape's outline. The border can be
transparent, solid, dashed, dotted, and combinations.
5. BorderWidth Determines the width of the shape border line.
6. fillColor Defines the interior color of the shape.
7. FillStyle Determines the interior pattern of a shape. Some choices are: solid,
transparent, cross, etc.
8. Shape Determines whether the shape is a square, circle, or some other choice.
13. The Line Control
• Like the shape control, the line control is a graphical control.
• Line is use it to display horizontal, vertical, or diagonal lines in a form.
• We can use these controls at design time as a design element or at runtime to alter the
original line you drew.
• It can also change a line at runtime by changing its X1, X2, Y1, and Y2 properties.
• Line Tool Properties:
• BorderColor Determines the line color.
• BorderStyle Determines the line 'shape'. Lines can be transparent, solid, dashed,
dotted,and combinations.
• BorderWidth Determines line width.
14.The Timer Control
• You use a timer control when you want to execute code at specific intervals.
• Many times, especially in using graphics, we want to repeat certain operations at regular
intervals.
• The timer tool allows such repetition. The timer tool does not appear on the form
while the application is running.
• The Timer Properties:
• Enabled Used to turn the timer on and off. When on, it continues to operate
until the Enabled property is set to False.
Interval Number of milliseconds between each invocation of the Timer Event
c) Result:
Thus the study of various Java tools was done.
2 In the form use the front end tools in the toolbox like textbox, label, and command button
and create a front end Design for the simple calculator.
Open the properties window for the tools and select properties. Now the properties
window is opened. Set properties for each tool in the form like caption, name, etc.
Delete the default values of the text box
3 Double click each and every tool to open the project code window. write the
code for the events of the tools
4 Double click the buttons and write the code for buttons
Write the code for the simple operations in the calculator like Addition, subtraction,
5 multiplication and division. The code is Automatically compiled at the end of each line while
pressing the Enter key.
Now execute the code by click the F5 button in the keyboard or select
7 Run--->start.
After successfully executing the project create the executable file by Select
the option file---> make file.exe.
f) Program:
Private Sub Command1_Click()
Text3.Text = Val(Text1.Text) + Val(Text2.Text)
End Sub
g) Output:
h) Result:
Thus the design and implementation of a form using Java was performed.