Download - Oracle Si12
-
7/30/2019 Oracle Si12
1/141
CONFIDENTIALMC Limited
1
-
7/30/2019 Oracle Si12
2/141
CONFIDENTIALMC Limited
2
CONTENTS Introduction to DBMS
CODD rules
SQL * PLUS COMMANDS
SQL Sub Languages Operators Functions Constraints Group by, order by and having clauses
Data base objects Data dictionary in Oracle Creating users Joins Sub queries
PL/SQL
ANONYMOUS BLOCKS Cursors Triggers Procedures Functions Packages
-
7/30/2019 Oracle Si12
3/141
-
7/30/2019 Oracle Si12
4/141
CONFIDENTIALMC Limited
4
BASICS
Data
It is a collection of raw facts and figures
In order to use the data, the data needs to be preserved orstored in a definite location for every piece of data has anobjective and a purpose
Storage areas Pen drive Floppy CD ROM drive Manual storage
Data base
Place holder for storing the data to overcome the flaws with respectto data storage in the above mentioned areas
In order to store data in a data base, we need to define a datastructure Files
Tables
-
7/30/2019 Oracle Si12
5/141
CONFIDENTIALMC Limited
5
Disadvantages with file systems
Data redundancy
Data is in secured
Data base will be dependent on the programming
logic Hardware cost was intensifying
Concurrent access anamolies
-
7/30/2019 Oracle Si12
6/141
CONFIDENTIALMC Limited
6
Advantages with tables
In a table, rows need not be stored in a sequential manner
In a table, the data in the cells is atomic
In tables, data redundancy can be minimized or controlled
by imposing certain constraints like primary key
The usage of tables in a data base has been standardized
as relational data base management system
-
7/30/2019 Oracle Si12
7/141CONFIDENTIALMC Limited7
Codd rules
In order to qualify a data base as RDBMS it needs
to satisfy or comply with come standards referred
to as codd rules
No of codd rules : 12
-
7/30/2019 Oracle Si12
8/141CONFIDENTIALMC Limited8
12 Rules of Codd
1. Information rule
2. Guaranteed access rule
3. Systematic representation of null values
4. Active online catalog based on relational model
5. Data sub language rule
6. High level insert,update and delete
7. View updation rule
8. Physical data independence
9. Logical data independence
10. Data integrity rule11. Distribution rule
12. No sub version rule
-
7/30/2019 Oracle Si12
9/141CONFIDENTIALMC Limited9
Information rule
Each and every data item must be physically
represented or stored in the form of rows and
columns in a table
-
7/30/2019 Oracle Si12
10/141CONFIDENTIALMC Limited10
Guaranteed access rule
Each and every data item must be logically
represented as a combination of a column name,
table name and a primary key
Conclusions
In order to resolve the ambiguity in column names, we haveto use the table name in conjunction with a column name
Primary key has to be imposed on atleast 1 column in everytable for ensuring dependency between non key attributesand the primary key column so that the entire row in thattable can be uniquely identified
-
7/30/2019 Oracle Si12
11/141CONFIDENTIALMC Limited11
Systematic representation of null
values
A null value is a value which signifies a missing
or in appropriate information in a column of a
table
Null values are independent of data type
1 null value is not equal to another null value
Null value enhance the memory management in
oracle
It has to be a default value to be supplied by thesystem in a table in case a missing information
has been encountered
-
7/30/2019 Oracle Si12
12/141CONFIDENTIALMC Limited12
Active online catalog based on
relational model
Data dictionary has to be mandatorily
defined in any propretitory data base
package
Data dictionary is used for capturing theinformation with respect to data base
objects
Data dictionary accommodates meta data
-
7/30/2019 Oracle Si12
13/141CONFIDENTIALMC Limited13
Views of data dictionary
All_objects
User_objects
All_views
User_views
All_sequences
User_sequences
All_triggers
User_triggers All_synonyms
User_synonyms
-
7/30/2019 Oracle Si12
14/141CONFIDENTIALMC Limited14
High level insert, update and delete
Insert, update and delete are row wise operations
and not column wise
-
7/30/2019 Oracle Si12
15/141CONFIDENTIALMC Limited15
Data sub language rule
Any DBMS is supposed to implement or
comply at least one of the following sub
languages to store, use and manipulate
data in a data baseData definition languageData manipulation languageTransaction control language
DDL + DML + TCL = SQL
-
7/30/2019 Oracle Si12
16/141CONFIDENTIALMC Limited16
View updating rule
All the views that are theoretically
updatable must be practically
updated by the system
View is a virtual tableAny up dations made on a view must be
reflected on the base table and vice versa
-
7/30/2019 Oracle Si12
17/141CONFIDENTIALMC Limited 17
Physical data independence
Data base must be independent of
programming logic ie changes made
to a data base must not effect the
logic in a program
-
7/30/2019 Oracle Si12
18/141CONFIDENTIALMC Limited 18
Logical data independence
Application logic must be
independent of data base ie changes
made to a application logic must not
effect the data base
-
7/30/2019 Oracle Si12
19/141
-
7/30/2019 Oracle Si12
20/141CONFIDENTIALMC Limited 20
Data integrity rule
Primary key
Unique
Check Default
Foreign key
Not null
-
7/30/2019 Oracle Si12
21/141CONFIDENTIALMC Limited 21
SQL * PLUS COMMANDS(ORACLE Proprietary)
Ch / /
Changes the old table name to new table name
Cl scr Clears the screen contents
L
Display the previous SQL command
/
Executes the previous SQL command
RUN
Display and execute the previous SQL command
I WHERE EMPNO = 7369;
Adds a new line to the previous SQL command
Save
Creates a file for the previous SQL command Extension is .SQL
Path : D:\oracle\product\10.2.0\db_1\BIN Get
Display the contents of the file created
-
7/30/2019 Oracle Si12
22/141CONFIDENTIALMC Limited 22
-
7/30/2019 Oracle Si12
23/141
CONFIDENTIALMC Limited 23
DESCRIPTION
SQL is a non procedural query language devised by IBM in theyear 1970 for implementing their DB product by name DB2
Using SQL queries, we cannot create a procedure or a function They are not storable in a data dictionary
SQL is a universally acceptable standard for implementingany proprietary data base
Oracle SQL server SYBASE FOX PRO MY SQL
-
7/30/2019 Oracle Si12
24/141
CONFIDENTIALMC Limited 24
SUB LANGUAGES
DATA definition language(defines a data structure) Create Alter Truncate Drop
Data manipulation language(defines the way of maniuplating datain a structure)
Insert Update Delete Select
Transaction control language Grant Revoke
-
7/30/2019 Oracle Si12
25/141
CONFIDENTIALMC Limited 25
Create
Create table ( )
Eg
create table stud(sno number, sname char(10));
Maximum no of characters for a table name is 30
Alter
-
7/30/2019 Oracle Si12
26/141
CONFIDENTIALMC Limited 26
Alter Modify the data type of a column
Alter table modify ( );
alter table stud modify(sno varchar2(10));
You can increase the size of the column if the table is empty andcontaining data and you can decrease the size of the column if thetable is empty and the data which was previously inserted is incompliance with the decreased size of the column
Add a column
alter table stud add(city varchar2(10))
Delete a column
alter table stud drop column sname alter table stud drop (sno,age)
Drop multiple columns
Rename a column
alter table stud rename column city to state
Combinations of add and modify
alter table stud modify(state number) add (sno number)
-
7/30/2019 Oracle Si12
27/141
CONFIDENTIALMC Limited 27
Data types
Number([]) Number(precision ,scale)
Date
Timestamp
Char() Varchar2()
Blob
Bfile
Clob
Insert
-
7/30/2019 Oracle Si12
28/141
CONFIDENTIALMC Limited 28
Insert Inserting data into all the columns in a table Insert into stud values(10,1);
Inserting data into specific columns insert into stud(sno) values(3)
Define insertion order insert into emp1(ename,eno) values('kumar', 1)
Insert values into a table at run time insert into emp1 values(&eno,'&ename');
Insert values into a table at run time forspecific columns insert into stud(sno) values(&sno)
-
7/30/2019 Oracle Si12
29/141
CONFIDENTIALMC Limited 29
Contd
Create table at run time create table &table_name(&col &data_type, &col1 &data_type1)
Truncate
Used for deleting data from the table Truncate table
Eg truncate table emp1;
Drop Drop table ;
-
7/30/2019 Oracle Si12
30/141
CONFIDENTIALMC Limited 30
Update
Syntax
Update set = [where];
Eg update emp1 set ename = 'krishna' where ename = 'ravi
Deleting a value from a cell update emp1 set ename = null where eno = 7
Delete
-
7/30/2019 Oracle Si12
31/141
CONFIDENTIALMC Limited 31
Delete
Delete from [where ];
Eg
delete from emp1 where eno = 1
Comparison between truncate and delete Truncate can never be rolled back Truncate is a table level command Delete can be rolled back
Delete is a row level operation
-
7/30/2019 Oracle Si12
32/141
CONFIDENTIALMC Limited 32
Performance issue
Prior to deleting the table structure, the datawithin the table needs to be truncated for drop
only deletes the structure but the data within that
structure will still reside in the memory which will
go un referenced
-
7/30/2019 Oracle Si12
33/141
CONFIDENTIALMC Limited 33
-
7/30/2019 Oracle Si12
34/141
CONFIDENTIALMC Limited 34
DESCRIPTION
SYNTAX
Select from [where ]Eg
Select * from emp;
Select sal from emp;
Select 1 from emp;
-
7/30/2019 Oracle Si12
35/141
CONFIDENTIALMC Limited 35
Contd..
select empno, job from emp where sal = 1000 and
sal
-
7/30/2019 Oracle Si12
36/141
CONFIDENTIALMC Limited 36
Sql operators
BETWEEN and
select sal from emp where sal between 1000 and 2000
Not between and
IN
SELECT * FROM EMP WHERE JOB IN('CLERK', 'SALESMAN','MANAGER')
NOT IN
LIKE
SELECT * FROM EMP WHERE ENAME LIKE 'S% select * from emp where ename like '_M%
DISTINCT
select distinct(job) from emp Is null
select comm from emp where comm is null /
-
7/30/2019 Oracle Si12
37/141
CONFIDENTIALMC Limited 37
Concatenation operator
select ename || ' is a ' || job || ' whose salary is ' ||sal || ' from ' ||deptno from emp
Eg
SMITH is a CLERK whose salary is 800 from 20
-
7/30/2019 Oracle Si12
38/141
CONFIDENTIALMC Limited 38
-
7/30/2019 Oracle Si12
39/141
CONFIDENTIALMC Limited 39
DESCRIPTION
A function is a sub program which accepts somearguments and returns a value
Categories of functions
System defined functions
User defined functions
Calling a function
Select function_name() from dual/;
-
7/30/2019 Oracle Si12
40/141
CONFIDENTIALMC Limited 40
System defined functions
Numeric functions
String functions
Date and time functions
Conversion functions
Aggregate functions
NUMERIC FUNCTIONS
-
7/30/2019 Oracle Si12
41/141
CONFIDENTIALMC Limited 41
NUMERIC FUNCTIONS
Function Description Syntax
Ceil(arg1) Returns succeeding integer
value
select ceil(0.1) from dept
Floor(arg1) Returns the preceding integer
value
select floor(-0.1) from emp
Round(arg1) Rounds the decimal to the
nearest integer value(ie 0.5
scale is taken as a standard)
select round(-1.5) from emp
Trunc(arg1) This will truncate the decimal
places and returns the integral
part
select trunc(1.34) from emp
Power(arg1,arg2) Returns the power of a number select power(2,10) from emp
Sqrt(arg1) Returns the square root of a
number
Sin.,cos,tan(arg1)
String Functions
-
7/30/2019 Oracle Si12
42/141
CONFIDENTIALMC Limited 42
String Functions
Function Description Syntax
Lower(arg1) Display data in lower case select lower(ename) from emp
Upper(arg1) Display data in upper case select upper('kumar') from emp
Initcap(arg1) Display data in sentence case select initcap(ename) from emp
Substr(a1,a2,a3) A1 string, a2 startingposition of the string, a3 noof characters to be extracted
including start position
select substr(ename, 1, 3) from
emp
Concat(arg1,arg2) Combines 2 string objects select concat(45, 10) from emp
lpad
Lpad(arg1 arg2 arg3) Arg1 string object/col name SELECT LPAD(ENAME
-
7/30/2019 Oracle Si12
43/141
CONFIDENTIALMC Limited 43
Lpad(arg1, arg2, arg3) Arg1 string object/col name
Arg2 no of characters to be addedfrom the left hand side + the existing noof characters
Arg3 characters to be added
SELECT LPAD(ENAME,LENGTH(ENAME)+3, 'Mr.') from emp
Rpad(arg1, arg2, arg3) Arg1
string object/col nameArg2 no of characters to be addedfrom the right hand side + the
existing no of characters
Arg3 characters to be added
SELECT rPAD(ENAME,LENGTH(ENAME)+3, 'Mr.') from emp
Ltrim(arg1, arg2) Trims characters from the left hand
side
select ltrim('hyderabad', hyd') from
emp
/
Rtrim(arg1, arg2) Trims characters from the right hand
side
select rtrim('hyderabad', bad') from
emp
/
Translate(arg1, arg2, arg3) Arg1 string, arg2 characters tobe replaced, arg3 new characters
Replace (arg1, arg2, arg3)
-
7/30/2019 Oracle Si12
44/141
-
7/30/2019 Oracle Si12
45/141
CONFIDENTIALMC Limited 45
Replace and translate
Replace No of characters to be replaced can be greater than or equal
to the new characters
Translate
No of characters to be replaced = no of new characters
Date and time functions
-
7/30/2019 Oracle Si12
46/141
CONFIDENTIALMC Limited 46
Function Decription Syntax
Sysdate Returns the system date(dd-
mon-yy)
select sysdate+365 from emp
Add_months(arg1,arg2) Arg1 date, arg2 no ofmonths
select add_months(sysdate, -17)
from emp
Next_day(arg1, arg2) Arg1 date, arg2 day of theweek
select next_day(sysdate,
'saturday') from emp
Last_day(arg1) Arg1 date select last_day('01-feb-44') fromemp
Months_between(arg1, arg2)
Current_timestamp Display the current date and
time in milli seconds
-
7/30/2019 Oracle Si12
47/141
CONFIDENTIALMC Limited 47
Aggregate functions
Sum
Avg
Count
Min
Max
Any aggregate function accepts only 1 argument
All the aggregate functions are independent of the type ofthe data to be used as an argument in those functionsexcept for sum and average.
Sum and average operate only on numeric type
-
7/30/2019 Oracle Si12
48/141
CONFIDENTIALMC Limited 48
Conversion functions
To_char(arg1,arg2) select to_char(sysdate, 'dd$mon$yy') from emp
Extract select extract(year from sysdate) from emp;
To_date(arg1)
-
7/30/2019 Oracle Si12
49/141
CONFIDENTIALMC Limited 49
Group by clause
select deptno, max(sal) from emp group by deptno
Note
A column which has been defined in the group by clause need not appear inthe select clause. But a column on which a aggregate function has not beeninvoked must and should appear in the group by clause
A group by clause must and should be used in conjunction with anaggregate function in the select clause
Where clause cannot be used in conjunction with a group by clause and thereplacement would be the having clause
Eg
select max(sal) from emp group by deptno having max(sal) >3000
-
7/30/2019 Oracle Si12
50/141
CONFIDENTIALMC Limited 50
Order by
Display data in a sorted order Ascending Descending
Syntax
Select from order by asc/desc select * from emp order by comm
If a column has null values then
For ascending sort order, null values will be displayed at the bottom and fordescending sort order null values will be displayed at the top
-
7/30/2019 Oracle Si12
51/141
CONFIDENTIALMC Limited 51
Constraints
Not null
Unique
Primary key
Check
Default
Foreign key
-
7/30/2019 Oracle Si12
52/141
CONFIDENTIALMC Limited 52
Syntax for constraints imposing
Create table ( [constraint] constraint type);
Can impose constraints at 2 levels
Column level
Constraint definition and column definition apper at the same
place Table level
Constraint definition and column definition appear at differentplaces
-
7/30/2019 Oracle Si12
53/141
CONFIDENTIALMC Limited 53
Not null
Discards entry of null values and permitsduplicated entries
create table B(eno number not null)
-
7/30/2019 Oracle Si12
54/141
CONFIDENTIALMC Limited 54
Unique
Discards duplicated entries and permits nullvalues
create table B(eno number unique)
-
7/30/2019 Oracle Si12
55/141
CONFIDENTIALMC Limited 55
Primary key
Unique and not null
Eg
create table d(eno number primary key)
Primary key and unique keys by default impose a
unique index on a column in a table
Primary key is a unique row identifier
-
7/30/2019 Oracle Si12
56/141
CONFIDENTIALMC Limited 56
Check
create table e(sno number age numbercheck(age >= 18))
-
7/30/2019 Oracle Si12
57/141
CONFIDENTIALMC Limited 57
Default
Create table e(sno number, doj date defaultsysdate)
insert into c values(default);
-
7/30/2019 Oracle Si12
58/141
CONFIDENTIALMC Limited 58
Imposing constraints at the table level
create table c(eno number, ename varchar2(10),unique(eno))
create table d(eno number, ename varchar2(10),
primary key(eno))
Composite primary key
create table c(eno number, dno number, primarykey(eno,dno))
Composite unique key
create table d(eno number, dno number, unique(eno,dno))
create table e(eno number, ename varchar2(10),
check(eno > 1))
-
7/30/2019 Oracle Si12
59/141
CONFIDENTIALMC Limited 59
Not null Unique Primary key Default Check
Not null No Yes Yes No Yes
Unique Yes No No No Yes
Primary key Yes No No No Yes
Default Yes Yes Yes No Yes
Combination of constraints on a single column of a table
-
7/30/2019 Oracle Si12
60/141
-
7/30/2019 Oracle Si12
61/141
CONFIDENTIALMC Limited 61
Adding a constraint
alter table e1 add primary key(eno)
Disabling a constraint
ALTER TABLE ENABLE/DISABLE CONSTRAINTTYPE
Rename a constraint
alter table e1 rename constraint e1_nn to e2_nn;
Delete a constraint
alter table e1 drop constraint e2_nn;
-
7/30/2019 Oracle Si12
62/141
CONFIDENTIALMC Limited 62
Data base objects
Tables
Views
Synonyms
Sequences
Indexes
-
7/30/2019 Oracle Si12
63/141
CONFIDENTIALMC Limited 63
Activities
Create
Retreive
Update
Delete
-
7/30/2019 Oracle Si12
64/141
-
7/30/2019 Oracle Si12
65/141
CONFIDENTIALMC Limited 65
Views
View is a virtual table
View defintion is storable and not the data from the view
Advts
User can access only specific columns of a table Up dations made on a view or on a table have to be reflected on the other
data base object Syntax
Create[or replace] view as ;
Create a view without the base table
-
7/30/2019 Oracle Si12
66/141
CONFIDENTIALMC Limited 66
create force view v3 as select * from abc
Deleting a view
drop view v2 Create a view with a condition
Create view as [with check option]
View with aggregate functions
create view v1 as select max(sal) max_sal from emp3 group bydeptno
Alias name
-
7/30/2019 Oracle Si12
67/141
CONFIDENTIALMC Limited 67
Contd
View with string functions create view v2 as select lower(ename) ename_ll from emp
View with numeric functions
create view v3 as select sqrt(sal) sqr_sal from emp
Read only view
create view v4 as select empno from emp3 with read only Possibilities
Create a view on a view Create a table on a view
-
7/30/2019 Oracle Si12
68/141
CONFIDENTIALMC Limited 68
Synonyms
What is the difference between alias name and a synonym Alias name is temporary and used only for display purpose with respect to a
specific column in a table Synonym is a permanent name given to a table which is storable in the data
dictionary
When to use a synonym?
Synonym can be used if the name of a table is very long
Syntax
Create synonym for [] . create synonym d for emp3
Up dations made on a synonym are reflected on the base tableand vice versa
-
7/30/2019 Oracle Si12
69/141
CONFIDENTIALMC Limited 69
POSSIBILITIES
Create a synonym on a view
Create a view on a synonym
Create a synonym on a synonym
Create a table on a synonym Alias name and a synonym
select eno as "Employee Number" from s6
-
7/30/2019 Oracle Si12
70/141
CONFIDENTIALMC Limited 70
Sequences
It is a data base object which encourages automatic generation ofnumbers in a table
Syntax
Create sequence [start with ] [minvalue ] [maxvalue] [increment by ][cycle cache ];
Attributes of a sequence
Nextval Currval
Generate numbers from a sequence
Select .nextval/currval from /
By default, a sequence object creates a cache memory which
stores the values printed/generated by it
Contd
D fi i th t t d d l f
-
7/30/2019 Oracle Si12
71/141
CONFIDENTIALMC Limited 71
Defining the start and end values of a sequence
create sequence d2 start with 100 maxvalue 200
Defining the increment value for a sequence
Defining cycle cache for a sequence
create sequence d6 start with 100 maxvalue 110 cycle cache 100
Use a sequence in a table
insert into test1 values(d7.nextval, '&ename')
Setting increment value after sequence creation
alter sequence d10 increment by 2
Setting max value after sequence creation alter sequence d10 maxvalue 100
Setting cycle cache value
alter sequence d10 cycle cache 50
Drop a sequence
Drop sequence d10;
-
7/30/2019 Oracle Si12
72/141
CONFIDENTIALMC Limited 72
Sub queries
Display the salary of all the employees who are getting a salarygreater than smith
Eg
select sal from emp where sal > (select sal from emp where ename ='SMITH')
Update the salary of allen same as that of smith Display the details of all the employees who are getting a salary
greater than average salary
select * from emp where sal > (select avg(sal) from emp)
Joins
-
7/30/2019 Oracle Si12
73/141
CONFIDENTIALMC Limited 73
It is a concept through which data from multiple tables can beretrieved
Joins eliminate a cross product relationship between the tables
Joins
Equi join
Retreives data from multiple tables based on the equality condition provided both the tables arerelated
Eg
* select empno, ename, dname from emp,dept where emp.deptno = dept.deptno
* select empno, ename, dname,sal from emp,dept where emp.deptno = dept.deptno
* and sal > 1000
Non equi join Right outer join
select empno, ename, dname from emp,dept where emp.deptno(+) = dept.deptno
Left outer join select empno, ename, dname from emp,dept where emp.deptno = dept.deptno(+)
-
7/30/2019 Oracle Si12
74/141
CONFIDENTIALMC Limited 74
Users
Syntax Create user user name identified by password
Granting privilages
grant resource,connect to tanla;
Removing permissions revoke resource,connect from tanla;
-
7/30/2019 Oracle Si12
75/141
CONFIDENTIALMC Limited 75
-
7/30/2019 Oracle Si12
76/141
CONFIDENTIALMC Limited 76
-
7/30/2019 Oracle Si12
77/141
CONFIDENTIALMC Limited 77
DESCRIPTION
It is a procedural language used in conjunction with SQL toperform some activities in a data base which are not possible
using the normal SQL queries
The implementation of PL/SQL specification is very much
benificial when compared to SQL with respect to improving the
systems performance
It reduces the network traffic in a distributed environment
The data types of SQL and PL/SQL remain the same
PL/SQL specification ensures a logical and physical data
independence
-
7/30/2019 Oracle Si12
78/141
CONFIDENTIALMC Limited 78
Contents
Anonymous blocks
Cursors
Functions
Procedures Exception handling mechanisms
Triggers
Packages
-
7/30/2019 Oracle Si12
79/141
CONFIDENTIALMC Limited 79
ANONYMOUS BLOCK
This block can form a single unit for combining different sets ofSQL statements so that call to be made to a data base from an
external buffer or location can be only for 1 time accomplishing
different types of results
This block cannot be permanently stored in the data dictionary
and is used only at run time
Structure of anonymous block
Declare
-
7/30/2019 Oracle Si12
80/141
CONFIDENTIALMC Limited 80
Begin
;
;;
;
;
Exception when then
raise_application_error( );
End;
Output statement
Dbms_output.put_line();
The above statement can be operational if the server output isset to an on mode
Set server output on
-
7/30/2019 Oracle Si12
81/141
CONFIDENTIALMC Limited 81
Display a message
begin
dbms_output.put_line('Exam to be conducted in the last session');
end;
Use the ampersand (&) operator to give any input at run time
P i h d
-
7/30/2019 Oracle Si12
82/141
CONFIDENTIALMC Limited 82
Print the system date
begin
dbms_output.put_line(sysdate);end;
/
-
7/30/2019 Oracle Si12
83/141
COMMENTS
-
7/30/2019 Oracle Si12
84/141
CONFIDENTIALMC Limited 84
COMMENTS
declare
date1 date; /* THIS IS A LOCAL VARIABLE */
begin
date1 := &d1;
dbms_output.put_line('The date is ' ||date1);end;
/
ADD 2 NUMBERS
-
7/30/2019 Oracle Si12
85/141
CONFIDENTIALMC Limited 85
ADD 2 NUMBERS
DECLARE
N1 NUMBER;
N2 NUMBER;
N3 NUMBER;
BEGIN
N1 := &NUM1;N2 := &NUM2;
N3 := N1+N2;
DBMS_OUTPUT.PUT_LINE('THE SUM IS ' ||N3);
END;
/
DETERMINE THE BIGGEST AMONG 2
-
7/30/2019 Oracle Si12
86/141
CONFIDENTIALMC Limited 86
DETERMINE THE BIGGEST AMONG 2
NUMBERSDeclare
n1 number;
n2 number;
begin
n1 := &num1;
n2 := &num2;
if(n1 > n2) thendbms_output.put_line('The biggest number is '|| n1);
else
dbms_output.put_line('The biggest number is '|| n2);
end if;
end;
P
-
7/30/2019 Oracle Si12
87/141
CONFIDENTIALMC Limited 87
Program
Write an anonymous block which will perform theoperations on numbers dependending on the
users choice
If the choice is 1 then perform addition
If choice is 2 then perform subtraction
If choice is 3 then perform multiplication
Else perform division
declare
n1 number;
-
7/30/2019 Oracle Si12
88/141
CONFIDENTIALMC Limited 88
n2 number;
n3 number;
begin
n1 := &num1;
n2 := &num2;n3 := &num3;
if(n1 > n2 and n1 > n3) then
dbms_output.put_line('The biggest
number is ' ||n1);
elsif(n2 > n1 and n2 > n3) then
dbms_output.put_line('The biggest
number is ' ||n2);
else
dbms_output.put_line('The biggest
number is ' ||n3);end if;
end;
-
7/30/2019 Oracle Si12
89/141
CONFIDENTIALMC Limited 89
Accept empno at run time and display the name of that employee
declare
no number;ge number;
beginno := &num1;select age into ge from test where eno = no;dbms_output.put_line(ge);
end;
Accept the empno at run time and
d t th l f th t l b
-
7/30/2019 Oracle Si12
90/141
CONFIDENTIALMC Limited90
update the salary of that employee by
10%declare eno emp1.empno%type; sa emp1.sal%type;begin eno := &eno; select sal into sa from emp where
empno = eno; sa := sa+(10*sa/100); update emp1 set sal = sa whereempno = eno; dbms_output.put_line('Theupdated salary is '||sa);
end;/
Description Variable declaration with respect to a
-
7/30/2019 Oracle Si12
91/141
CONFIDENTIALMC Limited91
column in the table
Syntax
.% type;
%type It is an attribute which when used in conjunction with a variable name
signifies that the data type of the column in a table is in compliance withthe declared type of the variable in the anonymous block. Theadvantage of using this attribute is that if any changes are made to thetable structure, the same changes are not reflected in the applicationlogic encouraging physical data independence
Into This operator is used to copy the data from a specific column in a table into the local variable;
Syntax
* Select into from where =
A t t ti d di l th d l f th t l
-
7/30/2019 Oracle Si12
92/141
CONFIDENTIALMC Limited92
Accept empno at run time and display the name and salary of that employee
declareeno emp.empno%type;name emp.ename%type;sa emp.sal%type;
begineno := &employee_no;select ename,sal into name, sa from emp where empno = eno;dbms_output.put_line(name ||' '|| sa);
end;
Loop
-
7/30/2019 Oracle Si12
93/141
CONFIDENTIALMC Limited93
Loop
declare
x number;y number;
beginx := 1;loop
y := x*2;
insert into test10 values(x,y);x := x+1;exit when x >= 10;
end loop;dbms_output.put_line('Insertion sucessful....');
end;
For loop
-
7/30/2019 Oracle Si12
94/141
CONFIDENTIALMC Limited94
For loop
declarex number;y number;
beginx := 1;
for x in 1..10 loopy := x*2;insert into test10 values(x,y);
end loop;dbms_output.put_line('Insertion sucessful....');
end;
Requirement
-
7/30/2019 Oracle Si12
95/141
CONFIDENTIALMC Limited95
Requirement
Accept empno at run time and update the salary of an employee : If he belongs to deptno 10 then update his salary by Rs 100 If he belongs to deptno 20 then update his salary by Rs 200 If he belongs to deptno 30 then update his salary by Rs 300
declare
-
7/30/2019 Oracle Si12
96/141
CONFIDENTIALMC Limited96
declareeno emp90.empno%type;dno emp90.deptno%type;nsal emp90.sal%type;
begineno := &employee_no;select deptno,sal into dno,nsal where empno = eno;if(dno = 10) then
nsal := nsal+100;elsif(dno = 20) then
nsal := nsal+200;else
nsal := nsal+300;end if;update emp90 set sal = nsal where empno = eno;
dbms_output.put_line('Records Updated...');end;
Variables belonging to the same type cannot be declared on a single line
-
7/30/2019 Oracle Si12
97/141
CONFIDENTIALMC Limited97
Variables belonging to the same type cannot be declared on a single line
declaren1, n2 number;
begin
n1 := 10;n2 := 20;dbms_output.put_line(n1+n2);
end;/
If a value is not assigned to any local variable then by default, a null
-
7/30/2019 Oracle Si12
98/141
CONFIDENTIALMC Limited98
g y y
value will be supplied by the system
declaren number;
begin
dbms_output.put_line('The value is ' ||n);end;/
-
7/30/2019 Oracle Si12
99/141
CONFIDENTIALMC Limited99
-
7/30/2019 Oracle Si12
100/141
CONFIDENTIALMC Limited100
REQUIREMENT
-
7/30/2019 Oracle Si12
101/141
CONFIDENTIALMC Limited101
REQUIREMENT
Display the names of all the employees from emptable
declare
name emp.ename%type ;
begin
select ename into name from emp;
end;
/
Description
-
7/30/2019 Oracle Si12
102/141
CONFIDENTIALMC Limited102
Description
The above code returns an error because intooperator can fetch on a maximum basis only 1
row at a time for a particular input given at run
time
To fetch multiple rows from a table, we need toimplement a specification referred to as cursors
Contd
-
7/30/2019 Oracle Si12
103/141
CONFIDENTIALMC Limited103
Contd
Cursor is a private SQL area used for fetching thedata from a table row wise ie for every SQL
statement issued by the user, by default a cursor
will be created for that statement
How the system creates a cursor
-
7/30/2019 Oracle Si12
104/141
CONFIDENTIALMC Limited104
for every SQL statement?
Declare the cursor Cursor is
Open the cursor
Open ;
Fetch data from the cursor into a local variable Fetch into ;
Close the cursor
Close ;
Display the names from the emp
-
7/30/2019 Oracle Si12
105/141
CONFIDENTIALMC Limited105
table using cursors
declare cursor c1 is select ename from emp;name emp.ename%type;
beginopen c1;loop
fetch c1 into name;exit when c1%notfound;dbms_output.put_line(name);
end loop;close c1;
end;
/
Display the first 3 rows from emp
-
7/30/2019 Oracle Si12
106/141
CONFIDENTIALMC Limited106
table
declarecursor c1 is select ename from emp;name emp.ename%type;
beginopen c1;loop
fetch c1 into name;exit when c1%rowcount >3;dbms_output.put_line(name);
end loop;close c1;
end;
Display the table itself using
-
7/30/2019 Oracle Si12
107/141
CONFIDENTIALMC Limited107
cursors
declarecursor c2 is select * from dept;rec dept%rowtype;
beginopen c2;loop
fetch c2 into rec;exit when c2%notfound;dbms_output.put_line(rec.deptno || ' ' ||rec.dname || ' '||rec.loc);
end loop;close c2;
end;/
Attributes of cursors
-
7/30/2019 Oracle Si12
108/141
CONFIDENTIALMC Limited108
Attributes of cursors
%rowtype This attribute can be used with cursors if you want to declare a variable
which holds data from multiple columns in the same table Syntax
%rowtype;
%rowcount
This attribute can be used with cursors to limit the display of data fromtables with respect to specific number of rows
%notfound
This attribute when used with cursors determines the availability of datawithin a cursor
-
7/30/2019 Oracle Si12
109/141
CONFIDENTIALMC Limited109
-
7/30/2019 Oracle Si12
110/141
CONFIDENTIALMC Limited110
USER DEFINED FUNCTIONS
-
7/30/2019 Oracle Si12
111/141
CONFIDENTIALMC Limited111
USER DEFINED FUNCTIONS
SYNTAX
Create or replace () return is ;
Begin ;return ();
End []
Function to add 2 numbers
-
7/30/2019 Oracle Si12
112/141
CONFIDENTIALMC Limited112
Function to add 2 numbers
function add3(n1 number, n2 number)return number is s number;begin
s := n1+n2;return s;
end;
FUNCTION WITH DEFAULT
PARAMETERS
-
7/30/2019 Oracle Si12
113/141
CONFIDENTIALMC Limited113
PARAMETERS
Create or replace function add4(n1 number default 10, n2 number default 20)return number is s number;begin
s := n1+n2;return s;
end;
Function that accepts empno as an input and return the name
of the employee
-
7/30/2019 Oracle Si12
114/141
CONFIDENTIALMC Limited114
of the employee
create or replace function name_disp(eno emp.empno%type)return emp.ename%type is name emp.ename%type;begin
select ename into name from emp where empno = eno;
return name;end;
-
7/30/2019 Oracle Si12
115/141
CONFIDENTIALMC Limited115
-
7/30/2019 Oracle Si12
116/141
-
7/30/2019 Oracle Si12
117/141
CONFIDENTIALMC Limited117
Syntax
Create or replace procedure () isBegin
statements;
End;
Procedure to add 2 numbers
-
7/30/2019 Oracle Si12
118/141
CONFIDENTIALMC Limited118
Procedure to add 2 numbers
create or replace procedure add5(n1 number, n2 number, n3 out number) isbegin
n3 := n1+n2;dbms_output.put_line('The sum is ' ||n3);
end;
Description
-
7/30/2019 Oracle Si12
119/141
CONFIDENTIALMC Limited119
esc pt o
In case a parameter has been defined as an out parameter in a procedure
then that parameter has to be declared as a session variable in the SQL
prompt
SQL > VAR
Calling a procedure
SQL > exec (, , , :) In a procedure call, the out parameter has to be defined as a bind variable
Bindvariable
-
7/30/2019 Oracle Si12
120/141
CONFIDENTIALMC Limited120
Exception types
-
7/30/2019 Oracle Si12
121/141
CONFIDENTIALMC Limited121
p yp
Zero divide No_data_found
Too_many_rows
Zero divide
-
7/30/2019 Oracle Si12
122/141
CONFIDENTIALMC Limited122
_
declaren1 number;n2 number := 0;
beginn1 := &num1;dbms_output.put_line(n1/n2);
exception when zero_divide thenraise_application_error(-20001, 'sorry cannot perform division');
end;
No data found
-
7/30/2019 Oracle Si12
123/141
CONFIDENTIALMC Limited123
declareeno emp.empno%type;name emp.ename%type;
begineno := &employee_no;select ename into name from emp where empno = eno;dbms_output.put_line(name);
exception when no_data_found thenraise_application_error(-20001, 'data not available in the emp table');
end;
Too many rows
-
7/30/2019 Oracle Si12
124/141
CONFIDENTIALMC Limited124
_ y_
declarename emp.ename%type;
beginselect ename into name from emp;dbms_output.put_line(name);
exception when too_many_rows thenraise_application_error(-20001, 'see 1 row at a time');
end;/
-
7/30/2019 Oracle Si12
125/141
CONFIDENTIALMC Limited125
DESCRIPTION
-
7/30/2019 Oracle Si12
126/141
CONFIDENTIALMC Limited126
Package is a named group of functions,procedures and cursors
Advantages of using a package
Resolve ambiguity in the names of functions and procedures
Reusability
How to create a package ?
-
7/30/2019 Oracle Si12
127/141
CONFIDENTIALMC Limited127
p g
Package specification Package body
Note
Package specification name and package body name must
be the same
Syntax for creating a package
specification
-
7/30/2019 Oracle Si12
128/141
CONFIDENTIALMC Limited128
specification
Create package is;;;End;
Syntax for creating a package
body
-
7/30/2019 Oracle Si12
129/141
CONFIDENTIALMC Limited129
body
Create package body isProcedure isBegin
;
End;Function return is ;Begin
;return var;
End;
End;
Requirement
-
7/30/2019 Oracle Si12
130/141
CONFIDENTIALMC Limited130
Create a package which consists of a functionand a procedure
The function has to add 2 numbers and return the
sum
The procedure has to subtract 2 numbers
Package specification
-
7/30/2019 Oracle Si12
131/141
CONFIDENTIALMC Limited131
create package m1 isfunction sum1(n1 number, n2 number) return number;procedure sub1(n1 number, n2 number, n3 out number);end;
-
7/30/2019 Oracle Si12
132/141
Call a procedure within a package
-
7/30/2019 Oracle Si12
133/141
CONFIDENTIALMC Limited133
Exec . ()
Call a function within a package
Select . () from
-
7/30/2019 Oracle Si12
134/141
CONFIDENTIALMC Limited134
-
7/30/2019 Oracle Si12
135/141
Syntax for creating a DML trigger
-
7/30/2019 Oracle Si12
136/141
CONFIDENTIALMC Limited136
Create or replace trigger of on before/after insert/update/delete for each row;Begin
raise_application_error( );End;
Restrict the users from deleting a
row from emp table
-
7/30/2019 Oracle Si12
137/141
CONFIDENTIALMC Limited137
row from emp table
create or replace trigger t1 before delete on emp for each rowbegin
raise_application_error(-20001, 'sorry cannot delete a row');
end;
Restrict the users from inserting
data into a table
-
7/30/2019 Oracle Si12
138/141
CONFIDENTIALMC Limited138
data into a table
create or replace trigger t2 before insert on result3 for each rowbegin
raise_application_error(-20001, 'do not try to insert a row');
end;
Restrict the users from creating
the table
-
7/30/2019 Oracle Si12
139/141
CONFIDENTIALMC Limited139
the table
-
7/30/2019 Oracle Si12
140/141
CONFIDENTIALMC Limited140
-
7/30/2019 Oracle Si12
141/141