Professional Documents
Culture Documents
Rdbms Manual 0
Rdbms Manual 0
AUTHOR: M.Mageshwari M.Sc., MPhil., Lecturer, Department of CE, M.S.P.V.L.Polytechnic College, Pavoorchatram.
Page1
S.NO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 SQL Editor Command Column Commands Use Index on a Table SQL Function
PROGRAM
PAGE NO
5 11 17 19 26 35 39 44 48 52 56 60 64 68 71 76 81 84 88 95
Data Control Language Select Command in SQL *Plus Integrity Constraints Sub Queries Joins in Sql * Plus Logical Operator in SQL * PLUS Different Select Statements in SQL* Employee Details Using PL/SQL To Calculate EB Bill Using If Statement Built in Function using PL/SQL User Define Exception using PL/SQL Procedure & Function using PL/SQL Students Admission Using Trigger Employee Salary Detail Using Cursor DML Using ADO Creation Navigation object using ADO creation
EXTRA PROGRAMS
1 2 3 4 Transaction Control Language Sequence Creation View Synonyms 102 104 106 108
Page2
In the Oracle language RDBMS system is used to manipulate the database. This system is used to manipulate the database. This system accepts all user requests for insertion, updating and deletion of data. RDBMS engine is loaded and a remains running in the memory till the database operation is not complete. In the multiuser system RDBMS engine respond to multiuser request which is handled by RDBMS server known as Oracle server.
Step1:
Start windows in the normal way
Step2:
Click on the start button and click on Internet Explorer. It displays the Microsoft Internet Explorer home page.
Step3:
Login Screen You connect to the Login screen from your web browser with a URL like: http://machine_name.domain:port/isqlplus
Page3
Username:
Enter a valid username to connect to Oracle Database (mandatory).
Password:
Enter a valid password for the username (mandatory).
Connection Identifier:
Leave this field blank to use the default Oracle database, otherwise enter a connection identifier for the database you want to connect to. ISQL*Plus can be configured to restrict connections to specific databases. If restricted database access has been enabled, a dropdown list of available databases is displayed in place of the Connection Identifier text field. This enables greater security for iSQL*Plus Servers in hosted environments. This is configured using the iSQLPlusConnectIdList parameter in the configuration file.
Page4
Click the Login button to log in to iSQL*Plus. If you enter an invalid username or password, the Login screen is re-displayed with an error message.
Step4: Workspace
The Workspace consists of the Workspace, History and Load Script screens. After successfully logging in, the Workspace is displayed. From the Workspace you can:
Access Preferences screens Enter, Execute and Cancel scripts Load and Save scripts View, Save and Print output Log out Get help
The Workspace and History screens display the user's connection information in the top right. The connection information is displayed in the form:
Page5
Clear
Clears all statements in the Input area, and all displayed output. Cancels any script that may be running.
Execute
Executes the contents of the Input area. Depending on your preference settings, the results are displayed in the Output area, in a new web browser window, or saved to a file.
Load Script
Displays the Load Script screen where you enter a path and file name, or a URL for the script you want to load into the Input area for editing or execution.
Save Script
Displays the File > Save As dialog where you enter a file name for the script you want to save from the Input area as a plain text file. It may be useful to identify scripts with an extension of .SQL.
Cancel
Cancels any script that is currently running, but does not clear the Output area. A message saying that the script was cancelled is displayed.
Next Page
Displays the next page of report output. The Next Page button is displayed when there are more results to display than can fit on the current output page or the script contains a PAUSE command. You can configure whether pages are displayed on a single page or multiple pages using Preferences > Interface Configuration > Output Page Setup, or by executing the SET PAUSE ON or SET PAUSE OFF command.
Page6
Syntax:
The Describe Command:
DESC table_name;
Create Command:
CREATE TABLE <table name> (column1 datatype1,.. column datatype
n);
Alter Command:
ALTER TABLE <table name> MODIFY (column datatype,.); ALTER TABLE <table name> ADD (column datatype,.);
Insert Command:
INSERT INTO <table name> VALUES (value1, value2,.);
Select Command:
SELECT * FROM <table name>; (or)
Update Command:
UPDATE <table name> SET column1=expression, column2=expression..WHERE <search_condituin>;
Delete Command:
DELETE FROM <table name> [WHERE <search_condition>];
Page7
describe tabs; Name TABLE_NAME TABLESPACE_NAME CLUSTER_NAME IOT_NAME PCT_FREE PCT_USED INI_TRANS MAX_TRANS INITIAL_EXTENT NEXT_EXTENT MIN_EXTENTS MAX_EXTENTS PCT_INCREASE FREELISTS FREELIST_GROUPS LOGGING BACKED_UP NUM_ROWS select table_name from tabs order by table_name; TABLE_NAME EMP STUDENT Null? NOT NULL Type VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER VARCHAR2(3) VARCHAR2(1) NUMBER
Page8
You can use the describe command on the following views to obtain information on your account. View Name DICT DICT_COLUMN CAT OBJ TABS COLS USER_VIEWS SYN SEQ USER_CONSTRAINTS IND USER_IND_COLUMNS Description table names and table description column names of table names and column description names of all user's tables, views, synonyms, and sequences information on all objects in your account table information on all user's tables column information on all user's columns view information on all user's views synonyms information on all user's synonyms sequence information on all user's sequences constraint information on user's constraints index information on all user's indices column information on user's indices
Page9
Page10
structures like tables, indexes etc. It can also be used for interactive, data maintain. 3. How to create a table? The first letter should be an alphabet. Oracle reserve words cannot be used as table name The length of a table name should not exceed 30 characters Different tables should have different names. Underscore, numerals and letters are allowed. Blank space and single quote are not allowed. Double quotes can be used for naming a table. In this case the tables student, Student and STUDENT are all different tables. 4. How to change the structure of a table?
The structure of a table can be changed using this command. Using this command we can do the following. Add a new column Change the width of a data type Change the data type of a column Include an integrity constraint Drop an integrity constraint.
Page12
2. Column Commands
Aim:
To work the following conditions: a) Column formatting b) Alias and Column ordering
Syntax:
Column Formatting
COLUMN name_of_column FORMAT style
Column Alias
SELECT column name "alias name" FROM table
Order By
SELECT column FROM table ORDER BY column name
Query:
Table creation: create table emp(emp_no number,emp_name varchar2(8),desig varchar2(12),doj date,salary number(8),hra number(7));
Table created.
desc emp
Type
Page13
b) To change the width of the column, use the element A followed by the number of characters that the column must contain column desig format a4; select * from emp EMP_NO EMP_ DESI Mana ger desi gnin geng Lect urer Teac her soft ware eng DOJ 12-SEP-08 25-MAR-05 17-FEB-08 29-JAN-07 26-AUG-05 SALARY $20,000 $47,000 $17,000 $12,000 $47,000 HRA 600 1200 1000 700 1200
1111 Jeyanthi 1112 Seetha 1113 Glory 1113 Ratha 1114 Uma
c) To display the number in scientific notation, use EEEE format column hra format 9.9999EEEE; select * from emp EMP_NO EMP_ DESI Mana ger desi gnin geng Lect urer Teac her soft ware eng DOJ 12-SEP-08 25-MAR-05 17-FEB-08 29-JAN-07 26-AUG-05 SALARY $20,000 $47,000 $17,000 $12,000 $47,000 HRA 6.0000E+02 1.2000E+03 1.0000E+03 7.0000E+02 1.2000E+03
1111 Jeya nthi 1112 Seet ha 1113 Glor y 1113 Rath a 1114 Uma
Page15
output:
COLUMN emp_no ON HEADING 'EmployeeNumber'
f) Clear Settings column emp_name clear select * from emp; EmployeeNumber 1111 1112 1113 1113 1114 EMP_NAME Jeyanthi Seetha Glory Ratha Uma Designation Manager DOJ 12-SEP-08 SALARY HRA 20000 47000 17000 12000 47000 600 1200 1000 700 1200
Page16
SELECT EMP_NO,EMP_NAME from emp order by emp_name ASC; EMP_NO 1113 1111 1113 1112 1114 EMP_NAME Glory Jeyanthi Ratha Seetha Uma
Page17
1. What is the use of column command? The COLUMN controls column and column heading formatting. The options are all cumulative and may be entered either simultaneously on a single line.
2. How to change the column header? Column titles that are displayed by SQL* plus reflect the name given to the column in the table. We can define a title for a column that is more easily understood by using the HEADING parameter.
3. Data Definition Language Statements: When creating and managing any object in an oracle database, you use the Data Definition Language (DDL) elements of the SQL language. Create This statement add a new object to the database. You use it to create new tables, views, stored procedure and other objects. This statement is used to change the characteristics of tables, indexes and other objects in the database. The ALTER statement does not apply to all objects in the database.
Alter
4. How to use of ORDER by expr? Organizes the rows returned by SELECT command. Expr is expression, generally a field by which the rows will be stored. ASC/DESC The default is ASC; it sorts in ascending order. DESC sorts in descending order.
Page18
Composite Index
CREATE INDEX <Index_name> ON <table_name>(column_name1,);
Dropping Index
DROP INDEX <Index_name>;
Simple Index:
create index empno_index on emp(emp_no) Index created. select index_name,table_name from user_indexes; INDEX_NAME EMPNO_INDEX TABLE_NAME EMP
Composite Index:
create index emp_index on emp(emp_name,desig,salary) Index created. select index_name,index_type,table_name from user_indexes; INDEX_NAME EMP_INDEX EMPNO_INDEX
Resul lt:The query w execu T was uted successfully and output w verifie d was ed.
2. How to drop an in 2 ndex? When you no longer nee an inde you ca drop it using the DROP IN n ed ex, an e NDEX comma and. When the index is dropp n x ped, oracle removes any refere e ence to it from the data dictionary and frees any dis space used by the index. a sk u e
4. SQL Function
Aim:
To Work with the different categories of functions such as Math, Date, Aggregate and Conversion functions.
Syntax:
Math Numeric Function:
ABS(n); CEIL(n): COS(n); COSH(n); EXP(n);
Date Function
ADD_MONTH(date,month); LASY_DAY(date); MONTHS_BETWEEN(date1,date2); NEXT_DAY(date,day_name); ROUND(date,[format]);
Aggregate Function:
AVG(n); COUNT(n); MAX(n); MIN(n); STDDEV(n); VARIANCE(n);
Conversion functions:
TO_CHAR(date[,format]); TO_DATE(date[,format]); TO_NUMBER(date[,format]);
Math Function:
SELECT ABS(10), ABS(-10) FROM dual; ABS(10) 10 ABS(-10) 10
Page21
Date Function:
ADD_MONTH: select * from student; REGNO 101 103 104 105 NAME Mala viji mitha Mathu AGE 18 18 19 21 DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 SEX F F F M ADDRESS Tenkasi Tirunel chennai tenkasi PHONENO 240902 565776 234567 234789
select dob,add_months(dob,60) from student; DOB 12-SEP-89 31-MAR-89 15-SEP-88 19-SEP-86 ADD_MONTHS(DOB,60) 12-SEP-94 31-MAR-94 15-SEP-93 19-SEP-91
Page22
select months_between(doj,dob) from staff; MONTHS_BETWEEN(DOJ,DOB) 276.516129 261.709677 12 22 Next_Day: select next_day('6-apr-09','Monday') from dual; NEXT_DAY('6-APR-09 13-APR-09
Page23
Aggregate Function:
Avg: select avg(age) from student; AVG(AGE) 19 Count: select count(age) from student; COUNT(AGE) 4 Max: select max(age) from student; MAX(AGE) 21 Min: select min(age) from student; MIN(AGE) 18 Stddev: select stddev(age) from student; STDDEV(AGE) 1.41421356
Page24
Conversion functions: Conversion function converts a value from one data type to another. The conversion function are classified into three characters TO_CHAR (date conversion): Select name,to_char(dob,'day-month-year') from student; NAME Mala viji mitha Mathu TO_CHAR(DOB,'DAY-MONTH-YEAR') tuesday -september-nineteen eighty-nine friday -march -nineteen eighty-nine thursday -september-nineteen eighty-eight friday -september-nineteen eighty-six
TO_CHAR (Number conversion): create table stoc(item_name varchar2(10),stock number(10),cost number(10)); Table created. select * from stoc; ITEM_NAME computer printer UPS AC computer STOCK 100 50 75 10 10 COST 25000 1500 2000 30000 25000
Page25
TO_DATE: create table purchase_master(num number(5),trade_name varchar2(10), date_of_purchase date,no_of_item number(5));Table created. insert into purchase_master values(1,'JKTrade', to_date('01-Jan-2000','DD-MONYYYY'),200); 1 row created. insert into purchase_master values(1,'JTrade', to_date('01-January-2000','DDMON-YYYY'),200); 1 row created. NUM 1 1 To_number: select * from stoc; ITEM_NAME computer printer UPS AC computer
STOCK 100 50 75 10 10
Page26
Viva Questions:
1. What is function? An SQL function is a built-in-function that manipulates data items and returns a result. SQL functions may accept zero, one or more arguments. 2. How to use Date function? Date functions accept DATE input and may return value of data type or a number. 3. How to use aggregate function or group function? A group function returns one result row based on a group of rows.
Aim:
a) b) c) d) Create a table to show the salary details of the employees. Grant select and update privileges on above table to other users Grant all the privileges to some other users. Revoke all the above granted permissions.
Syntax:
Grant System Privilege:
GRANT system PRIVILEGE TO user
User creation:
Connect system/manager; Connected. create user mathu identified by mitha; User created. grant create session to mathu; Grant succeeded. grant create table to mathu;
Page28
Connect to user:
connect mathu/mitha; Connected.
Create a table:
create table employee(name varchar2(8),id_no number(5),job varchar2(8),dob date,doj date,salary number(7));Table created.
Insert a table:
insert into employee values('RAJA',1110,'lecturer','12-jun-86','12-jun-08',20000) 1 row created. insert into employee values('RAMA',1111,'LAWYER','12-MAY-80','12-jun06',20000) 1 row created. insert into employee values('PRABHU',1112,'COLLECTO','12-FEB-78','12-DEC08',50000) 1 row created.
Page29
Create a table:
connect santhya/silviya Connected. create table emp_sal(name varchar2(10),ta number(6),hra number(6),da number(6),bf number(5),netsalary number(6)); Table created.
Insert a table:
insert into emp_sal values('Raja',500,750,366,780,8000); 1 row created. insert into emp_sal values('Rama',750,1000,500,1200,10000); 1 row created. insert into emp_sal values('Prabhu',1000,1200,1500,1700,20000); 1 row created.
c. Gran all the p nt privileges to some other use s ers: connect mathu/m t mitha Connec cted select * from emp ployee NA AME RAJA RAMA PRABHU ID_NO I JOB DOB D DOJ SA ALARY 20000 20000 50000
oyee to san nthya grant all on emplo Grant su ucceeded. connect santhya/silviya t Connect ted. select * from math hu.employ yee
DO OB
DOJ
Delete f from math hu.employe where i ee id_no=1110 1 row deleted. d NAME E RAMA A PRABH HU Selva a ID_NO O 1111 1 1112 2 1114 4 JO OB LAW WYER COLLECTO doc ctor DOB 12-MAY-80 1 0 12-FEB-78 1 8 1 19-JUN-81 1 DO OJ 12-JU UN-06 12-DE EC-08 20-MA AY-06 SA ALARY 20000 2 50000 5 40000 4
update mathu.em mployee se dob='14et -feb-84' wh here id_no o=1114 1 row updated. u NAME E RAMA PRABHU Selva ID_N NO JO OB DOB 12 2-MAY-80 12 2-FEB-78 14 4-FEB-84 DO OJ 12-JUN N-06 12-DEC C-08 20-MAY Y-06 SA ALARY 20000 50000 40000
d. Revo oke all the above granted pe e ermissions s: Revoke select,upd date on em mp_sal from mathu m Revoke succeeded d. connect mathu/m t mitha Connec cted.
Resul lt:The query w execu T was uted successfully and output w verifie d was ed.
The CREATE USER command is responsible for the creation of new users. It creates a user or an account through which you can connect to the database, and establish the means by which oracle will allow the user access. 4. What are privileges? A privilege is an authorization given to the user to access and manipulate a database object in a certain way. There are two types of privileges: i. System privileges 5. What are system privileges? Oracle includes over 100 privileges that can be granted to users. They include the capability to create various database objects and modify the configuration of the database. The granting of these privileges is restricted to the DBA by default. Some of the most commonly granted system privileges are listed in the following table: ii. Object privileges
Privilege
Description
Enables a user to connect to the database instance. After creating a user, you need to grant the CREATE SESSION
CREATE SESSION
privilege; otherwise, the user cannot connect. Granting the CREATE SESSION privilege is not done automatically by oracle and must be granted explicitly.
Enables a user to create a table in his or her schema. Enables a user to create a view in his or her schema. Enables a user to create a private synonym in his or her schema. Enables a user to create another user in the database and specify the password and other settings at creation time.
CREATE USER
Privilege
SELECT INSER UPDATE DELETE ALTER INDEX REFERENCES EXECUTE
Granted On
Table, View, Sequence Table, View Table, View Table, View Table, Sequence Table Table Procedure, function, package
Aim:
a) Create a table student_master with the following fields name, Regno, dept and year with suitable data types. Use select command to do the following. b) Select the students name column. c) Display the unique rows. d) Sort the table in alphabetical order. e) Select all the students of a particular department.
Syntax:
Select Command:
SELECT * FROM <table_name>; (or)
a) Create a table student_master with the following fields name, Regno, dept and year with suitable data types. Use select command to do the following. create table student_master(regno number(8),name varchar(10),dept varchar(10),year number(4)); Table created. insert into student_master values(123,'Dhivya','Physics',1998); 1 row created.
b) Select the students name column. select name from student_master; NAME Dhivya Muthu Kala
c) Display the unique rows. insert into student_master values(124,'fdgdf','sgf',1998); 1 row created. select * from student_master; REGNO 123 124 125 124 NAME Dhivya Muthu Kala fdgdf DEPT Physics Maths Computer sgf YEAR 1998 2000 2003 1998
Page38
d) Sort the table in alphabetical order. select * from student_master order by name; REGNO 123 125 124 124 NAME Dhivya Kala Muthu fdgdf DEPT Physics Computer Maths sgf YEAR 1998 2003 2000 1998
e) Select all the students of a particular department. select * from student_master where dept='Computer'; REGNO 123 125 124 124 NAME Dhivya Kala Muthu fdgdf DEPT Physics Computer Maths sgf YEAR 1998 2003 2000 1998
Viva Questions:
Page39
The select command is used to retrieve the stored data from a table. To avoid the selection of duplicate rows, the distinct clause is used in the select statement.
2. What is sorting? To arrange the given numbers in ascending or desc order. 3. How to use select command? All SQL queries begin with the SELECT statement. This statement enables you to retrieve all data or only certain columns and rows in a table. It can also return data from more than one table. It enables you not only to retrieve data but also perform calculations on existing data and return the results of these calculations.
Arguments:
DISTINCT L ALL * Table View WHERE It means that only rows that are unique will be returned; any duplicates will be weeded out first. It means that all rows satisfying the conditions will be returned (this is the default). Selects all the columns of tables or views specified in FROM clause. It means that all columns from this table will be displayed. Select all the columns of the specified view. Filters the rows that will be displayed by the query. Without this clause, all the rows are displayed.
7. Integrity Constraints
Page40
a) Create a sales_order with s_order_no and product_no as primary key. Set other field store client number, delivery address, delivery date, order status. b) Add a new column for storing salesman number using ALTER command c) Set the s_order_no as foreign key as column constraint d) Set the s_order_no foreign key as table constraint
Syntax:
The Constraint Keyword:
CREATE TABLE <TABLE_NAME> (column 1 datatype CONSTRAINT <constraint_name> constraint definition, column2 datatype);
a) Create a sales_order with s_order_no and product_no as primary key. Set other field store client number, delivery address, delivery date, order status. create table sales_orders(s_order_no varchar2(6),product_no varchar2(6), client_no varchar2(6), dely_addr varchar2(25), dely_date date, order_status varchar2(10),PRIMARY KEY(s_order_no, product_no));
desc sales_order
Page41
b) Add a new column for storing salesman number using ALTER command Alter table sales_orders add (sales_man_no number(5)) Table altered. desc sales_orders Name S_ORDER_NO PRODUCT_NO CLIENT_NO DELY_ADDR DELY_DATE ORDER_STATUS SALES_MAN_NO Null? NOT NULL NOT NULL Type VARCHAR2(6) VARCHAR2(6) VARCHAR2(6) VARCHAR2(25) DATE VARCHAR2(10) NUMBER(5)
c) set the s_order_no as foreign key as column constraint select * from sales_order_det; S_ORDER_ NO 11 12 13 14 15 PNO 343 345 346 347 348 DESCRI QTY_ PTION ORD Arial shear Oil colgate Pears 10 34 56 45 35 QTY_DISP P_RATE 4 4 12 56 65 45 56 45 67 32 PROFIT_ SELL_ PER PRICE 67 76 20 15 13 12 50 18 24 14
Table creation n:
create t table sal_d d(s_order_n numbe no er(4) prima key,pro ary oduct varc char2(5),st tock number r(5)); Table cr reated. select * from sal_ _d; S_ORDE ER_NO 102 2 104 4 101 1 103 3 105 5 PRODU UCT UPS CPU COMP PU PRIN N KEYB B STOC CK 15 5 123 10 0 134 109
Table creation n:
create t table sales s_order1(s_ _order_no number(4 4),product_ _no varcha ar(5),clien nt_no number r(5),del_ad varcha ddr ar(8),dely_d date date,o ord_status varchar(8 s 8),primary y key(s_order_no,pr roduct_no o),foreign k key(s_order_no) refer rences sal_ _d); Table cr reated.
insert into sales_order1 values('1011','34','1110','Chennai','19-jan-09','Fulfiled') * ERROR at line 1: ORA-02291: integrity constraint (MAGESH.SYS_C005312) violated - parent key not found
Viva Questions:
1. What is meant by data integrity? The integrity of data can be verified and checked by data integrity systems. These systems are required at the time of supply of data that the user can be prevented from supplying data of specific nature.
2. What are the different types of data integrity? There are two types of data integrity a. Entity b. Referential The entity data integrity are a) Default Indicates the default value b) Not NULL The value is not NULL c) Unique The value needs to be unique d) Check The value should be within limits The referential integrity are a) Primary key b) Foreign key
Page44
The primary key value rule specifies that each row of a table must be
The referential integrity rule determines that the value or group of fields corresponds to the key fields of other tables
Reference
Restrict Set to NULL Set to default Cascade
Description
Disables the updating are deletion of the specified data. when specified data is updated or deleted, all the associated data is adjusted to NULL when specified data is updated or deleted, all the dependent data is adjusted to the default value When specified data is updated or deleted, all the dependent data is updated too. If a row that is referenced is deleted, all the dependent rows will also be deleted
No Action
Disables the updation and deletion of specified data. This id default operation in Oracle
5. Explain the column level constraints? If the constraints are defined along with the column definition, it is called column level constraint. Column level constraint can be applied to any one column at a time i.e. they are local to a specific column. If the constraint spans across multiple columns, the user will have to use table level constraints. 6. Explain the Table level constraints? If the data constraint attached to specific cell in a table references the contents of another cell in the table then the user will have to use table level constraints. Table level constraints are stored as a part of the global table definition.
Aim: a) Create a table student with their elective paper as one field b) Create another table staff with the subject names they have handled and number of times handled. c) Construct an English sentence to display the rows in the staff table. d) Use sub-query to display the information about students name and staff names where both have same subject names e) Display the subject name, staff name where same subject is handled by more than one staff f) Display the student, subject name where the subject is not at all handled any staff in the staff table.
Syntax:
SubQuery:
SELECT * FROM <table_name> where [condition]SELECT * FROM <tablename> where [search condition]
Multiple Queries:
SELECT DISTINCT (column name) FROM <table_name> where (column name)IN (SELECT * FROM <table_name> where[search condition] IN (SELECT * FROM <table_name> where [search condition];
a) Create a table student with their elective paper as one field: create table student (rollno number(5), name varchar2(10), age number(4), degree varchar2(4), subject varchar2(8)); Table created. insert into student values(123,'Mitha',25,'MSC','Java'); 1 row created. insert into student values(124,'Malar',24,'MCA','.Net'); 1 row created. insert into student values(125,'Santhiya',21,'ME','CG'); 1 row created.
b) Create another table staff with the subject names they have handled and number of times handled. create table staff(staff_id number(3), staff_name varchar2(8), subject_name varchar2(6), times_handled number(3)); Table created. insert into staff values (&staff_id,'&staff_name','&subject_name',×_handled);
c) construct a English sentence to display the rows in the staff table: select staff_name || ' handled' || subject_name || ' ' || times_handled || 'times.' from staff; STAFF_NAME||'HANDLED'||SUBJECT_NAME||''||TIMES_HANDLED||'TIME S.' Jeyam Prabha Jeya handled handled handled VC++ CG Java 4 2 3 times. times. times.
d) Use sub queries to display the information about students name and staff names where both have same subject names: select name, staff_name from student a, staff b where upper(subject)in(select upper(subject_name) from staff)and upper(a.subject)=upper(b.subject_name); NAME Ram Santhiya Mitha STAFF_NAME jeyam Prabha Jeya
e) Display the subject name, staff names where same subject is handled by more than one staff: insert into staff values(348,'Ravi','java',2); 1 row created. select * from staff; STAFF_ID 346 347 345 348 STAFF_NAME jeyam Prabha Jeya Ravi SUBJECT_NAME VC++ CG java java TIMES_HANDLED 4 2 3 2
f) Display the student, subject name where subject is not at all handle any staff in the staff table: select distinct subject from student where upper(subject) not in(select distinct upper(subject_name) from staff); SUBJECT .Net VB
Viva Questions:
1. What do you mean by subqueries? The subqueries are the form of SQL statement which appears inside other SQL statements. Then the statement containing subqueries is called parent statement. This is just like SQL executing another SQL statement. 2. Explain important uses of subqueries? i. ii. iii. iv. v. To insert records in the target table To create tables and insert records in this table To update records in the target table To create views To provide values for conditions in WHERE, HAVING clauses of SELECT, UPDATE and DELETE statements 3. What is the use of upper function? It changes all the characters in char into capitals.
Aim:
a) b) c) d) Create a sales_order table and client_master table with suitable fields. Find the total number of quantity ordered for a particular product. Display the rows of the table in the sales order date wise. Join the two tables and display the product number,product name where the orderno in the sales_order table and orderno in client_master are equal. e) Join the sales_order table to itself and display the order number,client number and salesman number where client has been services by more than one salesman.
Syntax:
Join:
SELECT column1,column2,..FROM <table1>,<table2> where <logical expression>;
a) Create a sales_order table and client_master table with suitable fields. Create sales_order Detail Table: create table sales_order(s_ord_no number(5),prod_no number(5), prod_name char(7),qty number(5),cli_no number(5),s_man_no number(6),s_date date); Table created. insert into sales_order values(122,090,'Rin',34,1222,123,'11-apr-04'); 1 row created. insert into sales_order values(232,78,'Colgate',35,343,343,'22-mar-98'); 1 row created. insert into sales_order values(343,23,'Oil',34,232,4354,'10-may-03'); 1 row created.
S_DATE
Create client_master Detail Table: create table client_master_det(cli_no number(5),c_name char(7),cli_order_no number(5),addr char(6)); Table created. insert into client_master_det values(23,'Mitha',122,'Nellai'); 1 row created. insert into client_master_det values(45,'Raj',1343,'Ten'); 1 row created. insert into client_master_det values(67,'Gowsic',769,'UK'); 1 row created. select * from client_master_det; CLI_NO 23 45 67 Raj Gowsic C_NAME Mitha CLI_ORDER_NO 122 1343 769 ADDR Nellai Ten UK
b) Find the total number of quantity ordered for a particular product. select sum(qty) from sales_order where prod_no=90; SUM(QTY) 79
c) Display the rows of the table in the sales order date wise.
Page51
d) Join the two ta t ables and display the produc number,product name wh ct t here the or rderno in the sales s_order table and orderno in client_m master are equal. select p prod_no,pr rod_name,cli_order_ _no,s_ord_n from sa no ales_order ss, r client_m master_det cc where ss.s_ord_ t e _no=cc.cli_ _order_no; PROD D_NO PROD_NA AME CLI_ORD DER_NO 122 S_OR RD_NO 122
90 Ri in
e) Join the sales_ t _order tab to itself and dis ble splay the o order num mber,clien nt numb and sa ber alesman n number wh here clien has bee services by more than nt en e one sa alesman. select d distinct a.s s_ord_no,a a.s_man_n from sal no les_order a a,sales_ord b where der a.cli_no o=b.cli_no and a.s_m man_no<>b b.s_man_n no; no rows selected s insert in sales_ nto _order valu ues(456,08 89,'Pons',4 45,1222,67 78,'11-feb-04');
1 row cre eated.
S_ORD_ _NO PROD D_NO PRO OD_NAME QTY CLI_ _NO S_MA AN_NO 122 232 343 434 456 90 Rin 78 Colga ate 23 Oil 90 Flour r 89 Pons 34 35 34 45 45 1222 1 343 232 454 1222 1
S_ _DATE
123 11-A APR-04 343 22-M MAR-98 4354 10-M MAY-03 23 09-J JAN-01 678 11-F FEB-04
distinct a.s s_ord_no,a a.s_man_n from sal no les_order a a,sales_ord b where der select d a.cli_no o=b.cli_no and a.s_m man_no<>b b.s_man_n no;
Viva Questions:
1. What is join? A join combines the data spread across tables. A join is performed by the WHERE clause which combines the specified rows of tables. 2. What is simple join? The simple join retrieves rows from two tables having a common column. It is further classified into i. ii. Equi- join Non equi join
3. Explain self join? Joining a table to itself called a self join. The join condition compares the each row of the table to itself and also other rows of the same table.
Aim:
a) Create table sales_order_details with the s_order_no as primary key and with the following fields: product_no, description, qty_ordered, qty_dispatched, product_rate, profit_percent, sell_price, supplier-name: b) Select each row and compute sell_price*.50 and sell_price*1.50 for each row selected. c) Select product_no,profit_percent, sell_price where profit_per is not between 10 and 20 both includive. d) select product_no, description, Profit_percent, sell_price where profit_percent is not between 20 and 30. e) select the suppier_name and product_no where supplier_name has r or h as second charcter.
Syntax:
Logical Operators:
Logical operators are used to combine two or more conditions.The value of a condition is either TRUE or FALSE.
Table Creation:
create table sales_order_det(s_order_no number(5) PRIMARY KEY,pno number(5),descriptio varchar(10),qty_ord number(4),qty_disp number(4),p_rate number(4),profit_per number(3),sell_price number(4)); Table created. insert into sales_order_det values(11,343,'Arial',10,4,45,67,12); 1 row created.
[[[[
a) Select each row and compute sell_price*.50 and sell_price*1.50 for each row selected. select sell_price*.50,sell_price*1.5 from sales_order_det; SELL_PRICE*.50 6 25 9 SELL_PRICE*1.5 18 75 27
select * from sales_order_det; S_ORDER _NO 11 12 13 14 15 PNO DESCRIPTIO QTY_ QTY_ ORD 10 34 56 45 35 DISP 4 4 12 56 65 P_RATE 45 56 45 67 32 PROFIT SELL_PRIC _PER 67 76 20 15 13 E 12 50 18 24 14
343 Arial 345 Rin 346 Oil 347 colgate 348 Pears
b) Select product_no,profit_percent, sell_price where profit_per is not between 10 and 20 both includive.
Page55
select pno,profit_per,sell_price from sales_order_det where profit_per <=10 or profit_per>=20; PNO 343 345 346 PROFIT_PER 67 76 20 SELL_PRICE 12 50 18
c) select product_no, description, Profit_percent, sell_price where profit_percent is not between 20 and 30. select pno,profit_per,descriptio,sell_price from sales_order_det where profit_per not between 20 and 30; PNO 343 345 347 348 PROFIT_PER 67 76 15 13 DESCRIPTIO Arial Rin colgate Pears SELL_PRICE 12 50 24 14
d) select the suppier_name and product_no where supplier_name has r or h as second charcter. update sales_order_det set descriptio='shear' where pno=345 1 row updated. select descriptio,pno from sales_order_det where descriptio like '_r%' or descriptio like '_h%'; DESCRIPTIO Arial shear PNO 343 345
Result: Page56
Viva Questions:
1. Explain the use of Logical expression? The logical expressions are created by joining field names or variables with values by logical operators. The logical expression creates a condition which may be true or false. These expressions are attached to SQL and if they are true then SQL is executed. 2. Explain the variety of Logical operators used? The varieties of logical operators used are > >= < <= = 3. Explain how the conditional retrieval of data is carried out? The data can be retrieved by writing SQL command using select * and attaching a logical expression. For example Select * from emp where condition The condition can be a logical expression. 4. What is meant by pattern matching? The use of the like predicate: For character data types: % matches any string _ (underscore) matches any single character
a) Create a table client_master with the following fields client_no, name, address1, address2, city, state, pincode, remarks, bal_due with suitable types.Create another table supplier_table from client_master. Select all the fields and rename client_no with supplier_no and name with supplier_name. b) Insert data into client_master. c) Insert data into supplier_master from client_master. d) Delete the selected row in the client_master.
Syntax:
Creating a table from an existing table:
CREATE TABLE<target_table>(column1,column2,)] as SELECT [*|column1,column2,.] FROM <source_table>;
a) Create a table client_master with the following fields client_no, name, address1, address2, city, state, pincode, remarks, bal_due with suitable
Page58
types.Create another table supplier_table from client_master. Select all the fields and rename client_no with supplier_no and name with supplier_name Create client_master Table: create table client_master (client_no number(5), name varchar(10), addr1 varchar(8),addr2 varchar(8),city varchar(7),state varchar(7),remarks varchar(7),bal_due number(5)); Table created. Create supplier_master Table: create table supplier_master(supplier_no, supplier_name,addr1, addr2,city,state,remarks) as select client_no, name,addr1, addr2, city, state, remarks from client_master; Table created.
b) Insert data into client_master. insert into client_master values(101,'Mathu','2nd st','2nd st','Tenkasi','TN','Good',1900); 1 row created. insert into client_master values(102,'Madan','3rd st','3rd st','Tenkasi','TN','Bad',1000); 1 row created. select * from client_master; CLIENT_NO NAME ADDR1 ADDR2 101 102 CITY STATE REMARKS BAL_DUE TN TN Good Bad 1900 1000
insert into supplier_master select client_no,name, addr1,addr2,city,state,remarks from client_master; 2 rows created. select * from supplier_master; SUPPLIER_NO SUPPLIER_NAME ADDR1 ADDR2 101 102 Mathu Madan CITY STATE REMARKS TN TN Good Bad
d) Delete the selected row in the client_master. Before Deletion: select * from client_master; CLIENT_NO NAME ADDR1 ADDR2 101 102 Madan 3rd st CITY STATE REMARKS TN TN Good Bad BAL_DUE 1900 1000
After Deletion: delete from client_master where name='Madan'; 1 row deleted. select * from client_master; CLIENT_NO NAME ADDR1 ADDR2 101 CITY STATE REMARKS TN Good BAL_DUE 1900
Viva Questions:
Page60
It is a non- procedure language which allows for accessing the data and manipulation of data. It allows for data query and security. These are four basic operations in SQL: i. Select the database ii. Update the database iii. Insert the database iv. Delete the database 2. What is the benefit of random access file in a database system? In this file the data is access directly by random access of any record. Every record has fixed number of bytes of memory. Therefore access to any record can be easily done. 3. What are the different types of file organizations? The data in the file has to be properly organize to ensure that the records are available for processing. There are four methods of organizing file. i. Sequential file ii. Direct file iii. Index sequential file iv. Random access file 4. What is the database administrator? The database administrator (DBA)
Aim:
Create a PL/SQL code to display the employee details for an employee.
Syntax:
PL/SQL Block Structure:
[DECLARE Variable declarations] BEGIN Executable statements [EXCEPTION Exception handlers] END;
Create Table:
create table e_detail(emp_name varchar2(10), emp_id varchar2(10),BP number(5), HRA number(5), DA number(5),PF number(5)); insert into e_detail values('&emp_name', &emp_id,&BP, &HRA, &DA, &PF); old 1: insert into e_detail values('&emp_name', &emp_id,&BP, &HRA, &DA, &PF) new 1: insert into e_detail values('Hari', 103,5000, 150, 200, 500) 1 row created. select * from e_detail; EMP_NAME Ravi sankar Hari
DA 75 400 200
Page62
select emp_name,BP,HRA,DA,PF into e_name,e_bp,e_hra,e_da,e_pf from e_detail where emp_id=x; gp:=e_bp+e_hra+e_da; np:=gp-e_pf; dbms_output.put_line(' Emp_Name: ' || e_name || ' Gross Pay :' || gp || ' Net Pay:' ||np ); end loop; end; Emp_id : ' || x || '
Page63
Viva Questions:
1. What do you mean by PL/SQL? The PL/SQL is an extension of SQL and it contains number of SQL statement which can be executed at a time. The PL/SQL allows to perform updating and retrieval values in the database. It also allows for decision making and conditional checking. It also allows for cyclic operation on database. 2. What do you mean by literals or constants? The literals are the value which remains constants. There are three types of literals: a) Numeric b) String c) Logical
It is a non executable statement written in the program by use of or /* */. This statement are inserted in the program for explaining the title and variables of the program or description or logics of the program 5. Explain the use of variables in the programs? The variables in the program are used for storing the values which are unknown and which may vary during the execution of program. 6. What are different types of variables used in the program? There are four types of variable a) Numeric variable b) Char variable c) Date variable d) Logical variable
Aim:
To write a PL/SQL code to calculate EB bill for the given units using if statement.
Syntax:
If Statement:
IF condition THEN S1 S2 . . . . END IF; S1,S2 Statements Condition Boolean Expression
Table Creation:
create table eb_bill(name varchar2(10), e_id number(5), pre_reading number(5), curr_reading number(5)); Table created. insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading); old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Sudan', 1001, 103, 250) 1 row created. old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Jana', 1002, 500, 750) 1 row created.
Page66
old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Kishore', 1003, 430, 690) 1 row created. old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Arun', 1004, 340, 400) 1 row created. old 1: insert into eb_bill values ('&name', &e_id, &pre_reading, &curr_reading) new 1: insert into eb_bill values ('Kumaran', 1005, 750, 1050) 1 row created. select * from eb_bill; NAME Sudan Jana Kishore Arun Kumaran E_ID 1001 1002 1003 1004 1005 PRE_READING 103 500 430 340 750 CURR_READING 250 750 690 400 1050
To calculate EB bill for the given units using if statement. set serveroutput on declare e_name varchar2(10); start_id number(5):=&start_id; end_id number(5):=&end_id; e_pre_reading number(5); e_curr_reading number(5); units number(5); amount number(5); x number; begin for x in start_id..end_id loop select name,pre_reading,curr_reading into e_name,e_pre_reading,e_curr_reading from eb_bill where e_id=x;
Page67
Units : '
OUTPUT:
old 3: start_id number(5):=&start_id; new 3: start_id number(5):=1001; old 4: end_id number(5):=&end_id; new 4: end_id number(5):=1005; Name Name Name Name Name : : : : : Sudan Jana Kishore Arun Kumaran ID ID ID ID ID : : : : : 1001 1002 1003 1004 1005 Units Units Units Units Units : : : : : 147 250 260 60 300 Amount Amount Amount Amount Amount : : : : : 441 1000 1040 1040 1200
Page68
The function used for display of value for variable is DBMS output function which calls upon put line function to display a value of variable. 2. Explain the control statement used in oracle? The control statements are used for decision making. The control statement checks the condition and accordingly executes the decision. 3. What are the different types of control statement used? If statement are used as control statements. These statements are a) If THEN statement b) If THEN ELSE statement c) If THEN ELSE if statement d) Compound if statement 4. Explain the used of looping statements? The looping statements have the capability to repeat sequence of statement. It performs number of cycles of operation over the given statement for modification of variables. The cycles are terminated when the condition is false. 5. What are the different types looping statements used? There are four types of looping statement used a) Simple loop b) While statement c) For loop statement d) Goto statement
Page69
Syntax:
Exception Handlers:
WHEN <exception name> [OR <exception name>] then <Sequence of statements>
Table Creation:
create table alumni(name varchar2(10), address varchar2(10), degree varchar2(10), batch number(10)); Table created. insert into alumni values('&name', '&address', '°ree', '&batch'); select * from alumni; NAME Babu Christy Malar Mitha Jency ADDRESS PCM Surandai Ppy Pv govai DEGREE BE MCA MCA Mphil BE BATCH 2002 2000 2005 2003 2002
To handle built-in exception like NO_DATA_FOUND, TOO_MANY_ROWS. set serveroutput on declare a_batch number(10); a_name varchar2(10);
Page70
select name, address, degree into a_name, ad, a_degree from alumni where batch= a_batch; dbms_output.put_line('Alumni_Name: ' || a_name || ' Batch : ' || a_batch ); exception when no_data_found then dbms_output.put_line('The ' || a_batch || ' Record Not Found. Please Insert.'); when too_many_rows then dbms_output.put_line('The ' || a_batch ||' Occurs Two Times. Please Select One Row Record.'); end; old 7: a_batch:=&batch; new 7: a_batch:=2000; Alumni_Name: Christy Batch : 2000
PL/SQL procedure successfully completed. old 7: a_batch:=&batch; new 7: a_batch:=2002; The 2002 Occurs Two Times. Please Select One Row Record. PL/SQL procedure successfully completed.
old 7: a_batch:=&batch; new 7: a_batch:=1999; The 1999 Record Not Found. Please Insert. PL/SQL procedure successfully completed.
The terminology for handling the errors in PL/SQL is exception. There are two types of exception. They are 1. Predefined exceptions 2. User defined exceptions An exception is raised when an error occurs. 2. What is a predefined exception? Predefined exceptions are raised automatically by the system during the run time when an error occurs. 3. List the predefined exception?
Predefined exception
No_data_found Too_many_rows Zero_divide Program error
Raised if
Select statement returns no rows (records). Select into statement returns more than one row. Try to divide a number by zero. PL/SQL has an internal problem. Conversion of a character string to a
Invalid_number
Page72
Syntax:
User-define Exception:
RAISE exception name;
if d=2 then if (a>0 and b>0 )then c:=a-b; dbms_output.put_line('Subtraction :'||c); else raise sub_excep; end if; end if;
if d=3 then if (a>0 and b>0) then c:=a*b; dbms_output.put_line('Multiplication :'||c); else raise mul_excep; end if; end if;
if d=4 then if(a>0 and b>=0) then c:=a/b; dbms_output.put_line('Divition :'||c); else raise div_excep; end if; end if;
Page74
Output:
1. 1. 2. 3. 4. Addition Subtraction Multiplication Division
old 2: d number:=&n; new 2: d number:= 1; old 3: a number:=&a; new 3: a number:=10; old 4: b number:=&b; new 4: b number:=20; Addition :30 PL/SQL procedure successfully completed.
Page75
old 2: d number:=&n; new 2: d number:= 3; old 3: a number:=&a; new 3: a number:=10; old 4: b number:=&b; new 4: b number:=23; Multiplication :230 PL/SQL procedure successfully completed.
3. 1. 2. 3. 4.
old 2: d number:=&n; new 2: d number:= 4; old 3: a number:=&a; new 3: a number:=12; old 4: b number:=&b; new 4: b number:=0; Divide by Zero Exception PL/SQL procedure successfully completed.
Page76
should
be
declared in the declarative part and raised explicitly by a raise statement. 2. Explain the pragma? A pragma is a compiler directive. This is processed at compile time and not at run time. 3. What is mean by Raise_application_error? This is more descriptive than named exception. The general syntax is Raise_application_error (error number, error message); Where Error_number is a number between -20,000 and -20,999 Error message is the text associated with this error. The error message must be fewer than 512 characters. 4. What is mean by exception handling in oracle? The exceptional errors occurring during the program can be handled by exception handling block in oracle program. If the error condition occurs in the program than the program can be terminated and the error is raised to the user indicating the exception to an error.
Page77
Syntax:
Procedure: Create or Replace procedure procedure_name [parameter list] is . . . Begin . . . Exception . . . End; Executing a Procedure: Exec <Procedure_name> (parameter);
Declarative Part
Execution Part
Execution Handler
a) To use procedure and get the result create or replace procedure find_address(phno number) as addr varchar2(50); begin select username||','||doorno||','||place||','||pincode into addr from phone where ph_no=phno; dbms_output.put_line(addr); exception
Page78
Syntax:
Function:
CREATE OR REPLACE FUNCTION [schema.] function name (argument IN datatype,..)
RETURN datatype {IS, AS} variable declaration; constant declaration; BEGIN PL/SQL subprogram body; EXCEPTION Exception PL/SQL block; END
Page79
create o replace function f or findaddres ss(phno in number) return var n rchar2 as addr varchar r2(50); begin select u username||','||door rno||','||p place||','||pincode into addr from phon ne where ph_no=p phno; return a addr; exceptio on when no_data_found then retu ' Addre Not Fo w d urn ess ound'; end; Functio created. on
2) declare addr varchar2(50); begin addr:=findaddress(243434); dbms_output.put_line(addr); end; OUTPUT: Address Not Found PL/SQL procedure successfully completed.
Page81
The procedure is a subprogram which can be called in the main program by the user. These the user made functions and operations which can be performed on the given database. The procedures are attached to the database and can be called by PL/SQL program to perform the calculations.
2. Explain what do you mean by function? The functions are similar to procedures and are subprograms called by PL/SQL program. The function retrieves the input values and the output value is returned to the PL/SQL program.
3. Explain modes of parameter? The parameter defined in the parameter list may be in one of the following three modes. They are a. In b. Out c. Inout
Page82
Syntax:
Creation of Triggers:
Create or replace Trigger <trigger_name> {before/after} {insert/update/delete} on <table_name> [for each statement/for each row] [when<condition];
To update the records while deleting the one record in another table. create table student(name varchar2(10),app_no number(10), join_year date,dob date,qualification varchar2(10)); Table created. insert into student values('&name',&app_no,'&join_year','&dob','&qualification'); select * from student; NAME Raju Viji APP_NO JOIN_YEAR DOB 02-MAR-87 12-APR-88 QUALIFICATION +2 10
create table student_detail(name varchar2(10),app_no number(10), join_year date,primary key(app_no)); Table created. desc student_detail; Name NAME APP_NO JOIN_YEAR
Page83
Trigger Creation:
create or replace trigger trig after update on student_detail for each row declare s_app_no number(10); s_joint_year date; pass_out number(5); begin s_app_no:=:new.app_no; delete from student where app_no=s_app_no; end; Update student_detail set name='Anu' where app_no=501; 1 row updated. select * from student_detail; NAME Kavi Vijay Reegan Anu viji select * from student; NAME Viji APP_NO JOIN_YEAR DOB 12-APR-88 QUALIFICATION 10 APP_NO JOIN_YEAR 555 02-JUN-08 556 01-JUN-09 557 05-JUN-98 501 02-MAR-87 502 26-MAY-06
502 26-MAY-06
Page84
Viva Questions:
1. What is trigger? A database trigger is a PL/SQL block that can be associated to a specific database table. The purpose of a database trigger is to perform a service when a specified operation occurs on a table. We create a database trigger by specifying a database table and by specifying that before or after a database operation (INSERT, UPDATE, or DELETE) on that table a procedure should be invoked. 2. Explain the trigger restrictions? A trigger cannot execute the COMMIT, ROLLBACK, or SAVEPOINT commands. It also cannot call procedures or functions that execute those tasks. The SELECT command can be used only with the INTO clause. 3. List the component of a trigger? A trigger has three parts: i. SQL command that activates the trigger The trigger can be activated by a SQL command or by user event. In a table, it can be triggered by INSERT, UPDATE, or DELETE commands. In a schema object, it can be triggered through the CREATE, ALTER or DROP commands, when the database is loaded or shut down, or through an error message. ii. Trigger restriction Represented by the WHEN clause, it specifies what condition must be true for the trigger to be triggered iii. Trigger action The PL/SQL block, or Java or C routine executed by the trigger. 4. How to explain the modifying a trigger? A trigger cannot be directly modified. To change it you must recreate it with the CREATE command. If a trigger had its privileges granted to other users, they remain valid as long as the trigger exists.
Page85
Syntax:
Open:
OPEN <cursor_name>;
Fetch:
FETCH cursor_name INTO column_name;
Close:
CLOSE cursor_name;
create table cur_sal(emp_no number(6) primary key,name varchar(7), desig varchar(9),depart varchar(10),bp number(6),da number(4),ma number(4),allow number(4),ded number(6,2)); Table created. insert into cur_sal values(122,'Sam','Lecturer','CE', 5000, 20, 120, 400, 300); 1 row created. insert into cur_sal values(34,'Aravind','Engineer','EEE', 20000, 1000,200, 700, 800); 1 row created. insert into cur_sal values(111,'Ravi','Designer','IT', 10000, 100,150, 300, 500); 1 row created.
Page86
cursor empsal is select emp_no,name,bp+da*bp/100+ma+allow-ded from cur_sal; begin dbms_output.put_line('EMP_NO'||'NAME'||'NET SALARY'); dbms_output.put_line('------------------------------------------'); open empsal; loop fetch empsal into e_no,e_name,net_sal; exit when empsal%notfound; dbms_output.put_line(rpad(e_no,10,' ')||rpad(e_name,7,' ')||net_sal); end loop; close empsal; end;
cursor c_sal(emp_id number) is select emp_no,bp,da,ma,allow,ded from cur_sal where emp_no=emp_id; begin open c_sal(no); fetch c_sal into no,basic,da,med,other,ded; if c_sal%notfound then dbms_output.put_line('No such employee found'); else update cur_sal set bp=8000,da=20,ma=222,allow=600,ded=250 where emp_no=no; end if; close c_sal; end; PL/SQL procedure successfully completed.
After Updating:
select * from cur_sal; EMP_NO 122 34 111 NAME Sam Ravi DESIG Lecturer DEPART CE BP 5000 8000 DA MA ALLOW DED 20 120 20 222 400 600 300 300 250 500
Page88
The cursors are the memory areas or work areas used for internal processing of data. These are capable are storing the data on which SQL operations can be performed. 2. What are the operations required for cursors? The following operations are required for the cursor a. Declare a cursor along with SQL statement b. Open a cursor c. Fetch data from cursor d. Closed the cursor 3. What is the use of %notfound? The %notfound evaluates to true if the data manipulation language statement does not return any row. Otherwise it evaluates to false. 4. What is the use of fetch command? The fetch command retrieves the current row and places the pointer to the next row. 5. What is the use of close command? After processing the last row in the active set, the cursor is closed using close command.
Page89
number(1),subject2
number(3),subject3
number(4),avg number(4));
-----------EEE Mech
-----------40 100
------------ -----------45 99 50 99
Page90
Page91
TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox8.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "', '" & TextBox6.Text & "', '" & TextBox7.Text & "')", con) x = cmd.ExecuteNonQuery() If (x = 1) Then MsgBox("1row created") Else MsgBox("no rows created") End If con.Close() Catch ex As Exception MsgBox(ex.Message) End Try End If End Sub Private Sub cmdclickme_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click TextBox6.Text = Val(TextBox3.Text) + Val(TextBox4.Text) + Val(TextBox5.Text) TextBox7.Text = Val(TextBox6.Text) / 3 End Sub Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click con.Open()
Page92
"',name='" & TextBox2.Text & "',department='" & TextBox8.Text & "',subject1='" & TextBox3.Text & "',subject2='" & TextBox4.Text & "', subject3='" & TextBox5.Text & "',total='" & TextBox6.Text & "', avg='" & TextBox7.Text & "' Where regno ='" & TextBox1.Text & "'", con) x = cmd.ExecuteNonQuery() If (x = 1) Then MsgBox("1row updated") Else MsgBox("no rows updated") End If con.Close() End Sub Private Sub cmddelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click con.Open() cmd = New OracleCommand("delete from stud where regno='" & TextBox1.Text & "'", con) x = cmd.ExecuteNonQuery() If (x = 1) Then MsgBox("1row deleted") Else MsgBox("no rows deleted") End If con.Close() End Sub Private Sub cmdview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click con.Open() cmd = New OracleCommand("select * from stud where regno='" & TextBox1.Text & "'", con) dr = cmd.ExecuteReader
Page93
Page94
output:
Database output:
SQL> select * from stud;
REGNO NAME DEPARTME SUBJECT1 SUBJECT2 SUBJECT3 TOTAL AVG
-----------EEE IT Mech
-----------50 99 99
---45 93 99
Result:The above program was successfully and the output was verified.
Page95
Contain fundamental classes with the core ADO.Net functionality. These include dataset and data relation which allow you to manipulate structured relation data. System.Data.Oracleclient: It contains classes to connect the Microsoft oracle server database. These classes like oracle command and connection provide all the same properties and method as the counter parts in system data.oracle namespace. Dataobject: Allow to store a local disconnected copy of data, they dont store a connection to a data store. Dataset: Dataset class and disconnect information drawn by direct connection and allows you to manipulate the datas. The data is a class no direct connection to a data source. Datatable: Add information in to a dataset in one table at a time data table object represent one of this table. Datarow: It represents a single row of information into the table. Datacolumn: Data column object not contain any actual data.
Aim:
To develop a visual basic application with suitable Lables&Textboxes for the columns of a table. Add command buttons to perform the following: display records,Previous,Next,First and Last. Use the ODBC driver to connect the application with the oracle.
Table creation:
SQL> create table biodata(name varchar2(8),sex varchar2(6),status varchar2(9),Qualification varchar2(9),percentage number(4),designation varchar2(12),Exprience varchar2(6),address varchar2(14),email_id varchar2(15),phoneno number(10)); Table created. SQL> insert into biodata values('Magesh','FEMALE','Married','Msc.MPhil','89','Lecturer','3years','Te nkasi','www.gmail.com','9790894132'); 1 row created. SQL> insert into biodata values('Christy','FEMALE','Married','MCA','92','Lecturer','3years','SURANDA I','chr@gmail.com','9894677898'); 1 row created. SQL> insert into biodata values('Jency','FEMALE','unMarried','BE','94','Lecturer','2years','TIRUNELV ELI','jeya@gmail.com','9987543784'); 1 row created.
Page97
values('Malar','FEMALE','unMarried','MCA','99','Lecturer','1years','CHENNAI
PHONENO
-----Married Married
-------- ----------- ------------ -----Msc.MPhil MCA 89 92 94 99 87 Lecturer Lecturer Lecturer Lecturer Lecturer 3years 3years 2years 1years 3years
Program:
Imports System.Data Imports System.Data.OracleClient Imports System.Data.OracleClient.OracleConnection Imports System.Data.OracleClient.OracleDataReader Public Class Form3 Inherits System.Windows.Forms.Form Private WithEvents mycurrencymanager As CurrencyManager Dim con As New OracleConnection Dim ds As New DataSet Dim cmd As New OracleCommand Dim dr As OracleDataReader
Page98
Page100
Output:
Result:The above program was successfully and the output was verified.
Page101
These object represent and sql statement or stored procedure are back you can used in future for to read, update or modify the data. To used your command you must be use a data adapter or use one of the following ExecuteNonQuery: It allows you to execute the command without retrieving any information. This is ideal for add , update, delete operation using SQL statement. ExecuteReader: Create or Reader connection which provides a fast forward connection only that allows you to retrieved rows from the data source. ExecuteScalerL: These also create a reader but only return a single value. The first column from the first row of the resulting rows. This method cannot be used if you are using an SQL statement or stored procedure that return a value instead of row set.
Page102
Extra Programs
Aim:
To Execute all the TCL Commands.
Table Creation:
create table emp(empnum varchar2(8),empname varchar2(8),desig varchar2(14),doj date,salary number(8)); Table created.
A.COMMIT:
Commit Commit complete. insert into emp values('1003','Vishal','operator','12-feb-03','4000') 1 row created.
Page104
B.COMMIT(savepoint)
commit; Commit complete. insert into emp values('1003','barath','operator','12-may-03','4000') 1 row created. select * from emp EMPNUM 1003 1001 EMPNAME barath mathu DESIG operator designeng manager DOJ 12-MAY-03 12-SEP-07 14-SEP-07 SALARY 4000 30000 35000
1002 raja savepoint id; Savepoint created. rollback to savepoint id Rollback complete. select * from emp; EMPNUM 1003 1001 1002 EMPNAME barath mathu raja
Page105
select order_seq.nextval from dual; NEXTVAL 14 select order_seq.nextval from dual; NEXTVAL 16
Dropping a sequence:
drop sequence order_seq Sequence dropped. select order_seq.currval from dual; select order_seq.currval from dual * ERROR at line 1: ORA-02289: sequence does not exist
Page107
3. View
create view emp_view as select * from emp View created. select * from emp_view; EMPNUM 1001 1002 8 EMPNAME mathu raja hari DESIG designeng manager accountant DOJ 12-SEP-07 14-SEP-07 02-MAY-09 SALARY 30000 35000 4000
create view sal_view as select e.empnum,e1.name,e1.addr from emp e,empl e1 where e.empnum=e1.empnum; View created. select * from sal_view EMPNUM 1001 1002 raja NAME mathu tenkasi madurai ADDR
EMP_VIEW1 select empnum,desig,salary from emp SAL_VIEW select e.empnum,e1.name,e1.addr from emp e,empl e1 where e.empnum=e1.empnum
Deleting a view:
drop view sal_view; View dropped. select * from sal_view; select * from sal_view * ERROR at line 1: ORA-00942: table or view does not exist
4. Synonyms
Page109
Aim:
To Modify the Table name using data object.
select * from e; EMPNUM 1001 1002 EMPNAME mathu raja DESIG desigeng manager DOJ 12-SEP-09 03-FEB-06 SALARY 34000 45000
Rename Synonyms:
Page110
Removing synonyms:
drop synonym m; Synonym dropped. select * from m; select * from m * ERROR at line 1: ORA-00942: table or view does not exist
Page111