Idbms File
Idbms File
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not null);
Rules:
1. Oracle reserved words cannot be used.
3. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. 2 different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is ‘null’.
ALTER TABLE
Alter command is used to:
1. Add a new column.
3. Modify the existing column definition.
3. To include or drop integrity constraint.
Syntax: alter table tablename add/modify (attribute datatype(size));
Example:
1. Alter table emp add (phone_no char (20));
2. Alter table emp modify(phone_no number (10));
3. ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
DROP TABLE
It will delete the table structure provided the table should be empty.
Example: drop table prog20; Here prog20 is table name
TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained
then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;
Example: Truncate table stud;
DESC
This is used to view the structure of the table.
Example: desc emp;
Name Null? Type
Q2: Add a column experience to the emp table. experience numeric null allowed.
Solution:
1. Learn alter table syntax. 2. Define the new column and its data type.
3. Use the alter table syntax.
Ans:
SQL> alter table emp add(experience number(2));
Table altered.
Q3: Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax. 2. Modify the column width and its data type.
Ans:
SQL> alter table emp modify(job varchar2(12));
Table altered.
SQL> alter table emp modify(job varchar(13));
Table altered.
e) Result:
Thus the data definition language commands was performed and implemented
successfully
c) SQL Commands:
INSERT COMMAND
Inserting a single row into a table:
Syntax: insert into <table name> values (value list)
Example: insert into s values(‘s3’,’sup3’,’blore’,10)
UPDATE COMMAND
Syntax:update tablename set field=values where condition;
Example:Update emp set sal = 10000 where empno=135;
DELETE COMMAND
Syntax: Delete from table where conditions;
Example:delete from emp where empno=135;
d) Queries:
Q1: Insert a single record into dept table.
Solution:
1. Decide the data to add in dept.
2. Add to dept one row at a time using the insert into syntax.
Ans:
SQL> insert into dept values (1,'IT','Tholudur');
1 row created.
Q2: Insert more than a record into emp table using a single insert command.
Ans:
SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename: Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
SQL> /
Enter value for empno: 2
Enter value for ename: Arjun
Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2,'Arjun','ASP',2,12000)
1 row created.
SQL> /
Enter value for empno: 3
Enter value for ename: Gugan
Enter value for job: ASP
Enter value for deptno: 1
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(3,'Gugan','ASP',1,12000)
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working
as ASP
Ans:
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
SQL> update emp set sal=15000 where job='ASP';
2 rows updated.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
Q4: Create a pseudo table employee with the same structure as the table emp and insert
rows into the table using select clauses.
Ans:
SQL> create table employee as select * from emp;
Table created.
SQL> desc employee;
Name Null? Type
EMPNO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(13)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Q5: select employee name, job from the emp table
Ans:
SQL> select ename, job from emp;
ENAME JOB
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
suresh lect
6 rows selected.
Q6: Delete only those who are working as lecturer
Ans:
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
6 suresh lect 1 8000
6 rows selected.
SQL> delete from emp where job='lect';
1 row deleted.
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
Q7: List the records in the emp table orderby salary in ascending order.
Ans:
SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
5 Akalya AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q8: List the records in the emp table orderby salary in descending order.
Ans:
SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2. Select should include distinct clause for the deptno.
Ans:
SQL> select distinct deptno from emp;
DEPTNO
1
2
e) Result:
Thus the DML commands using from where clause was performed successfully and
executed.
c) SQL Commands:
DATE FUNCTION
1. Add_month
This function returns a date after adding a specified date with specified number of months.
Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
2. last_day
It displays the last date of that month.
Syntax: last_day (d); where d-date
Example: Select last_day (‘1-jun-2009’) from dual;
3. Months_between
It gives the difference in number of months between d1 & d2.
Syntax: month_between (d1,d2); where d1 & d2 -dates
Example: Select month_between (‘1-jun-2009’,’1-aug-2009’) from dual;
4. next_day
It returns a day followed the specified date.
Syntax: next_day (d,day);
Example: Select next_day (sysdate,’wednesday’) from dual
5. round
This function returns the date, which is rounded to the unit specified by the format model.
Syntax : round (d,[fmt]);
where d- date, [fmt] – optional. By default date will be rounded to the nearest day
Example: Select round (to_date(‘1-jun-2009’,’dd-mm-yy’),’year’) from dual;
Select round (‘1-jun-2009’,’year’) from dual;
NUMERICAL FUNCTIONS
Command Query Output
CHARACTER FUNCTIONS
CONVERSION FUNCTION
1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date format.
If format is negelected then it converts date to varchar2 in the default date format.
Example: select to_char (sysdate, ’dd-mm-yy’) from dual;
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Example: select to_date(‘aug 15 2009’,’mm-dd-yy’) from dual;
Miscellaneous Functions
1. uid – This function returns the integer value (id) corresponding to the user currently
logged in.
Example: select uid from dual;
2. user – This function returns the logins user name.
Example: select user from dual;
3. nvl – The null value function is mainly used in the case where we want to consider null values
as zero.
Syntax; nvl(exp1, exp2)
If exp1 is null, return exp2. If exp1 is not null, return exp1.
Example: select custid, shipdate, nvl(total,0) from order;
4. vsize: It returns the number of bytes in expression.
Example: select vsize(‘tech’) from dual;
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
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%';
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q3: Display the rows whose salary ranges from 15000 to 30000.
Ans:
SQL> select * from emp where sal between 15000 and 30000;
80000 16000
Q5: Count the total records in the emp table.
Ans:
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> select count(*) from emp;
COUNT(*)
5
Q6: Determine the max and min salary and rename the column as max_salary and
min_salary.
Solution:
1. Use the MIN & MAX aggregate function in select clause.
2. Rename the column as min_sal & max_sal.
Ans:
SQL> select max(sal) as max_salary, min(sal) as min_salary from emp;
MAX_SALARY MIN_SALARY
30000 10000
Q7: Display the month between “1-jun-10”and 1-aug-10 in full.
Ans:
SQL>Select month_between (‘1-jun-2010’,’1-aug-2010’) from dual;
Q8: Display the last day of that month in “05-Oct-09”.
Ans:
SQL> Select last_day ('1-jun-2009') from dual;
LAST_DAY(
30-JUN-09
Q9: Find how many job titles are available in employee table.
Solution:
1. Use select from clause.
2. Use count function to get the result.
Ans:
SQL> select count(job) from emp;
COUNT(JOB)
4
SQL> select count(distinct job) from emp;
COUNT(DISTINCTJOB)
2
Q10: What is the difference between maximum and minimum salaries of employees in the
organization?
Solution:
1. Use select from clause.
2. Use function max(),min() and find the difference between them to get the result.
Ans:
SQL> select max(sal), min(sal) from emp;
MAX(SAL) MIN(SAL)
20000 10000
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);
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
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
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.
Ans:
SQL> select * from emp,dept where emp.deptno!=dept.deptno;
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC
LEFTOUT-JOIN
Tables used
SQL> select * from stud1;
Regno Name Mark2 Mark3 Result
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
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
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.
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
Q1: The organization wants to display only the details of the employees those who are ASP.
(Horizontal portioning)
Solution:
1. Create a view on emp table named managers
2. Use select from clause to do horizontal partioning
Ans:
SQL> create view empview as select * from emp where job='ASP';
View created.
SQL> select * from empview;
EMPNO ENAME JOB DEPTNO SAL
DEPT TABLE
EMP TABLE
EMPVIEW VIEW
EMPVIEW1 VIEW
Q4: Execute the DML commands on the view created.
Ans:
SQL> select * from empview;
EMPNO ENAME JOB DEPTNO SAL
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);
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.
Q4: Write a pl/sql program to find the sum of digits in a given number
c) Procedure for doing the experiment:
Step
Details of the step
no.
1 Read a number. Separate the digits using modular function
2 Sum the digits separated by mod function
3 Display the sum of digits
d) Program:
SQL>edit sumofdigits.sql
declare
a number;
d number:=0;
sum1 number:=0;
begin
a:=&a;
while a>0
loop
d:=mod(a,10);
sum1:=sum1+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('sum is'|| sum1);
end;
e) output:
SQL> @ sumofdigits.sql
16 /
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.
Check the balance for the account no. check if the users balance is less than
3
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
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
Exercise Number: 8
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
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 MARK2 TOTAL
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 MARK2 TOTAL
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;
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
3 Execute the trigger by inserting value into the 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:
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.