You are on page 1of 71

EXPNO: 1 DATE: AIM:

DATABASE LANGUAGES ********************

To study and execute the data definition language (DDL), data manipulation language (DML), Data Control Languages (DCL) and Transaction Control Language (TCL) commands using SQL. LIST OF DDL COMMANDS: CREATE TABLE Command. DESCRIBE Command. ALTER TABLE Command. DROP TABLE Command. TRUNCATE TABLE Command.

LIST OF DML COMMANDS:


INSERT Command. SELECT Command. UPDATE Command. DELETE Command.

LIST OF DCL COMMANDS:


GRANT Command. REVOKE Command.

LIST OF TCL COMMANDS:


COMMIT Command. ROLLBACK Command.

PROCEDURE TO CREATE AN USER:


1. 2. 3. 4. Create your own user first. Create one user name with password. If you are in any other system other than sys manager, do the following steps: SQL> connect system/manager; Itll display as CONNECTED. 5. SQL> create user com1 identified by student; Where, Com1 - user name. Student - password. 6. CREATE SESSION must be granted by the system manager to the user (com1). 7. SQL>connect com1/student; Connected. DESCRIPTION OF DDL COMMANDS: i) CREATE: PURPOSE: This command is used to create a table. SYNTAX : Create table <table name> (column_name1 datatype size, column_name2 datatype size); CREATE TABLE tablename (column_name data_ type constraints, ) EXAMPLE: 1

SQL> create table empl(empno number(5) primary key, ename char(20), dept (10)); ii) DESCRIBE: This command display the table structure. SYNTAX: sQL>desc tablename; EXAMPLE: desc electronic1; iii)ALTER: PURPOSE: This command is used to add a new column in or modify a column to the structure of the table. SYNTAX: SQL>alter table tablename add(columnname datatype,.); SQL>alter table tablename modify(columnname (change the size of the datatype),.); SQL>alter table tablename drop(columnname ,.); SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo); EXAMPLE: alter table electronic1 modify(productsname char(11)); SQL> alter table empl add(bp number(8)); iv) DROP: PURPOSE: This command is used to delete or removing the entire table Deletes table structure Cannot be recovered because Use with caution SYNTAX: drop table <table name>; EXAMPLE: drop table electronic; v)TRUNCATE: PURPOSE : This command is used to delete or remove the contents of the table SYNTAX : truncate table <table name>; EXAMPLE: Truncate table electronics1; OUTPUT: BEFORE TRUNCATE: SQL> truncate table empl; AFTER TRUNCATE: SQL> select * from empl; iv) DELETE TABLE Command: SQL> delete table empl;

DESCRIPTION OF DML COMMANDS:


i)INSERT: PURPOSE: This command is used to insert the values in to the table. SYNTAX: Insert into <table name> values (value1,value2,);

EXAMPLE:
2

SQL> insert into empl values(101,XXX,CSE,12000); SQL> insert into empl values(102,YYY,MECH,10000); iii) SELECT: PURPOSE: This command is used to display the entire table. SYNTAX: Select * from <table_name>; SQL> select * from empl; iii)UPDATE: PURPOSE: This command is used to update the old values in to the new values. SYNTAX: Update <table_name> set column_name=value where <condition>

EXAMPLE:

EXAMPLE:

SQL> update empl set bp=15000 where eid=101; SQL> select * from empl; iv)DELETE: PURPOSE: SYNTAX: This command is used to delete the values from the table. delete from <table_name> where <condition>;

EXAMPLE:

SQL> delete from empl where eid=102;

v)GRANT Command: PURPOSE: This command is used to give some permissions (like select, update) to he user. SYNTAX: grant <system privilege> on <table_name> to <user_name>;

where:

system privileges is nothing but the DML commands (insert, alter, update, select,..).

vi)REVOKE Command: PURPOSE: This command is used to release all permissions . SYNTAX : Revoke <object privileges> on <table_name> from <user_name>; vii)COMMIT Command: PURPOSE: This command is used to make all transaction changes permanent to the data base. This command erases all save points and release the transaction lock. SYNTAX: commit; SAVEPOINT: Savepoint is not a command. It is only a marker. Savepoint are used to divide a lengthy transaction into smaller ones. SYNTAX: savepoint ID; 3

viii)ROLLBACK Command: PURPOSE: This command is used to undo all the changes made in the current transaction. We can either rollback the entire transaction or rollback a transaction to a savepoint. SYNTAX: (a): rollback; (This will rollback(undo) the entire transaction). (b): rollback to savepoint <id>; (Thisll undo all changes made after the creation of the savepoint id).

RESULT:
Thus the above program for data manipulation language (DML), Data Control Languages (DCL) and Transaction Control Language (TCL) has been executed successfully and the output is verified.

Exp no: 2 Date:

NESTED QUERIES & AGGREGATE FUNCTIONS

AIM:
To study and execute the queries for nested queries & aggregate functions.

PROCEDURE:
Writing and Practice of Simple Queries. 1. Get the description of EMP table. SQL>desc emp; 2. Get the description DEPT table. SQL>desc dept; 3.List all employee details. SQL>select * from emp; 4.List all employee names and their salaries, whose salary lies between 1500/- and 3500/both inclusive. SQL>select ename from emp where sal between 1500 and 3500; 5. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789. SQL>select ename from emp where mgr in(7602,7566,7789); 6. List all employees which starts with either J or T. SQL>select ename from emp where ename like J% or ename like T%; 7. List all employee names and jobs, whose job title includes M or P. SQL>select ename,job from emp where job like M% or job like P%; 8. List all jobs available in employee table. SQL>select distinct job from emp;
4

9. List all employees who belongs to the department 10 or 20. SQL>select ename from emp where deptno in (10,20); 10. List all employee names , salary and 15% rise in salary. SQL>select ename , sal , sal+0.15* sal from emp; 11. List minimum , maximum , average salaries of employee. SQL>select min(sal),max(sal),avg(sal) from emp; 12. Find how many job titles are available in employee table. SQL>select count (distinct job) from emp; 13. What is the difference between maximum and minimum salaries of employees in the organization? SQL>select max(sal)-min(sal) from emp; 14. Display all employee names and salary whose salary is greater than minimum salary of the company and job title starts with M. SQL>select ename,sal from emp where job like M% and sal > (select min (sal) from emp); 15. Find how much amount the company is spending towards salaries. SQL>select sum (sal) from emp; 16. Display name of the dept. With deptno 20. SQL>select ename from emp where deptno = 20; 17. List ename whose commission is NULL. SQL>select ename from emp where comm is null; 18. Find no.of dept in employee table. SQL>select count (distinct ename) from emp; 19. List ename whose manager is not NULL. SQL>select ename from emp where mgr is not null; Writing Queries using GROUP BY and other clauses. To write queries using clauses such as GROUP BY, ORDER BY, etc. and retrieving information by joining tables. Source tables: emp, dept, programmer, software, study. Order by: The order by clause is used to display the results in sorted order. Group by: The attribute or attributes given in the clauses are used to form groups. Tuples with the same value on all attributes in the group by clause are placed in one group. Having: SQL applies predicates (conditions) in the having clause after groups have been formed, so aggregate function be used. 1. Display total salary spent for each job category. SQL>select job,sum (sal) from emp group by job; 2. Display lowest paid employee details under each manager.
5

SQL>select ename, sal from emp where sal in (select min(sal) from emp group by mgr); 3. Display number of employees working in each department and their department name. SQL> select dname, count (ename) from emp, dept where emp.deptno=dept.deptno group by dname; 4. Display the sales cost of package developed by each programmer. SQL>select pname, sum(scost) from software group by pname; 5. Display the number of packages sold by each programmer. SQL>select pname, count(title) from software group by pname; 6. Display the number of packages in each language for which the development cost is less than thousand. SQL>select devin, count(title) from software where dcost < 1000 group by devin; 7. Display each institute name with number of students. SQL>select splace, count(pname) from study group by splace; 8. How many copies of package have the least difference between development and selling cost, were sold? SQL>select sold from software where scost dcost=(select min(scost dcost) from software); 9. Which is the costliest package developed in Pascal. SQL>select title from software where devin = PASCAL and dcost = (select max(dcost)from software where devin = PASCAL); 10. Which language was used to develop most no .of packages. SQL>select devin, count (*) from software group by devin having count(*) = (select max(count(*) ) from software group by devin); 11.Who are the male programmers earning below the average salary of female programmers? SQL>select pname from programmer where sal < (select avg(sal) from programmer where sex = F) and sex = M; 12. Display the details of software developed by the male programmers earning more than 3000/-. SQL>select programmer.pname, title, devin from programmer, software where sal > 3000 and sex = M and programmer.pname = software.pname; 13. Display the details of software developed in c language by female programmers of pragathi. SQL>select software.pname, title, devin, scost, dcost, sold from programmer, software, study where devin = c and sex =F and splace = pragathi and programmer.pname = software.pname and software.pname = study.pname; 14. Which language has been stated by the most of the programmers as proficiency one? SQL>select prof1, count(*) from programmer group by prof1 having count (*) = (select max (count (*) ) from programmer group by prof1);
6

Writing Nested Queries. To write queries using Set operations and to write nested queries. Set Operations: UNION OR INTERSECT AND EXCEPT NOT NESTED QUERY:- A nested query makes use of another sub-query to compute or retrieve the information. 1. Find the name of the institute in which the person studied and developed the costliest package. SQL>select splace, pname from study where pname = (select pname from software where scost = (select max (scost) from software); 2. Find the salary and institute of a person who developed the highest selling package. SQL> select study.pname, sal, splace from study, programmer where study.pname = programmer.pname and study.pname = (select pname from software where scost = (select max (scost) from software)); 3. How many packages were developed by the person who developed the cheapest package. SQL>select pname, count (title) from software where dcost = (select min(dcost) from software) group by pname; 4. Calculate the amount to be recovered for those packages whose development cost has not yet recovered. SQL>select title , (dcost-scost) from software where dcost > scost; 5. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference. SQL> select title, scost, dcost, (scost - dcost) from software descending order by (scost-dcost); 6. Display the details of those who draw the same salary. SQL> select p.pname, p.sal from programmer p, programmer t where p.pname <> t.pname and p.sal = t.sal;(or) SQL>select pname,sal from programmer t where pname<>t.pname and sal= t.sal; WORKING WITH SQL COMMANDS: SINGLE ROW FUNCTIONS: SQL> select add_months(sysdate,40)from dual; SQL> select sysdate from dual; SQL> select last_day(sysdate)from dual; SQL> select months_between(sysdate,'4-july-1989')from dual; SQL> select next_day(sysdate,'tuesday')from dual; SQL> select next_day(sysdate,'friday')from dual; SQL> select next_day('17-feb-2010','tuesday')from dual; SQL> select round(sysdate,'year')from dual; SQL> select round(sysdate,'month')from dual; SQL> select greatest('10-jan-2008','tuesday')from dual; SQL> select greatest('10-jan-2008','10-jan-2009')from dual; SQL> select greatest(sysdate,'10-jan-2009')from dual;
7

SQL> select greatest('10-jan-2008',sysdate,'10-jan-2009')from dual; SQL> select chr(65)from dual; SQL> select concat('bhava','tharani')from dual; SQL> select lower('PRAKASH')from dual; SQL> select lpad(type,4,'*')from turbo; SQL> select rpad(type,3,'*')from turbo; SQL> select ltrim('xabcde1jo','x')from dual; SQL> select ltrim('xxxxr','x')from duaL; SQL> select rtrim('xxxrxxx','x')from dual; SQL> select replace('tamil','t','T')from dual; SQL> select replace('main','streat')from dual; SQL> select substr('abcd,2)from dual; SQL> select upper('type')from dual; SQL> select ascii('a')from dual; SQL> select ascii('A')from dual; SQL> select instr('haifriends','en',3,1) from dual; SQL> select instr('this is test','is',3,1)from dual; SQL> select instr('this is test','is')from dual; SQL> select instr('this is test','is',1,1)from dual; SQL> select instr('haifriends','en',0) from dual; SQL> select instr('coso','o',0)from dual; SQL> select instr('coso co','o',4)from dual; SQL> select instr('cos0 c0','0') from dual; SQL> select length('rtq gfdg')from dual; SQL> select abs(-65.8)from dual; SQL> select abs(65.8)from dual; SQL> select ceil(45.04)from dual; SQL> select ceil(45.90)from dual; SQL> select ceil(45.00)from dual; SQL> select cos(45)from dual; SQL> select cos(45*(2217/180))from dual; SQL> select cos(0)from dual; SQL> select cosh(0)from dual; SQL> select exp(0)from dual; SQL> select exp(5)from dual; SQL> select floor(43.46)from dual; SQL> select exp(1)from dual; SQL> select ln(1)from dual; SQL> select mod(12,5)from dual; SQL> select power(2,2)from dual; SQL> select power(2,3)from dual; SQL> select round(45.01)from dual; SQL> select sign(-45)from dual; SQL> select sign(45)from dual; SQL> select tan(0)from dual; SQL> select tanh(0)from dual; Writing Queries using functions. AIM: To write queries using single row functions and group functions. 1. Display the names and dob of all programmers who were born in january.
8

SQL>select pname , dob from programmer where to_char (dob,MON)=JAN; 2. Calculate the experience in years of each programmer and display along with programmer name in descending order. SQL> select pname, round (months_between(sysdate, doj)/12, 2) "EXPERIENCE" from programmer order by months_between (sysdate, doj) desc; 3. List out the programmer names who will celebrate their birthdays during current month. SQL>select pname from programmer where to_char(dob,MON) like to_char (sysdate, MON); 4. Display the least experienced programmers details. SQL>select * from programmer where doj = (select max (doj) from programmer); 5. Who is the most experienced programmer knowing pascal. SQL>select pname from programmer where doj = (select min (doj) from programmer); 6. Who is the youngest programmer born in 1965. SQL> select pname , dob from programmer where dob = (select max (dob) from programmer where to_char (dob,'yy') = 65); 7. In which year, most of the programmers are born. SQL>select to_char (dob , YY) from programmer group by to_char (dob, YY) having count(*) = (select max (count(*)) from programmer group by to_char(dob,YY); 8. In which month most number of programmers are joined. SQL>select to_char (doj,YY) from programmer group by to_char (doj,YY) having count (*) = (select max (count(*)) from programmer group by to_char (doj,YY); 9. What is the length of the shortest name in programmer table ? SQL>select length (pname) from programmer where length (pname) = select min ( length (pname) from programmer); 10. Display the names of the programmers whose name contains up to 5 characters. SQL>select pname from programmer where length (pname) <=5; 11. Display all packages names in small letters and corresponding programmer names in uppercase letters. SQL>select lower (title), upper (pname) from software;

RESULT:
Thus the above queries for nested queries & aggregate functions has been executed successfully and the output is verified.

EXP NO: 3 DATE: AIM:

CONSTRAINTS IN SQL

To study and execute the constraints using SQL.

LIST OF CONSTRAINTS: It is a declarative way of defining a business rule for a column of a table. An integrity constraints is a statement about the table, data i.e. always live .The type are NULL CONSTRAINTS. NOT NULL CONSTRAINTS. PRIMARY KEY CONSTRAINTS. CHECK CONSTRAINTS. FOREIGN KEY CONSTRAINTS. DESCRIPTIONS: 1) DOMAIN INTEGRITY CONSTRAINTS: i)NOTNULL Constraint: When a not null constraint is enforced on a column or a group of columns in a table, oracle will not allow null values in the columns. Null value is different from zero value. Also a null values in one column is not equivalent to the null value in another column. SYNTAX: create table <table_name>(<column_name data type> not null, .); EXAMPLE: SQL> create table master(sno number(3) NOT NULL, name CHAR(10) NOT NULL, room_no number(2), address varchar2(10)); After this, oracle will not allow inserting a row with null values in the columns sno, name. ii)CHECK Constraint: If there is a necessity to enforce an integrity rule based on a logical or a Boolean expression; we can use the CHECK constraint. EXAMPLE: SQL>create table master(roll_no number(3) check (roll_no between 101 and 200), name char(10), address varchar2(20)); Checks the roll number between 101 and 20. OPERATORS USED IN CHECK CONSTRAINT: IN NOT IN BETWEEN LIKE LIKE :is used to perform pattern matching. There are two patterns % and _ (underscore). (a) % represents any number of spaces or characters. (b) _ represents one space or character. 2) ENTITY INTEGRITY CONSTRAINTS: i)UNIQUE CONSTRAINTS: Unique key constraint is used to prevent duplication of values within the row of a specified column or a group of columns in a table.
10

SYNTAX: SQL> create table tname (column name data type unique..)); EXAMPLE: SQL>create table student(roll_no number(4) unique, name char(10), address varchar2(10)); At the output oracle will not allow the same entry inside the ROLL_NO column. ii)PRIMARY KEY CONSTRAINTS: A primary key is one or more columns in a table which identifies each row in the table uniquely. This constraint does not allow NULL values and duplicate values across the columns comprising the primary key. SYNTAX: SQL>: create table tname(col name data type primary key)); EXAMPLE: SQL>create table stud(roll_no number(4) primary key, name char(10), address varchar2(20)); 3) REFERENTIAL INTEGRITY CONSTRAINTS: Referential integrity constraints are used to establish a parent-child relationship between two tables having a common column. To implement this integrity the column should be defined as primary key in the parent table and the same column as a foreign key in the child table. SYNTAX: SQL> create table tname(col name data type references <ref tname> ON <delete/update>CASCADE); (or) SQL> create table tname(col1 name data type, constraint constraint_name foreign key(col1 name) references other_table_name(col name), col2 name data type,.); EXAMPLE: SQL>create table master(id number(4) foreign key references student(roll_no), mark number(3)); (or) SQL> create table master(id number(4), constraint fkey foreign key(id) references student(roll_no),mark number(3)); Here the foreign key ID references the primary key ROLL_NO from the table student. It allows each value in a column or set of columns match a value in related tables unique or primary key. RESULT: Thus the above program for studying and executing the integrity constraints has been executed successfully and the output is verified.

This does not allow a duplicate value in a column or set of columns.

11

EXPT NO: 4 JOIN FUNCTION DATE:

AIM:
To execute the join function operation using queries

PROCEDURE:
A join is a query that combines rows from two or more tables, views, or materialized views. Oracle performs a join whenever multiple tables appear in the query's FROM clause. The query's select list can select any columns from any of these tables. If any two of these tables have a column name in common, you must qualify all references to these columns throughout the query with table names to avoid ambiguity.

1) Equi joins:
An equijoin is a join with a join condition containing an equality operator ( = ). An equijoin combines rows that have equivalent values for the specified columns. EXAMPLE: select e.empno, e.ename, e.sal, e.deptno, d.dname, d.city from emp e, dept d where emp.deptno=dept.deptno; (OR) select * from emp,dept where emp.deptno=dept.deptno;

2) Non Equi Joins:


Non equi joins is used to return result from two or more tables where exact join is not possible. EXAMPLE: select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s where e.sal between s.lowsal and s.hisal

a) Self Joins
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle combines and returns rows of the table that satisfy the join condition. EXAMPLE: Select e.empno, e.ename, m.ename Manager from emp e, emp m where e.mgrid=m.empno An inner join (sometimes called a "simple join") is a join of two or more tables that returns only those rows that satisfy the join condition. SYNTAX:
12

b) Inner Join

SELECT <column_name>, <column_name> FROM <table_name alias> INNER JOIN <table_name alias> ON <alias.column_name> = <alias.column_name> EXAMPLE: SELECT p.last_name, t.title_name FROM person p INNER JOIN title t ON p.title_1 = t.title_abbrev;

c) Outer Joins:
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also returns some or all of those rows from one table for which no rows from the other satisfy the join condition. i) Left Outer Join
To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use the ANSI LEFT [OUTER] JOIN syntax, or apply the outer join operator (+) to all columns of B in the join condition. For all rows in A that have no matching rows in B, Oracle returns null for any select list expressions containing columns of B.

SYNTAX: SELECT <column_name>, <column_name> FROM <table_name alias> LEFT OUTER JOIN <table_name alias> ON <alias.column_name> = <alias.column_name> EXAMPLE: SELECT p.last_name, t.title_name FROM person p LEFT OUTER JOIN title t ON p.title_1 = t.title_abbrev; ii) Right Outer Join
To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use the ANSI RIGHT [OUTER] syntax, or apply the outer join operator (+) to all columns of A in the join condition. For all rows in B that have no matching rows in A, Oracle returns null for any select list expressions containing columns of A.

SYNTAX: SELECT <column_name>, <column_name> FROM <table_name alias> RIGHT OUTER JOIN <table_name alias> ON <alias.column_name> = <alias.column_name> EXAMPLE: SELECT p.last_name, t.title_name FROM person p RIGHT OUTER JOIN title t ON p.title_1 = t.title_abbrev; iii) Full Outer Join
To write a query that performs an outer join and and returns all rows from A and B, extended with nulls if they do not satisfy the join condition (a full outer join), use the ANSI FULL [OUTER] JOIN syntax.

SYNTAX: SELECT <column_name>, <column_name> FROM <table_name alias> FULL OUTER JOIN <table_name alias> ON <alias.column_name> = <alias.column_name> EXAMPLE: SELECT p.last_name, t.title_name FROM person p FULL OUTER JOIN title t ON p.title_1 = t.title_abbrev; select e.empno,e.ename,e.sal,e.deptno,d.dname,d.city from emp e, dept d where e.deptno(+)=d.deptno;
13

That is specify the (+) sign to the column which is lacking values. RESULT: Thus the above program for studying and executing the joins has been executed successfully and the output is verified.

EXP NO: 5 DATE:

VARIOUS SELECT COMMANDS and INDEXES ***************************************

AIM:
To study and execute various select commands and indexes using SQL.

PROCEDURE:
TYPES OF SELECT COMMAND: GROUP BY ORDER BY HAVING and BETWEEN DISTINCT SET OPERATORS: UNION UNION ALL INTERSECT MINUS DESCRIPTION OF COMMANDS:
SQL> select * from dept; D_ID D_NAME ---------- ---------1 CSE 2 IT 3 MECH 4 ECE 5 EeE 6 Accounts 7 CIVIL 8 AUTO 9 EI 10 AERO SQL> select * from employee; EID NAME AGE SALARY DEPT_ID ---------- --------------- ---------- ---------- ---------1 Ram 20 5000 2 2 Sam 25 7000 2 3 ramesh 54 4000 4 4 Senthil 27 6700 5 5 Saranya 25 5700 2 6 Sathis 26 7400 3 7 Karthi 24 6200 1 14

8 Jaga

25

12000

i)GROUP BY: This command is used to display the group of values. SYNTAX: Select column1, column2 from <table_name> group by column1 having condition; EXAMPLE:
SQL> select dept_id,avg(salary) from employee group by dept_id; DEPT_ID AVG(SALARY) ---------- ----------1 6200 2 5900 4 4000 5 6700 3 7400 7 12000 SQL> select d_name,count(eid) from employee,dept where employee.dept_id=dept.d_id group by d_name; D_NAME ---------IT EeE CIVIL CSE MECH ECE COUNT(EID) ---------3 1 1 1 1 1

ii)ORDERBY: This command is used to display the column in an order(ascending order is default in all SQL queries). SYNTAX: Select * from <table_name> orderby condition; EXAMPLE: SQL> select * from employee order by name; EID NAME AGE SALARY DEPT_ID ---------- --------------- ---------- ---------- ---------8 Jaga 25 12000 7 7 Karthi 24 6200 1 1 Ram 20 5000 2 2 Sam 25 7000 2 5 Saranya 25 5700 2 6 Sathis 26 7400 3 4 Senthil 27 6700 5 3 ramesh 54 4000 4 iii)HAVING and BETWEEN:
15

SYNTAX:

This command is used to display the value having a condition. Select column1,column2.. from <table_name> where column having condition;

EXAMPLE: SQL> select dept_id,avg(salary) from employee group by dept_id having avg(salary)>2000;
DEPT_ID AVG(SALARY) ---------- ----------1 6200 2 5900 4 4000 5 6700 3 7400 7 12000

BETWEEN: SYNTAX: This command is used to display the values between any condition. Select column_name from table_name group by column_name between condition; EXAMPLE: SQL> select dept_id,avg(salary) from employee group by dept_id having avg(salary) between 2000 and 7000; DEPT_ID AVG(SALARY) ---------- ----------1 6200 2 5900 4 4000 5 6700 iv)DISTINCT: This command is used to eliminate the duplicate entries from the table. SYNTAX: Select distinct * from table_name; EXAMPLE SQL> select distinct age from employee order by age; AGE ---------20 24 25 26 27 54

SET OPERATORS:
Table1: STUDENT ROLLNO 1 NAME M1 M2 M3 XXX 90 60 90
16

2 AAA 80 70 50 3 BBB 90 80 50 Table2: STUD ROLLNO NAME M1 M2 M3 1 XXX 90 60 90 2 AAA 80 70 50 4 CCC 80 80 60 i)UNION: The union operator returns all distinct rows selected by the component queries. SQL>select * from student union select * from stud; OUTPUT: ROLLNO NAME M1 M2 M3 1 XXX 90 60 90 2 AAA 80 70 50 3 BBB 90 80 50 4 CCC 80 80 60 ii)UNION ALL: The union all operator returns all rows selected by both queries including duplicate. SQL>select * from student unionall select * from stud; OUTPUT: ROLLNO NAME M1 M2 M3 1 XXX 90 60 90 2 AAA 80 70 50 3 BBB 90 80 50 1 XXX 90 60 90 2 AAA 80 70 50 4 CCC 80 80 60 iii)INTERSECT: This operator returns only rows that are common to both queries. SQL>select * from student intersect select * from stud; OUTPUT: ROLLNO NAME M1 M2 M3 1 XXX 90 60 90 2 AAA 80 70 50 iv)MINUS: This operator returns all distinct rows selected only by the first query and not by the second query. SQL>select * from student minus select * from stud; OUTPUT: ROLLNO NAME M1 M2 M3 3 BBB 90 80 50

INDEXES:

17

An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. Create an Index: SYNTAX: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n); UNIQUE indicates that the combination of values in the indexed columns must be unique. EXAMPLE: CREATE INDEX supplier_idx ON supplier (supplier_name); In this example, created an index on the supplier table called supplier_idx. It consists of only one field - the supplier_name field. We could also create an index with more than one field as in the example below: CREATE INDEX supplier_idx ON supplier (supplier_name, city); Rename an Index: SYNTAX: ALTER INDEX index_name RENAME TO new_index_name; EXAMPLE: ALTER INDEX supplier_idx RENAME TO supplier_index_name; In this example, we're renaming the index called supplier_idx to supplier_index_name. Drop an Index: SYNTAX: DROP INDEX index_name; EXAMPLE: DROP INDEX supplier_idx; In this example, we're dropping an index called supplier_idx.

RESULT:
Thus the above various types of select commands and indexes has been executed successfully and the output is verified.

EXP NO: 6 DATE:

VIEWS ***************

AIM:
18

To study and execute various select commands and views using SQL.

PROCEDURE:

VIEWS:
tables.

A view is an object that gives the user a logical view of data from an underlying table or

Employee
EID 1 2 3 7 6 NAME Ram Sam ramesh hgh senthil AGE 20 25 54 55 34 SALARY 5000 7000 4000 6676 5000

1. Create a view from single table containing all columns from the base table. SYNTAX: Create view <view_name> as select * from <table_name>; EXAMPLE: EID NAME AGE SALARY SQL> create view emp_view as select * from employee; 1 Ram 20 5000 SQL> select * from emp_view;
2 3 7 6 Sam ramesh hgh senthil 25 54 55 34 7000 4000 6676 5000

2. Create a view from single table with selected columns. SYNTAX: Create view <view_name> as select <col1_name,col2_name> from <table_name>; EXAMPLE: SQL> create view sel_emp_view as select name, salary from employee; SQL> select * from sel_emp_view;
NAME Ram Sam ramesh hgh senthil SALARY 5000 7000 4000 6676 5000

3. Create a view from two tables with all columns. SYNTAX: Create view <view_name> as select * from <table1_name> full natural join <table2_name>; EXAMPLE: SQL>select * from student; SNO SNAME LNAME 2 sss 1 senthil kumar 3 karthi keyan 4 ravi chandaran
19

SQL> create view stud_emp_view as select * from student full natural join employ ee; SNO SNAME LNAME EID NAME AGE SALARY 2 sss 1 Ram 20 5000 2 sss 2 Sam 25 7000 2 sss 3 ramesh 54 4000 2 sss 6 senthil 34 5000 1 senthil kumar 1 Ram 20 5000 1 senthil kumar 2 Sam 25 7000 1 senthil kumar 3 ramesh 54 4000 1 senthil kumar 6 senthil 34 5000 3 karthi keyan 1 Ram 20 5000 3 karthi keyan 2 Sam 25 7000 3 karthi keyan 3 ramesh 54 4000 3 karthi keyan 6 senthil 34 5000 4 ravi chandaran 1 Ram 20 5000 4 ravi chandaran 2 Sam 25 7000 4 ravi chandaran 3 ramesh 54 4000 4 ravi chandaran 6 senthil 34 5000

4. Create a view from two tables with selected columns. SYNTAX: Create view <view_name> as select <col1_name,col2_name> from <table1_name><alias1>,<table2_name><alias2> where <alias1>.<col_name>=<alias2>.<col_name>; EXAMPLE: SQL>create view stud_emp_sel_view as select name,lname,age,salary from student s,employee e where s.sno=e.eid; SQL> select * from stud_emp_sel_view; NAME LNAME AGE SALARY Sam 25 7000 Ram kumar 20 5000 ramesh keyan 54 4000 5. Check all DML commands. INSERT: SYNTAX: insert into <view_name> values(value1,value2,value3,); EXAMPLE: SQL>insert into stud_view values(6,'Muthu','vel'); SQL> select * from stud_view; UPDATE: SYNTAX:
20

SNO SNAME LNAME 2 sss 1 senthil kumar 3 karthi keyan 4 ravi chandaran 6 Muthu vel

update <view_name> set <col1_name>=<value1> where <col2_name>=<value2>; EXAMPLE: SQL> update stud_view set lname='nnnn' where sno=2; SNO SNAME LNAME SQL> select * from stud_view; 2 sss nnnn 1 senthil kumar Note: update command does not works for all queries on views. 3 karthi keyan DELETE: 4 ravi chandaran SYNTAX: 6 Muthu vel delete from <view_name> where <col1_name>=<value1>; EXAMPLE: SQL> delete from emp_view where eid=6; SQL>select * from emp_view;
EID NAME 1 Ram 2 Sam 3 ramesh AGE 20 25 54 SALARY 5000 7000 4000

6. Drop views. SYNTAX: drop view <view_name>; EXAMPLE: SQL>Drop view stud_view; View dropped. SQL>select * from stud_view; Table or view does not exist

RESULT:
Thus the above view has been executed successfully and the output is verified.

EX.NO:7 DATE: AIM:

SIMPLE PL-SQL PROGRAMS

To write and execute simple pl/sql programs. PROCEDURE: PL/SQL Control Structures: 1. Simple IF-THEN Statement SQL> DECLARE n number; BEGIN n:=&n; IF n > 0 THEN
21

Dbms_output.put_line(Given number is Greater than ZERO); END IF; END; / 2. Simple IF-THEN-ELSE Statement SQL> DECLARE n number; BEGIN n:=&n; IF n > 0 THEN Dbms_output.put_line(Given number is Greater than ZERO); ELSE Dbms_output.put_line(Given number is Less than ZERO); END IF; END; / 3. Nested IF-THEN-ELSE Statements SQL> DECLARE n number; BEGIN n:=&n; IF n > 0 THEN Dbms_output.put_line(Given number is Greater than ZERO); ELSE IF n = 0 THEN Dbms_output.put_line(Given number is Equal to ZERO); ELSE Dbms_output.put_line(Given number is Less than ZERO); END IF; END IF; END; / 4. IF-THEN-ELSIF Statement SQL> DECLARE
n number; BEGIN n:=&n; IF n > 0 THEN Dbms_output.put_line('Given number is Greater than ZERO'); ELSIF n = 0 THEN Dbms_output.put_line('Given number is Equal to ZERO'); ELSE Dbms_output.put_line('Given number is Less than ZERO'); END IF; END;

22

5. Extended IF-THEN Statement SQL> DECLARE grade CHAR(1); BEGIN grade := 'B'; IF grade = 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); ELSIF grade = 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); ELSIF grade = 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); ELSIF grade = 'D' THEN DBMS_OUTPUT. PUT_LINE('Fair'); ELSIF grade = 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END IF; END; / 6. Simple CASE Statement SQL> DECLARE grade CHAR(1); BEGIN grade := 'B'; CASE grade WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END CASE; END; / 7. Searched CASE Statement SQL> DECLARE grade CHAR(1); BEGIN grade := 'B'; CASE WHEN grade = 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); WHEN grade = 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); WHEN grade = 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); WHEN grade = 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); WHEN grade = 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END CASE;
23

END; / 8. EXCEPTION Instead of ELSE Clause in CASE Statement SQL> DECLARE grade CHAR(1); BEGIN grade := 'B'; CASE WHEN grade = 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); WHEN grade = 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); WHEN grade = 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); WHEN grade = 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); WHEN grade = 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); END CASE; EXCEPTION WHEN CASE_NOT_FOUND THEN DBMS_OUTPUT.PUT_LINE('No such grade'); END; / 9. WHILE-LOOP Statement DECLARE A NUMBER; I NUMBER :=1; BEGIN A:=10; WHILE I<A LOOP DBMS_OUTPUT.PUT_LINE('VALUE :'||I); I:=I+1; END LOOP; END; /

10. FOR-LOOP Statement SQL> BEGIN FOR i IN 1..3 LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(i)); END LOOP; END; / 11. Reverse FOR-LOOP Statement SQL> BEGIN FOR i IN REVERSE 1..3 LOOP DBMS_OUTPUT.PUT_LINE (TO_CHAR(i));
24

END LOOP; END; / 12. Simple GOTO Statement SQL> DECLARE p VARCHAR2(30); n PLS_INTEGER := 37; BEGIN FOR j in 2..ROUND(SQRT(n)) LOOP IF n MOD j = 0 THEN p := ' is not a prime number'; GOTO print_now; END IF; END LOOP; p := ' is a prime number'; <<print_now>> DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p); END; / 13. GOTO Statement to Branch to an Enclosing Block SQL> DECLARE v_last_name VARCHAR2(25); v_emp_id NUMBER(6) := 120; BEGIN <<get_name>> SELECT last_name INTO v_last_name FROM employees WHERE employee_id = v_emp_id; BEGIN DBMS_OUTPUT.PUT_LINE (v_last_name); v_emp_id := v_emp_id + 5; IF v_emp_id < 120 THEN GOTO get_name; END IF; END; END; / 14. DoWhile Statement: declare n_num number := 1; begin loop dbms_output.put(n_num||', '); n_num := n_num + 1; exit when n_num > 5; end loop; dbms_output.put_line('Final: '||n_num); end;
25

/ ALGORITHMS: 1.Start the program 2.Declare the variables. 3.Perform the given operation 4.Display the result. 5.Stop the terminate the execution. PL-SQL PROGRAMS: 1. FACTORIAL VALUE PROGRAM: SQL> set serveroutput on; SQL>ed fact.sql; declare i number; n number; f number:=1; begin n:=&n; if n=0 then dbms_output.put_line('The factorial value is :'||i); end if; for i in 1..n loop f:=f*i; end loop; dbms_output.put_line('The factorial value is :'||f); end; / Output: Enter value for n: 5 old 6: n:=&n; new 6: n:=5; The factorial value is :120 2. PRIME NUMBER GENERATION PROGRAM: SQL> set serveroutput on; SQL>ed prime.sql; declare n number; i number; j number; k number;
26

p number; begin n:=&n; dbms_output.put_line('The prime number are'); for i in 2..n loop p:=0; for j in 2..(i-1) loop k:=i mod j; if k=0 then p:=1; end if; end loop; if p=0 then dbms_output.put_line(i); end if; end loop; end; / Output: SQL>set serveroutput on; SQL>@prime.sql; Enter value for n: 7 old 8: n:=&n; new 8: n:=7; The prime number are 2 3 5 7 3. FIBONACCI SERIES PROGRAM: SQL> set serveroutput on; SQL>ed fib.sql; declare a number:=-1; b number:=1; c number; i number; n number; begin n:=&n; for i in 1..n loop c:=a+b;
27

a:=b; b:=c; dbms_output.put_line(c); end loop; end; / Output: SQL>set serveroutput on; SQL>@fib.Sql; Enter value for n: 7 old 8: n:=&n; new 8: n:=7; 0 1 1 2 3 5 8 4. PL/SQL block for insertion into a table. To write a PL/SQL block for inserting rows into EMPDET table with the following Calculations: HRA=50% OF BASIC DA=20% OF BASIC PF=7% OF BASIC NETPAY=BASIC+DA+HRA-PF DECLARE ENO1 empdet.eno%type; ENAME1 empdet.name%type; DEPTNO1 empdet.deptno%type; BASIC1 empdet.basic%type; HRA1 empdet.HRA%type; DA1 empdet.DA%type; PF1 empdet.pf%type; NETPAY1 empdet.netpay%type; BEGIN ENO1:=&ENO1; ENAME1:='&ENAME1'; DEPTNO1:=&DEPTNO1; BASIC1:=&BASIC1; HRA1:=(BASIC1*50)/100; DA1:=(BASIC1*20)/100; PF1:=(BASIC1*7)/100; NETPAY1:=BASIC1+HRA1+DA1-PF1;

28

INSERT INTO EMPDET VALUES (ENO1, ENAME1, DEPTNO1, BASIC1, HRA1, DA1, PF1, NETPAY1); END; OUTPUT: SQL> @BASIC Enter value for eno1: 104 old 11: ENO1:=&ENO1; new 11: ENO1:=104; Enter value for ename1: SRINIVAS REDDY old 12: ENAME1:='&ENAME1'; new 12: ENAME1:='SRINIVAS REDDY'; Enter value for deptno1: 10 old 13: DEPTNO1:=&DEPTNO1; new 13: DEPTNO1:=10; Enter value for basic1: 6000 old 14: BASIC1:=&BASIC1; new 14: BASIC1:=6000; SQL>/ Enter value for eno1: 105 old 11: ENO1:=&ENO1; new 11: ENO1:=105; Enter value for ename1: CIRAJ old 12: ENAME1:='&ENAME1'; new 12: ENAME1:='CIRAJ'; Enter value for deptno1: 10 old 13: DEPTNO1:=&DEPTNO1; new 13: DEPTNO1:=10; Enter value for basic1: 6000 old 14: BASIC1:=&BASIC1; new 14: BASIC1:=6000; SQL> SELECT * FROM EMPDET; OUTPUT: ENO NAME DEPTNO BASIC HRA DA PF NETPAY --------- ------------------------------ --------- --------- --------- --------- --------- ----------------------101 SANTOSH 10 5000 2500 1000 350 8150 102 SHANKAR 20 5000 2500 1000 350 8150 103 SURESH 20 5500 2750 1100 385 8965 104 SRINIVASA REDDY 10 6000 3000 1200 420 9780 105 CIRAJ 10 6000 3000 1200 420 9780 5. checking armstrong number DECLARE num number(5); rem number(5); s number(5):=0; num1 number(5);
29

BEGIN

END; / OUTPUT:

num:=&num; num1:=num; while(num>0) loop rem:=mod(num,10); s:=s+power(rem,3); num:=trunc(num/10); End loop; if (s=num1)then dbms_output.put_line(num1 || ' IS ARMSTRONG NUMBER '); else dbms_output.put_line(num1 || ' IS NOT ARMSTRONG NUMBER'); End if;

SQL>@arm.sql Enter value for num: 153 old 7: num:=&num; new 7: num:=153; 153 IS ARMSTRONG NUMBER SQL> / Enter value for num: 123 old 7: num:=&num; new 7: num:=123; 123 IS NOT ARMSTRONG NUMBER 6. checking a number even or odd. DECLARE num number(5); rem number; BEGIN num:=&num; rem:=mod(num,2); if rem=0 then dbms_output.put_line(' Number '|| num ||' is Even'); else dbms_output.put_line(' Number '||num||' is Odd'); end if; END; / OUTPUT: SQL>start even Enter value for num: 6 old 5: num:=&num;
30

new 5: num:=6; Number 6 is Even SQL> / Enter value for num: 3 old 5: num:=&num; new 5: num:=3; Number 3 is Odd 7. find sum of digits of a given number. DECLARE num number(5); rem number(5); sm number(5):=0; num1 number(5); BEGIN num:=&num; num1:=num; while(num>0) loop rem:=mod(num,10); sm:=sm+rem; num:=trunc(num/10); end loop; dbms_output.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm); end; / OUTPUT: SQL> @sum INPUT truncated to 2 characters Enter value for num: 123 old 7: num:=&num; new 7: num:=123; SUM OF DIGITS OF 123 IS: 6 SQL> @sum INPUT truncated to 2 characters Enter value for num: 456 old 7: num:=&num; new 7: num:=456; SUM OF DIGITS OF 456 IS: 15

8. generating Fibonacci series. DECLARE num number(5);


31

BEGIN

f1 number(5):=0; f2 number(5):=1; f3 number(5); i number(5):=3; num:=&num; dbms_output.put_line('THE FIBONACCI SERIES IS:'); dbms_output.put_line(f1); dbms_output.put_line(f2); while(i<=num) loop f3:=f1+f2; dbms_output.put_line(f3); f1:=f2; f2:=f3; i:=i+1; end loop;

END; / OUTPUT: SQL> start fib Enter value for num: 10 old 8: num:=&num; new 8: num:=10; THE FIBONACCI SERIES IS: 0 1 1 2 3 5 8 13 21 34

9. checking Palindrome To write a PL/SQL block to Check the Given String is Palindrome or Not.

32

DECLARE name1 varchar2(20); name2 varchar2(20); l number(5); BEGIN name1:='&name1'; l:=length(name1); while l>0 loop name2:=name2||substr(name1,l,1); l:=l-1; end loop; dbms_output.put_line('REVERSE OF STRING IS:'||NAME2); if(name1=name2) then dbms_output.put_line(name1||' IS PALINDROME '); else dbms_output.put_line(name1||' IS NOT PALINDROME '); end if; END; / OUTPUT: Enter value for name1: LIRIL old 6: name1:='&name1'; new 6: name1:='LIRIL'; REVERSE OF STRING IS:LIRIL LIRIL IS PALINDROME

SQL> / Enter value for name1: MADAM old 6: name1:='&name1'; new 6: name1:='MADAM'; REVERSE OF STRING IS:MADAM MADAM IS PALINDROME

RESULT: Thus the various programs were implemented and their output was verified.

EXPNO: 8 DATE :

PROCEDURES AND FUNCTION

AIM:

To write PL/SQL programs that execute the concept of functions and procedures.
33

DEFINITION A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task. They are essentially sub-programs. Procedures and functions are made up of,

**These procedures and functions do not show the errors. KEYWORDS AND THEIR PURPOSES: REPLACE: It recreates the procedure if it already exists. PROCEDURE: It is the name of the procedure to be created. ARGUMENT: It is the name of the argument to the procedure. Parenthesis can be omitted if no arguments are present. IN: Specifies that a value for the argument must be specified when calling the procedure ie. Used to pass values to a sub-program. This is the default parameter. OUT: Specifies that the procedure passes a value for this argument back to its calling environment after execution ie. Used to return values to a caller of the sub-program. INOUT: Specifies that a value for the argument must be specified when calling the procedure and that procedure passes a value for this argument back to its calling environment after execution. RETURN: It is the data type of the functions return value because every function must return a value, this clause is required.

1) PROCEDURE: SYNTAX:

A procedure is a sub program that performs a specific action. A procedure can accept parameters.

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;
Here, the parameter list and exception part are optional.

Executing a procedure:

SQL> exec procedure_name (parameter);

CREATING THE TABLE ITITEMS AND DISPLAYING THE CONTENTS SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4)); Table created.
34

ITEMID --------101 102 103

ACTUALPRICE ----------2000 3000 4000

ORDID PRODID -------- --------500 201 1600 202 600 202

PROGRAM FOR GENERAL PROCEDURE SELECTED RECORDS PRICE IS INCREMENTED BY 500 , EXECUTING THE PROCEDURE CREATED AND DISPLAYING THE UPDATED TABLE SQL> create procedure itsum(identity number, total number) is price number; null_price exception; begin select actualprice into price from ititems where itemid=identity; if price is null then raise null_price; else update ititems set actualprice=actualprice+total where itemid=identity; end if; exception when null_price then dbms_output.put_line('price is null'); end; / Procedure created. SQL> exec itsum(101, 500); PL/SQL procedure successfully completed. SQL> select * from ititems; ITEMID ACTUALPRICE ORDID PRODID --------- ----------- --------- --------101 2500 500 201 102 3000 1600 202 103 4000 600 202 PROCEDURE FOR IN PARAMETER CREATION, EXECUTION SQL> set serveroutput on; SQL> create procedure yyy (a IN number) is price number; begin select actualprice into price from ititems where itemid=a; dbms_output.put_line('Actual price is ' || price); if price is null then dbms_output.put_line('price is null'); end if; end; / Procedure created. SQL> exec yyy(103); Actual price is 4000
35

PL/SQL procedure successfully completed. PROCEDURE FOR OUT PARAMETER CREATION, EXECUTION SQL> set serveroutput on; SQL> create procedure zzz (a in number, b out number) is identity number; begin selectordid into identity from ititems where itemid=a; if identity<1000 then b:=100; end if; end; / Procedure created. SQL> declare a number; b number; begin zzz(101,b); dbms_output.put_line('The value of b is '|| b); end; / The value of b is 100 PL/SQL procedure successfully completed. PROCEDURE FOR INOUT PARAMETER CREATION, EXECUTION SQL> create procedure itit( ainout number) is begin a:=a+1; end; / Procedure created. SQL> declare a number:=7; begin itit(a); dbms_output.put_line('The updated value is '||a); end; / The updated value is 8 PL/SQL procedure successfully completed.
EXAMPLE AND OUTPUT: Create a table STOCK contains fields like stock code, stock name, available stock and last purchase date. Write a procedure to update the current stock value of the stock code. Write a function to display the last purchase date for any stock code. SQL>create table stock(sno number(3), sname char(10), avail_stock number(3), last_purchase date); 36

Table created.

SQL>select * from stock; SNO SNAME AVAIL_STOCK LAST_PURCHASE 1 Mouse 20 23-jul-09 2 Keyboard 30 20-jul-09 3 Printer 35 18-jul-09 i)PROCEDURE: SQL>ed pro1; create or replace procedure store1(ino in number, avail in number) as a date; begin selectlast_purchase into a from stock where sno=ino; ifmonths_between(sysdate,a)<=12 then update stock set avail_stock=avail_stock+avail where sno=ino; else delete from stock where sno=ino; end if; end; SQL>set serveroutput on; SQL>@ pro1; 10 / Procedure created. SQL>edcal; declare ino number(3); avail number(3); begin ino := &ino; avail := &avail; store(ino,avail); end; SQL>@ cal; 9/ Enter value for INO: 1 Old 5: ino :=&ino; New 5: ino :=1; Enter value for avail=20 Old 5: avail :=&avail; New 5 : avail :=20; PL/SQL procedure successfully completed. OUTPUT: SQL>select * from stock; SNO SNAME AVAIL_STOCK LAST_UPDATE 37

1 2 3

Mouse 40 Keyboard 30 Printer 35

23-jul-09 20-jul-09 18-jul-09

2) FUNCTION: A function is a sub program that accepts arguments and returns a unique value to the caller. 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; **Here, exception part is optional and mode of operations can be in, out or inout.

CREATE THE TABLE ITTRAIN TO BE USED FOR FUNCTIONS SQL>create table ittrain( tno number(10), tfare number(10)); Table created. SQL>select * from ittrain; TNO TFARE --------- -----------1001 550 1002 600 PROGRAM FOR FUNCTION AND ITS EXECUTION SQL> create function aaa (trainnumber number) return number is trainfunctionittrain.tfare % type; begin selecttfare into trainfunction from ittrain where tno=trainnumber; return(trainfunction); end; / Function created. SQL> set serveroutput on; SQL> declare total number; begin total:=aaa (1001); dbms_output.put_line('Train fare is Rs. '||total); end; / Train fare is Rs.550 PL/SQL procedure successfully completed.
38

FACTORIAL OF A NUMBER USING FUNCTION PROGRAM AND EXECUTION SQL> create function itfact (a number) return number is fact number:=1; b number; begin b:=a; while b>0 loop fact:=fact*b; b:=b-1; end loop; return(fact); end; / Function created. SQL> set serveroutput on; SQL> declare a number:=7; f number(10); begin f:=itfact(a); dbms_output.put_line('The factorial of the given number is'||f); end; / The factorial of the given number is 5040 PL/SQL procedure successfully completed.
ii)FUNCTION: SQL>ed fun1; creatre or replace function fpho(ino number) return date is last_update date; begin; selectlast_purchase into last_update from stock where sno=ino; returnlast_update; end; SQL>set serveroutput on; SQL>@ fun1; 6/ Function created. SQL>ed subfun1; declare ino number(8); last_update date; begin ino:=ino; dbms_output.put_line(Last purchase date of stock number||ino||is||last_update); exception whenno_data_found then dbms_output.put_line(Check the number you have given); end; 39

OUTPUT: SQL>@ subfun1; 12 / Enter value for INO: 1 Old : 5 : ino:= &ino; New : 5 : ino:= 1; Last purchase date of stock number 1 is 23-jul-09. RESULT:

Thus the PL/SQL programs werefor procedure and functions has been executed successfully and the output is verified.

EXPNO: 9 DATE: AIM:

TRIGGERS

To write a PL/SQL program to manipulate record using triggers and update the result in the table. ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Create the trigger program and update the total. 4. After trigger creation insert the value in the total. 5. Stop the program. OVERVIEW TO TRIGGERS: A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. Trigger is pl/sql block or procedure that is associated with table,view,schema and database. Execute immidiately when particular event take place. SYNTAX: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] Where(condition) BEGIN SQL statements END;
40

TYPES OF TRIGGERS: There are two types of triggers based on the which level it is triggered. 1) Row level trigger - An event is triggered for each row upated, inserted or deleted. 2) Statement level trigger - An event is triggered for each sql statement executed. i) INSERT: BEFORE INSERT: To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of null values in DEPTNO column.
create or replace TRIGGER trig1 before insert on dept for each row DECLARE a number; BEGIN if(:new.d_id is Null) then raise_application_error(-20001,'error::deptno cannot be null'); else select count(*) into a from dept where d_id=:new.d_id; if(a=1) then raise_application_error(-20002,'error:: cannot have duplicate deptno'); end if; end if; END; OUTPUT: SQL> INSERT INTO DEPT VALUES('','SSS');(NULL VALUE) INSERT INTO DEPT VALUES('','SSS') * ERROR at line 1: ORA-20001: error::deptno cannot be null ORA-06512: at "SYSTEM.TRIG1", line 5 ORA-04088: error during execution of trigger 'SYSTEM.TRIG1' SQL> INSERT INTO DEPT VALUES(13,'SSS'); (SAME VALUE) INSERT INTO DEPT VALUES(13,'SSS') * ERROR at line 1: ORA-20002: error:: cannot have duplicate deptno ORA-06512: at "SYSTEM.TRIG1", line 13 ORA-04088: error during execution of trigger 'SYSTEM.TRIG1' AFTER INSERT:

SQL> create or replace trigger trig after insert on emp begin update emp set net_sal=(salary*0.15)+salary; end; / SQL> select * from emp; ENO ENAME SALARY NET_SAL ---------- -------------------- ---------- ---------2 Nares 3000 3500
41

3 Saru 5 ERN 1 SEN

5400 4000 3000

6667 3500 3500

SQL> insert into emp values(4,'dana',5000,null); 1 row created. SQL> select * from emp; ENO ENAME SALARY NET_SAL ---------- -------------------- ---------- ---------2 Nares 3000 3450 3 Saru 5400 6210 4 dana 5000 5750 5 ERN 4000 4600 1 SEN 3000 3450 AFTER INSERT: SQL>create or replace trigger tri2 after insert on vote222 for each row declare a number(5); begin a:=:new.idno; delete from vote111 where idno=a; end; / SQL>insert into vote111 values(1,abcd,12,main rd); 1 row created. SQL>select * from vote111; IDNO NAME ADDR 1 Abcd 12,main rd SQL>insert into vote222 values (1,abcd,12,main rd); AFTER EXECUTION: SQL>select * from vote111; IDNO NAME ADDR

SQL>select * from vote222; IDNO NAME ADDR 1 Abcd 12,main rd ii) UPDATE: BEFORE UPDATE:
CREATE OR REPLACE TRIGGER TRIGGER1 BEFORE UPDATE ON T1 FOR EACH ROW 42

when (new.age > old.age) BEGIN insert into t1 values(:old.tno, :old.tname, :new.age); END; / OUTPUT: SQL> UPDATE T1 SET AGE=20 WHERE TNO=2; UPDATE T1 SET AGE=20 WHERE TNO=2 * ERROR at line 1: ORA-04091: table SYSTEM.T1 is mutating, trigger/function may not see it ORA-06512: at "SYSTEM.TRIGGER1", line 2 ORA-04088: error during execution of trigger 'SYSTEM.TRIGGER1' SQL> UPDATE T1 SET AGE=25 WHERE TNO=2; 1 row updated.

BEFORE INSERT/UPDATE:
CREATE OR REPLACE TRIGGER UPPERCASE BEFORE INSERT OR UPDATE ON STUDENT FOR EACH ROW BEGIN :new.sname:=UPPER(:new.sname); :new.lname:=UPPER(:new.lname); END UPPERCASE; / OUTPUT: SQL> insert into student values(5,'daya','nandhan'); 1 row created. SQL> select * from student; SNO SNAME LNAME ---------- ---------- -------------------2 sss nnnn 1 senthil kumar 3 karthi keyan 4 ravi chandaran 6 Muthu vel 5 DAYA NANDHAN iii) DELETE: BEFORE DELETE: CREATE OR REPLACE TRIGGER TRIG2 BEFORE DELETE ON EMP FOR EACH ROW BEGIN raise_application_error(-20010,'You cannot do manipulation'); END; /

43

SQL> DELETE FROM EMP WHERE ENO=1; DELETE FROM EMP WHERE ENO=1 * ERROR at line 1: ORA-20010: You cannot do manipulation ORA-06512: at "SYSTEM.TRIG2", line 2 ORA-04088: error during execution of trigger 'SYSTEM.TRIG2' BEFORE INSERT/UPDATE/ DELETE: SQL> ed trig22.sql; CREATE OR REPLACE TRIGGER LOG_emp BEFORE INSERT OR DELETE OR UPDATE ON emp FOR EACH ROW DECLARE v_ChangeType CHAR(1); v_sid varchar2(10); BEGIN IF INSERTING THEN V_ChangeType := 'I'; v_sid := :new.eno; ELSIF UPDATING THEN V_ChangeType := 'U'; v_sid := :new.eno; ELSE V_ChangeType := 'D'; v_sid := :old.eno; END IF; INSERT INTO log_emp VALUES (v_ChangeType, USER, SYSDATE, v_sid); END LOGSTUDENTCHANGES; / OUTPUT: SQL> @trig22.sql; Trigger created. SQL> select * from emp; ENO ENAME SALARY NET_SAL ---------- -------------------- ---------- ---------2 SEN 3000 3500 5 ERN 4000 3500 1 SEN 3000 3500 SQL> create table log_emp(Change_type varchar(3),Changed_by varchar(15),time tim estamp,Eno number(3)); Table created.

44

SQL> insert into emp values(3,'Saru',5400,6667); SQL> update emp set ename='Nares' where eno=2; SQL>delete from emp where eno=5; SQL> select * from log_emp;

CHANGE_TYPE CHANGED_BY I U D SYSTEM SYSTEM SYSTEM

TIME 01-FEB-11 09.07.45.000000000 PM 01-FEB-11 09.10.38.000000000 PM 01-FEB-11 09.12.28.000000000 PM

ENO 3 2 5

RESULT: Thus the above experiment for Trigger has been executed successfully and the output is verified.

Exp. No: 10 DATE:

CURSORS

AIM To study and execute the manipulation of cursor management DEFINITION OF CURSOR: A cursor is a pointer to the context area. A PL/SQL program can control the context area through the cursor. There are of 2 types of cursors: STATIC CURSCOR REF CURSOR 1. STATIC CURSOR: There are two types: Attributes: a)%notfound- No more records can be fetched from the cursor. b)%found- A record can be fetched from the cursor. c)%rowcount- The number of rows fetched from the cursor so far. d)%isopen- The cursor has been opened.
45

a)OPEN: SYNTAX: open <cursor_name>; b)FETCH: SYNTAX: fetch <cursor_name> into <column_name>; c)CLOSE: SYNTAX: close <cursor_name>; 2) REF CURSOR: i) Declaring cursor variable: SYNTAX: type <type_name> is refcursor [return return_type]; ii) Opening a cursor variable: SYNTAX: open <cursor_variable> for select_stmt; iii) Closing a cursor variable: SYNTAX: close <cursor_name>; EXAMPLE: 1. TO WRITE A PL/SQL BLOCK TO CALCULATE AND DISPLAY THE EMPOYEE SALARY USING CURSOR FOR LOOP Create a table named EMPLOYEE. Declare the cursor that contains empno, name, netsalary. Update the salary of employee by using the cursor. Update the bonus of the employee using the cursor. SQL>create table employee(eid number(3),ename char(10), basic number(5), da number(5),hra number(5), netsal number(10), bonus number(10),dno number(3)); SQL>insert into employee values(&eid,&ename,&basic,&da,&hra,&netsal,&bonus,&dno); SQL>insert into employee values(1,syed,5000,10,1000,0,0,11); SQL>ed cur1; declare s1 employee.basic%type; e1 employee.eid%type; d1 employee.da%type; f1 employee.hra%type; n1 employee.netsal%type; b1 employee.bonus%type; cursor cur11 is select eid, basic, da, hra, netsal,bonus from employee; begin open cur11; loop fetch cur11 into e1,s1,d1,f1,n1,b1; update employee set netsal=s1+(s1*d1)/100+f1 where eid=e1; update employee set bonus=netsal+500 where eid=e1; exit when cur11%notfound; end loop; close cur11; end; /
46

SQL>@ cur1; PL/SQL procedure successfully completed. OUTPUT: SQL>select * from employee; EID ENAME BASIC DA HRA NETSAL BONUS DNO 1 syed 5000 10 1000 6500 7000 11 2 Ram 6300 20 1200 8760 9260 12 3 Kumar 7500 50 1500 12750 13250 11 2. TO WRITE A PL/SQL BLOCK TO DISPLAY THE EMPOYEE ID AND EMPLOYEE NAME USING CURSOR FOR LOOP SQL> set serveroutput on; SQL>ed cur12 declare begin for emy in (select eid,ename from employee) loop dbms_output.put_line('Employee id and employee name are '|| emy.eid ||' and '|| emy.ename); end loop; end; / OUTPUT: SQL>@cur12; Employee id and employee name are 1 and syed Employee id and employee name are 2 and Ram Employee id and employee name are 3 and Kumar PL/SQL procedure successfully completed. 3. TO WRITE A PL/SQL BLOCK TO UPDATE THE SALARY OF ALL EMPLOYEES WHERE DEPARTMENT NO IS 11 BY 5000 USING CURSOR FOR LOOP AND TO DISPLAY THE UPDATED TABLE SQL> set serveroutput on; SQL> declare cursor cem is select eid,ename,netsal,dno from employee where dno=11; begin --open cem; for rem in cem loop update employee set netsal=rem.netsal+5000 where eid=rem.eid; end loop; --close cem; end; / SQL>@curr12 PL/SQL procedure successfully completed. SQL> select * from employee; EID ENAME BASIC DA HRA NETSAL BONUS DNO 1 syed 5000 10 1000 11500 7000 11 2 Ram 6300 20 1200 8760 9260 12
47

Kumar 7500 50 1500 17750 13250 11

4. TO WRITE A PL/SQL BLOCK TO DISPLAY THE EMPLOYEE ID AND EMPLOYEE NAME WHERE DEPARTMENT NUMBER IS 11 USING EXPLICIT CURSORS SQL> set serveroutput on; SQL> ed curr33 declare cursor cenl is select eid,netsal from employee where dno=11; ecode employee.eid%type; esal employee.netsal%type; begin open cenl; loop fetch cenl into ecode,esal; exit when cenl%notfound; dbms_output.put_line(' Employee code and employee salary are ' || ecode ||' and '|| esal); end loop; close cenl; end; / OUTPUT: SQL>@curr33 Employee code and employee salary are 1 and 11500 Employee code and employee salary are 3 and 17750 PL/SQL procedure successfully completed. 5. TO WRITE A PL/SQL BLOCK TO UPDATE THE SALARY BY 5000 WHERE THE DEPARTMENT NUMBER IS 11, TO CHECK IF UPDATES ARE MADE USING IMPLICIT CURSORS AND TO DISPLAY THE UPDATED TABLE SQL> ed cur4; declare county number; begin update employee set netsal=netsal+1 where dno=&dno; county:= sql%rowcount; if county > 0 then dbms_output.put_line('The number of rows are '|| county); end if; if sql %found then dbms_output.put_line('Employee record modification successful'); else if sql%notfound then dbms_output.put_line('Employee record is not found'); end if; end if; end; / OUTPUT: SQL> @curr4 Enter value for dno: 12
48

old 4: update employee set netsal=netsal+1 where dno=&dno; new 4: update employee set netsal=netsal+1 where dno=12; The number of rows are 1 Employee record modification successful PL/SQL procedure successfully completed. SQL> / Enter value for dno: 13 old 4: update employee set netsal=netsal+1 where dno=&dno; new 4: update employee set netsal=netsal+1 where dno=13; Employee record is not found PL/SQL procedure successfully completed. SQL> select * from employee; EID ENAME BASIC DA HRA NETSAL BONUS DNO 1 syed 5000 10 1000 11500 7000 11 2 Ram 6300 20 1200 8761 9260 12 3 Kumar 7500 50 1500 17750 13250 11

6. To write a Cursor to display the list of Employees and Total Salary Department wise. SQL>ed curdept; DECLARE cursor c1 is select * from dept; cursor c2 is select * from employee; s employee.netsal%type; BEGIN for i in c1 loop s:=0; dbms_OUTPUT.put_line('----------------------------------------------'); dbms_OUTPUT.put_line('Department is :' || i.dno ||' Department name is:' || i.dname); dbms_OUTPUT.put_line('-------------------------------------------'); for j in c2 loop if ( i.dno=j.dno) then s:=s+j.netsal; dbms_OUTPUT.put_line(j.eid|| ' '|| j.ename || ' '|| j.netsal ); end if; end loop; dbms_OUTPUT.put_line('----------------------------------------------'); dbms_OUTPUT.put_line('Total salary is: '|| s); dbms_OUTPUT.put_line('----------------------------------------------'); end loop; END; / OUTUT: SQL> @curdept
49

---------------------------------------------Department is :11 Department name is:Accounts ------------------------------------------1 syed 11500 3 Kumar 17750 ---------------------------------------------Total salary is: 29250 ------------------------------------------------------------------------------------------Department is :12 Department name is:Sales ------------------------------------------2 Ram 8761 ---------------------------------------------Total salary is: 8761 ---------------------------------------------PL/SQL procedure successfully completed. RESULT Thus the various operations were performed on the table using cursors and the output was verified.

DATA BASE OBJECTS


Exp. No: 11 DATE:

AIM:

To execute SQL queries for database objects such as synonyms and sequences.

PROCEDURE:
WORKING WITH SQL COMMANDS

Synonyms provide a mechanism to create an alternate name for an object. For example, say USER1 is the currently connected user, and USER1 has select access to USER2s EMP table. Without a synonym, USER1 must select from USER2s EMP table as follows: SQL> select * from user2.emp; With a synonym, USER1 can do the following: SQL> create synonym emp for user2.emp; SQL> select * from emp; You can create synonyms for the following types of database objects: Tables 50

Synonyms

Views or object views PL/SQL packages, procedures, and functions Creating table in the user:system SQL> create table hotel31(hotel_id number(10) primary key,hotel_name char(10),hotel_address char(10),hotel_phno number(10),hotel_fax number(10)); Table created. SQL> desc hotel31; Name Null? Type ----------------------------------------- -------- ---------------------------HOTEL_ID NOT NULL NUMBER(10) HOTEL_NAME CHAR(10) HOTEL_ADDRESS CHAR(10) HOTEL_PHNO NUMBER(10) HOTEL_FAX NUMBER(10) SQL> insert into hotel31 values(1,'resh','calicut',4545,343); 1 row created. SQL> insert into hotel31 values(2,'ravi','calicut',2343,343); 1 row created. SQL> select * from hotel31; HOTEL_ID HOTEL_NAME HOTEL_ADDR HOTEL_PHNO HOTEL_FAX ---------- ---------- ---------- ---------- ---------1 resh calicut 4545 343 2 ravi calicut 2343 343 Creating synonym in user:sys as sysdba Simple synonym: SQL> create synonym hotel42 for system.hotel31; Synonym created. SQL> desc hotel42; Name Null? Type ----------------------------------------- -------- ---------------------------HOTEL_ID NOT NULL NUMBER(10) HOTEL_NAME CHAR(10) HOTEL_ADDRESS CHAR(10) HOTEL_PHNO NUMBER(10) HOTEL_FAX NUMBER(10) SQL> select * from hotel42; no rows selected 51

creating public synonym: SQL> create public synonym hotel41 for system.hotel31; Synonym created. SQL> desc hotel41; Name Null? Type ----------------------------------------- -------- ---------------------------HOTEL_ID HOTEL_NAME HOTEL_ADDRESS HOTEL_PHNO HOTEL_FAX SQL> select * from hotel41; no rows selected SQL> select * from hotel31; select * from hotel31 * ERROR at line 1: ORA-00942: table or view does not exist NOT NULL NUMBER(10) CHAR(10) CHAR(10) NUMBER(10) NUMBER(10)

*cant manipulate original table on another user. SEQUENCES:


Syntax: create sequence < sequence_name> .... SQL> create sequence hotel_id increment by 1 start with 1 maxvalue 100; Sequence created. SQL> select hotel_id.nextval from dual;

NEXTVAL ---------1 SQL> select hotel_id.nextval from dual; NEXTVAL ---------2 SQL> create sequence sno increment by 1 start with 1 maxvalue 100; Sequence created. SQL> create table stu(sid number(5),sname varchar2(10)); Table created. SQL> insert into stu values(hotel_id.nextval,'prabhu'); 1 row created.

52

SQL> insert into stu values(hotel_id.nextval,'prabhu'); 1 row created. SQL> select * from stu; SID SNAME ---------- ---------3 prabhu 4 prabhu SQL> create sequence no increment by 1 start with 1 maxvalue 100; Sequence created. SQL> create table emp(eid number(5),ename varchar2(10)); Table created. SQL> insert into emp values(no.nextval,'prabhu'); 1 row created. SQL> select * from emp; EID ENAME ---------- ---------1 prabhu SQL> insert into emp values(no.nextval,'prabhu'); 1 row created. SQL> select * from emp; EID ENAME ---------- ---------1 prabhu 2 prabhu SQL> insert into stu values(no.nextval,'raj'); 1 row created. SQL> select * from stu; SID SNAME ---------- ---------3 prabhu 4 prabhu 3 raj SQL> select no.nextval from dual; NEXTVAL 53

---------4 SQL> select no.nextval ,no.currval from dual; NEXTVAL CURRVAL ---------- ---------5 5

RESULT:

Thus the SQL Queries for database objects such as synonyms, sequences, view and index are verified and executed successfully.

Exp. No: 12 DATE:

STUDENT RECORD MANAGEMENT

AIM: To write a PL/SQL program for manipulating the student record and store it in the table. ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Get the student number 4. Get the information into the main table. 5. Find and calculate the total,average,result,grade. 6. Insert the record in sub table. 7. Stop the program. WORKED WITH SQL & PL/SQL: create table std_details(sno number(5) primary key,sname varchar2(25),mark1 number(3),mark2 number(3),mark3 number(3),tot number(3),savg number(3),result varchar2(10), grade varchar2(10)); create table std_main1((sno number(5),sname varchar2(35), mark1 number(3), mark2 number(3), mark3 number(3)); Output: Table created SQL>insert into std_main1 values(&sno,&sname,&mark1,&mark2,&mark3); SQL> Select 8 from std_main1; sno Sname Mark1 Mark2 Mark3 1 Sivakumar 90 98 97 2 Yasodha 89 96 99 3 Kala 66 77 88 54

4 5

Mala Raja

90 40

80 50

70 60

6 rows selected. SQL> desc std_details; Output: Name Null? Type SNO NUMBER(5) SNAME VARCHAR2(25) MARK1 NUMBER(3) MARK2 NUMBER(3) MARK3 NUMBER(3) TOT NUMBER(3) SAVG NUMBER(3) RESULT VARCHAR2(10) GRADE VARCHAR2(10)

declare no number(5); na varchar2(20); m1 number(3); m2 number(3); m3 number(3); t number(3); a number(3); r varchar2(10); g varchar2(10); x number(3); begin x:=&x; select sno,sname,mark1,mark2,mark3 into no,na,m1,m2,m3 from std_main1 where sno=x; t:=m1+m2+m3; a:=t/3; if(m1>=50 and m2>=50 and m3>=50) then r:=pass; else r:=fail; end if; if(a<=75) then g:=o; elsif(a>=60) then g:=A; elsif(a>=50) then g:=B; else g:=-; 55

end if; dbms_output.put_line(no); insert into std_details values(no,na,m1,m2,m3,t,a,r,g); dbms_output.put_line(data inserted); end; / output: Enter value for student_no: 1 Old 13: X:=&X; New 13:X:=1; 1 Data inserted PL/SQL procedure successfully completed. SQL>select *from std_details; SNO SNAME MARK1 MARK2 1 HARI 90 98

MARK3 97

TOT 285

SAVG 96

RESULT PASS

RESULT: Thus the PL/SQL program wasv executed and verified successfully.

Exp. No: 13 DATE:

ELECTION PROCESSING

AIM: To write a PL/SQL program to perform election processing and update the result in the table.

ALGORITHM: 1. Start the program 2. Declare the variables 3. Get the number of record in the table. 4. Using for loop, find the total result 5. Update the total result to the respective records in the table. 6. Stop the program. TABLE STRUCTURE: SQL>descele; Name NAME NO PLACE1 PLACE2 PLACE3 RESULT

Null?

Type VARCHAR2(10) NUMBER(3) NUMBER(5) NUMBER(5) NUMBER(3) VARCHAR2(15) 56

TOTAL PROGRAM:

NUMBER(10)

declare i number; c number; t number; v number; v1 number; rvarchar(20); p1 ele.place1%type; p2 ele.place2%type; p3 ele.place3%type; begin select count(*) into c from ele; v:=0; v1:=0; for i in 1..c loop select place1,place2,place3 into p1,p2,p3 from ele where no=i; t:=p1+p2+p3; updateele set total=t where no=i; if t<1000 then r:='depo lost'; updateele set result=r where result='pass'; end if; if t>=v then v1:=v; v:=t; end if; if v1<t and t<v then v1:=t; end if; end loop; dbms_output.put_line(v); dbms_output.put_line(v1); if v=v1 then dbms_output.put_line('Re election'); end if; updateele set result='winner' where total=v and result='depo lost'; updateele set result='runner' where total=v1 and result='depo lost'; end; / TABLE BEFORE EXECUTION: SQL> select *from ele; NAME prabhu harish danesh raja NO 1 2 3 4 PLACE1 10000 10040 24040 54 PLACE2 20000 2000 12000 65 57 PLACE3 10024 11002 1002 45 RESULT PASS PASS PASS PASS TOTAL 0 0 0 0

Senthur

20000

15000

10004

PASS

Output: SQL> set serveroutput on; SQL>@ele.sql; PL/SQL procedure successfully completed. TABLE AFTER EXCUTION: SQL> select * from ele; NAME NO PLACE1 PLACE2 PLACE3 RESULT TOTAL prabhu 1 10000 20000 10024 RUNNER 40024 harish 2 10040 2000 11002 DEPO LOST 23042 danesh 3 24040 12000 1002 DEPO LOST 37042 raja 4 54 65 45 DEPO LOST 164 Senthur 5 20000 15000 10004 WINNER 45004

RESULT: Thus the PL/SQL program were executed successfully and hence verified.

PARROLL PROCESSING
Exp. No: 14 DATE:

AIM:
To write a PL/SQL program to perform payroll processing using cursor methods and update the result in the table.

ALGORITHM:
1. 2. 3. 4. 5. start the program Declare the variable and set cursor. Open the cursor and fetch into r. Update the results to the respective records in the table. Stop the program.

TABLE STRUCTURES:
SQL>desc pay1; 58

Name Null? Type ----------------------------------------- -------- -----------------IDNO EMPNAME SALARY DA HRA PF GP TAX NP NOT NULL NUMBER(5) VARCHAR2(20) NUMBER(10) NUMBER(38) NUMBER(38) NUMBER(38) NUMBER(38) NUMBER(10) NUMBER(10)

PROGRAM: Declare Cursor turbo is select * from pay1 where idno>=1; r pay1%rowtype; begin open turbo; loop fetch turbo into r; exit when turbo%notfound; update pay1 set da=015*salary where idno=r.idno; update pay1 set hra=0.2*salary where idno=r.idno; update pay1 set pf=0.1*salary where idno=r.idno; update pay1 set gp=salary+da+hra where idno=r.idno; if(r.salary<20000) and (r.salary<40000) then update pay1 set tax=0.1*r.salary where idno=r.idno; end if; if(r.salary<40000)and (r.salary<100000) then update pay1 set tax=0.2*r.salary where idno=r.idno; end if; if(r.salary<100000) and (r.salary<150000) then update pay1 set tax=0.3*r.salary where idno=r.idno; end if; update pay1 set np=(gp-(pf+tax)) where idno=r.idno; end loop; close turbo; end; /

TABLE BEFORE EXECUTION: SQL> select * from pay1; IDNO EMPNAME SALARY 1 Prabhu 10000 2 Harish 20000 3 Sadish 50698 SQL>set serveroutput on; 59 DA 0 0 0 HRA 0 0 0 PF 0 0 0 GP 0 0 0 TAX 0 0 0 NP 0 0 0

SQL>@pay1.sql; TABLE AFTER EXECUTION: SQL> select * from pay1; IDNO EMPNAME SALARY 1 Prabhu 10000 2 Harish 20000 3 Sadish 50698 4 Arun 3000 DA 150000 300000 760470 45000 HRA 2000 4000 10140 600 PF 1000 2000 5070 300 GP 162000 324000 821308 48600 TAX 3000 6000 15209 900 NP 158000 316000 801029 47400

RESULT: Thus the PL/SQL Program was executed successfully.

EMPLOYEES RECORDS USING ADO WITH ODBC


Exp. No: 15 DATE:

Aim
To design a form employee records using visual basic the following properties. a) ADODC properties b) ADODB properties ALGORITHM: a) ADODC properties: 1. Start vb 6.0 and select a new standard exe project. 2. Go to the project menu and select components, which open windows. Select ADO data control 6.0 (OLEDB) and click ok. this will add tool box. 3. Add the ADO data control to the new form and used to be. 4. Add the ADO data control ADODC properties. 5. In the screen choose use connection strings option, select Microsoft OLEDB provider for oracle to use the connect data base, click next button. 6. Click the authentication tab and provide user. 7. Click record source property to specify the name of the table. 8. In the command button, select 2-adcmd table. 9. Select EMP table name from the column table or stored procedure. 10. Place a text box named TEXT!> set it as adodc1 the field name and sl.no. 11. Save the form and press the F5 button. b) ADODB properties. 1. Start vb 6.0 and select a new standard exe project. 2. Go to the project menu and select references, which open windows, Active data object 2.5 library and click OK. 3. Create the form and add control. 4. Write the program for each control. 5. Save the program for each control. 60

6. Stop the process.

EMPLOYEESDESIGN WINDOW

Login Page:

Private Sub Command1_Click() If Text1.Text = "admin" And Text2.Text = "123" Then Unload Me Main.Show End If End Sub Private Sub Command2_Click() Unload Me End Sub Private Sub Text2_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then Command1_Click End If End Sub

Main Page:

61

Private Sub Command1_Click() Unload Me Employee_Details.Show End Sub Private Sub Command2_Click() Unload Me View_form.Show End Sub

Employee Details:

62

Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim

con As New ADODB.Connection oconn As New ADODB.Connection cmd As New ADODB.Command rs As New ADODB.Recordset rs1 As New ADODB.Recordset rs2 As New ADODB.Recordset st2 As String strSQL As String s1 As String s2 As String s3 As String s4 As String s5 As String constr As String rec1 As Integer rec2 As Integer delrec_orcl As Integer st1, storc, storc1 As String c2str As String

Private Sub AdvSearch_Click() Unload Me AD_SEARCH.Show End Sub Private Sub Clear_Click() Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" End Sub Private Sub CLose_Click() 63

Unload Me End Sub Private Sub Command1_Click() Unload Me Main.Show End Sub Private Sub Delete_Access_Click() con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\emp.mdb;Persist Security Info=False" s2 = Val(Text1.Text) s3 = Text2.Text s4 = Val(Text3.Text) s5 = Val(Text4.Text) c2str = "delete from emp where emp_id=" + s2 con.Execute c2str con.CLose Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" MsgBox "Records deleted Successfully", vbOKOnly Unload Me Employee_Details.Show End Sub Private Sub Delete_orcl_Click() oconn.Open s1, "system", "123" storc = "select * from emp where eid=" + Text1.Text s2 = Val(Text1.Text) s3 = Text2.Text s4 = Val(Text3.Text) s5 = Val(Text4.Text) rs2.Open storc, oconn, adOpenDynamic, adLockBatchOptimistic delrec_orcl = 0 delrec_orcl = rs2.RecordCount If delrec_orcl < 1 Then MsgBox "No Records Found", vbOKOnly Else c2str = "delete from emp where eid=" + s2 oconn.Execute c2str MsgBox "Records deleted Successfully", vbOKOnly End If oconn.CLose Unload Me Employee_Details.Show End Sub Private Sub Form_Load() s1 = "Provider=MSDASQL.1;Persist Security Info=False;User ID=system;Data Source=emp1" cmd.CommandType = adCmdText Set oconn = New ADODB.Connection 64

oconn.Provider = "MSDASQL.1;Persist Security Info=False;Extended Properties=DRIVER={Oracle in OraDb11g_home1};SERVER=ORCL;UID=system;DBQ=ORCL;DBA=W;APA=T;EXC=F;XSM=Default;FEN= T;QTO=T;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS= T;MDI=Me;CSR=F;FWC=F;FBS=60000;TLO=O;MLD=0;ODA=F;" rs.CursorType = adOpenStatic rs.CursorLocation = adUseClient rs.LockType = adLockOptimistic rs1.CursorType = adOpenStatic rs1.CursorLocation = adUseClient rs1.LockType = adLockOptimistic rs2.CursorType = adOpenStatic rs2.CursorLocation = adUseClient rs2.LockType = adLockOptimistic End Sub Private Sub Insert_Click() con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\emp.mdb;Persist Security Info=False" st1 = "insert into emp values(" + Text1.Text + ",'" + Text2.Text + "' ," + Text3.Text + " ," + Text4.Text + " )" rs.Open st1, con, adOpenDynamic, adLockOptimistic Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" Unload Me con.CLose Employee_Details.Show MsgBox "Inserted successfully", vbOKCancel End Sub Private Sub Insert_orcl_Click() oconn.Open s1, "system", "123" strSQL = "insert into emp values(" + Text1.Text + ",'" + Text2.Text + "' ," + Text3.Text + " ," + Text4.Text + " )" rs1.Open strSQL, oconn, adOpenStatic, adLockOptimistic Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" Unload Me Employee_Details.Show MsgBox "Inserted successfully", vbOKCancel End Sub Private Sub Search_Access_Click() con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\emp.mdb;Persist Security Info=False" st1 = "select * from emp where emp_id=" + Text1.Text con.Execute st1 rs.Open st1, con, adOpenDynamic, adLockOptimistic rec1 = rs.RecordCount If rec1 = 0 Then MsgBox "No Records Found", vbOKOnly Else 65

Text1.Text = rs.Fields(0) Text2.Text = rs.Fields(1) Text3.Text = rs.Fields(2) Text4.Text = rs.Fields(3) End If con.CLose End Sub Private Sub Search_orcl_Click() oconn.Open s1, "system", "123" storc = "select * from emp where eid=" + Text1.Text oconn.Execute storc rs1.Open storc, oconn, adOpenDynamic, adLockBatchOptimistic rec2 = rs1.RecordCount If rec2 = 0 Then MsgBox "No Records Found", vbOKOnly Else Text1.Text = rs1.Fields(0) Text2.Text = rs1.Fields(1) Text3.Text = rs1.Fields(2) Text4.Text = rs1.Fields(3) End If rs1.CLose oconn.CLose End Sub Private Sub Update_Access_Click() con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\emp.mdb;Persist Security Info=False" s2 = Val(Text1.Text) s3 = Text2.Text s4 = Val(Text3.Text) s5 = Val(Text4.Text) c2str = "update emp set emp_name='" + s3 + "' , age = " + s4 + ", salary = " + s5 + " where emp_id=" + s2 con.Execute c2str con.CLose MsgBox "Records Updated Successfully", vbOKOnly Unload Me Employee_Details.Show End Sub Private Sub Update_orcl_Click() oconn.Open s1, "system", "123" s2 = Val(Text1.Text) s3 = Text2.Text s4 = Val(Text3.Text) s5 = Val(Text4.Text) c2str = "update emp set ename='" + s3 + "' , age = " + s4 + ", salary = " + s5 + " where eid=" + s2 oconn.Execute c2str oconn.CLose MsgBox "Records Updated Successfully", vbOKOnly Unload Me Employee_Details.Show End Sub

66

Advanced Search:

Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim Dim

con As New ADODB.Connection oconn As New ADODB.Connection cmd As New ADODB.Command rs As New ADODB.Recordset rs1 As New ADODB.Recordset rs2 As New ADODB.Recordset st2 As String strSQL As String s1 As String s2 As String s3 As String s4 As String s5 As String constr As String rec1 As Integer rec2 As Integer delrec_orcl As Integer st1, storc, storc1 As String c2str As String oconnstr As String

Private Sub btn_advSearch_Click() If oconn.State = 1 Then oconn.CLose End If If oconn.State = 0 Then oconn.Open oconnstr, "system", "123" End If strSQL = "select * from emp" 67

If txt_strtAge <> "" And txt_endAge <> "" And txt_strtSal <> "" And txt_endSal <> "" Then strSQL = strSQL + " where salary between " + txt_strtSal + " and " + txt_endSal + " and " + "age between " + txt_strtAge + " and " + txt_endAge End If If rs.State = 0 Then rs.CursorLocation = adUseClient rs.Open strSQL, oconn, adOpenDynamic, adLockOptimistic ElseIf rs.State = 1 Then rs.CLose End If cmd.CommandType = adCmdText Set DataGrid1.DataSource = rs End Sub Public Sub close1() oconn.CLose End Sub Private Sub btn_back_Click() Unload Me Employee_Details.Show End Sub Private Sub btn_clear_Click() txt_empid.Text = "" txt_exatSal.Text = "" txt_endSal.Text = "" txt_grtSal.Text = "" End Sub Private Sub btn_close_Click() Unload Me End Sub Private Sub btn_search_Click() If oconn.State = 1 Then oconn.CLose End If If oconn.State = 0 Then oconn.Open oconnstr, "system", "123" End If strSQL = "select * from emp where " If txt_empid <> "" Then strSQL = strSQL + "eid=" + txt_empid End If If txt_strtName <> "" Then strSQL = strSQL + "ename like '" + txt_strtName + "%'" End If If txt_endName <> "" Then strSQL = strSQL + "ename like '%" + txt_endName + "'" End If If txt_exatAge <> "" Then strSQL = strSQL + "age=" + txt_exatAge End If 68 txt_strtName.Text = "" txt_endName.Text = "" txt_strtAge.Text = "" txt_lessSAl.Text = "" txt_exatAge.Text = "" txt_strtSal.Text = "" txt_endAge.Text = ""

If txt_exatSal <> "" Then strSQL = strSQL + "salary=" + txt_exatSal End If If txt_strtAge <> "" And txt_endAge <> "" Then strSQL = strSQL + "age between " + txt_strtAge + " and " + txt_endAge End If If txt_strtSal <> "" And txt_endSal <> "" Then strSQL = strSQL + "salary between " + txt_strtSal + " and " + txt_endSal End If If txt_lessSAl <> "" Then strSQL = strSQL + "salary < " + txt_lessSAl End If If txt_grtSal <> "" Then strSQL = strSQL + "salary > " + txt_grtSal End If If txt_empid <> "" And txt_strtName <> "" Then strSQL = "" strSQL = "select * from emp where " strSQL = strSQL + "eid=" + txt_empid + "and ename like '" + txt_strtName + "%'" End If 'If txt_empid = "" And txt_strtName = "" And txt_endName = "" And txt_exatAge = "" And txt_strtAge = "" Then 'MsgBox "Enter any details!!!", vbOKOnly 'Else If rs.State = 0 Then rs.CursorLocation = adUseClient rs.Open strSQL, oconn, adOpenDynamic, adLockOptimistic ElseIf rs.State = 1 Then rs.CLose End If cmd.CommandType = adCmdText rec2 = rs.RecordCount If rec2 = 0 Then MsgBox "No Records Found", vbOKOnly Else Set DataGrid1.DataSource = rs End If 'End If End Sub Private Sub Form_Load() Set oconn = New ADODB.Connection 'oconnstr = "Provider=MSDASQL.1;Persist Security Info=False;Extended Properties=DRIVER={Oracle in OraDb11g_home1};SERVER=ORCL;UID=system;password=123;DBQ=ORCL;BAM=IfAllSuccessful;" oconnstr = "Provider=MSDASQL.1;Persist Security Info=False;User ID=system;Data Source=emp1" End Sub Private Sub txt_empid_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then btn_search_Click End If End Sub Private Sub txt_exatAge_KeyPress(KeyAscii As Integer) 69

If KeyAscii = 13 Then btn_search_Click End If End Sub Private Sub txt_exatSal_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then btn_search_Click End If End Sub Private Sub txt_grtSal_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then btn_search_Click End If End Sub Private Sub txt_lessSAl_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then btn_search_Click End If End Sub Private Sub txt_strtName_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then btn_search_Click End If End Sub

View Details:

70

Private Sub Command1_Click() Unload Me End Sub Private Sub Command2_Click() Unload Me Main.Show End Sub

Result:
Thus the employee records using visual basic were executed successfully and hence verified.

71

You might also like