oracle11g slides
TRANSCRIPT
-
5/20/2018 Oracle11g Slides
1/319
1
Oracle SQL, PL/SQL
By
Bhavna Philipose
Training Consultant : MCP
104.01.05
-
5/20/2018 Oracle11g Slides
2/319
2
Module Getting Started with Oracle
Overview
Introduction to Databases
Introducing SQL
Main Components of Oracle
Starting SQL * Plus
Exiting SQL * Plus
-
5/20/2018 Oracle11g Slides
3/319
3
Introduction to Databases
Computerized record-keeping system.
EMPNO ENAME JOB MANAGER HIREDATE SALARY COMMISSION
DEPTNO
7369 SMITH CLERK 790217-DEC-
1980800 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7698 BLAKE MANAGER 783901-MAY-
19812850 30
7782 CLARK MANAGER 7839 09-JUN-1981 2450 0 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 20
EMPLOYEE
-
5/20/2018 Oracle11g Slides
4/319
4
Introducing SQL
-
5/20/2018 Oracle11g Slides
5/319
5
Main Components of Oracle
SQL * Plus
-
5/20/2018 Oracle11g Slides
6/319
6
Main Components of Oracle
iSQL * Plus
-
5/20/2018 Oracle11g Slides
7/3197
Main Components of Oracle
PL/SQL
-
5/20/2018 Oracle11g Slides
8/3198
Starting SQL*Plus
-
5/20/2018 Oracle11g Slides
9/3199
Starting SQL * Plus from Command Prompt
-
5/20/2018 Oracle11g Slides
10/31910
Exiting SQL*Plus
SQL> EXIT
-
5/20/2018 Oracle11g Slides
11/31911
SQL Developer
Oracle SQL Developer is a free graphical tool for database
development and querying the Database.
Using SQL Developer, you can browse database objects,
run SQL statements and SQL scripts, and edit and debug
PL/SQL statements.
SQL Developer can connect to any Oracle Database
version 9.2.0.1 and later and runs on Windows, Linux and
Mac OSX.
It enhances productivity and simplifies your databasedevelopment tasks.
-
5/20/2018 Oracle11g Slides
12/31912
Connection To a Oracle Database
-
5/20/2018 Oracle11g Slides
13/31913
Browsing Objects
-
5/20/2018 Oracle11g Slides
14/31914
PL/SQLCreating Functions
-
5/20/2018 Oracle11g Slides
15/31915
Module : Editing SQL Commands
Overview
Entering SQL commands
Editing SQL commands
Managing SQL files
-
5/20/2018 Oracle11g Slides
16/31916
Entering and Editing SQL Commands
Terminating SQL statement:
a semicolon at the end of a line, a semicolon on a line by itself,
a slash ("/") on a line by itself.
Viewing contents of SQL buffer:
SQL> prompt:
SQL> list;
Viewing specific line:
SQL> 2
-
5/20/2018 Oracle11g Slides
17/31917
Entering and Editing SQL Commands
SQL> FROM meployee
SQL> change/mep/emp
SQL> c/mep/emp
SQL> c/emp
SQL>delSQL> input FROM employee
SQL> append , emp_name
SQL> save training.sql
-
5/20/2018 Oracle11g Slides
18/319
18
Managing SQL files
SQL> get training.sql
SQL> @ training.sql
SQL> run training.sql
SQL> clear buffer
SQL> spool C:\training
SQL> spool off
SQL> spool out
-
5/20/2018 Oracle11g Slides
19/319
19
Module : Data Retrieval & Ordering Output
Overview
Simple Data Retrieval
Describing Table Structure
Conditional Retrieval using Arithmetic, Relational, Logical
and Special Operators
The ORDER BY clause.
Aggregate functions
The GROUP BY and HAVING clause
-
5/20/2018 Oracle11g Slides
20/319
20
Data Retrieval
SQL> SELECT * FROM tab;
SQL> DESC deptName Null? Type
----------------------------------------------------------------------- -------- ----------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
BUDGET NUMBER
-
5/20/2018 Oracle11g Slides
21/319
21
Data Retrieval
SQL>SELECT * FROM employee;
SQL> SELECT emp_code, emp_name FROMemployee;
SQL> SELECT distinct dept_code FROMemployee;
-
5/20/2018 Oracle11g Slides
22/319
22
Conditional Retrieval
SQL> SELECT * FROM employee WHEREsalary > 3500;
SQL> SELECT emp_code, emp_name FROM employee WHERE
dept_code = 'MKTG';
-
5/20/2018 Oracle11g Slides
23/319
23
RelationalOperators
= equal to
!= not equal to
^= not equal to
not equal to
> greater than
< less than
>= greater than or equal to SELECT * FROM employee WHERE salary >3000;
SQL> SELECT emp_name FROM employee WHERE dept_code !='MKTG';
SQL> SELECT * FROM employee WHERE emp_name = 'Vijay
Gupta';
-
5/20/2018 Oracle11g Slides
24/319
24
Logical Operators
The ANDOperator
SQL> SELECT * FROM employeeWHERE dept_code = 'MKTG' ANDsex = 'F';
SQL> SELECT * FROM employee
WHERE salary >= 3000 ANDsalary SELECT * FROM employee
WHERE dept_code = 'MKTG' ORdept_code = 'FIN';
The NOTOperator
SQL> SELECT * FROM employee WHERE NOTdept_code =
'MKTG';
-
5/20/2018 Oracle11g Slides
25/319
25
Special Operators
The BETWEENoperator
SQL> SELECT * FROM employee WHERE salary BETWEEN 3000
and 4000;
SQL> SELECT * FROM employee WHERE date_join BETWEEN
'01-JAN-80' and '31-DEC-89'
The INoperator
SQL> SELECT * FROM employee WHERE dept_code IN ('MKTG',
'FIN');
SQL> SELECT * FROM employee
WHERE dept_code NOT IN('MKTG', 'FIN');
-
5/20/2018 Oracle11g Slides
26/319
26
Special Operators
The LIKEoperator
SQL> SELECT * FROM employee WHERE emp_name LIKE
'P%';
SQL> SELECT * FROM employee WHERE emp_name LIKE
'%Gupta';
SQL> SELECT * FROM employee WHERE emp_name LIKE
'%Gupta%';
SQL> SELECT * FROM employee WHERE grade LIKE '_1';
TheIS NULL operator
SQL> SELECT * FROM employee WHERE reports_to IS NULL;
SQL> SELECT * FROM employee WHERE reports_to IS NOT
NULL;
-
5/20/2018 Oracle11g Slides
27/319
27
Arithmetic Operators
+ addition
- subtraction* multiplication
/ division
SQL> SELECT * FROM product
WHERE direct_sales +indirect_sales > target;
SQL> SELECT prod_code, prod_name, direct_sales +indirect_sales
FROM product;
SQL> SELECT prod_code,
direct_sales +indirect_sales "Total sales"
FROM product;
-
5/20/2018 Oracle11g Slides
28/319
28
Ordering the SELECT Query Output
Ordering on single column
SQL> SELECT * FROM employee ORDER BYemp_code;
SQL> SELECT * FROM employee WHERE sex = 'M' ORDER BY
emp_name;
SQL> SELECT * FROM employee ORDER BYage DESC;
Ordering on multiple columns
SQL>SELECT * FROM employee ORDER BYdept_code,emp_name;
SQL>SELECT * FROM employee ORDER BYdept_code, age
DESC;
-
5/20/2018 Oracle11g Slides
29/319
29
Substitution Variables
... salary = ?
department_id = ?
... last_name = ? ...
I wantto query
different
values.
-
5/20/2018 Oracle11g Slides
30/319
30
Substitution Variables
substitution
variables
SubstitutionVariables
Use substitution variables to supplement the
following:
WHERE conditions
ORDER BY clauses
Column expressions
Table names
Entire SELECT statements
Substitutio
n Variables
Use substitution variables to:
Temporarily store values with single-ampersand (&) and double-ampersand
(&&) substitution
Using the Single-Ampersand Substitution
-
5/20/2018 Oracle11g Slides
31/319
31
SELECT product_id, warehouse_id, quantity_on_hand
FROM inventories
WHERE product_id = product_id ;
Using the Single Ampersand SubstitutionVariable
Use a variable prefixed with an ampersand (&) to prompt the user
for a value:
- r u u
-
5/20/2018 Oracle11g Slides
32/319
32
r u uVariable
Character and Date Values with
-
5/20/2018 Oracle11g Slides
33/319
33
SELECT last_name, department_id, salary*12
FROM employees
WHERE job_id = '&job_title' ;
Character and Date Values withSubstitution Variables
Use single quotation marks for date and character values:
-
5/20/2018 Oracle11g Slides
34/319
34
Specifying Column Names, Expressions, and Text
SELECT column_name
FROM inventories
WHERE Condition
ORDER BY Order_column ;
Using the Double-Ampersand
-
5/20/2018 Oracle11g Slides
35/319
35
SELECT employee_id, last_name, job_id, &&column_name
FROM employees
ORDER BY &column_name ;
Using the Double-AmpersandSubstitution Variable
Use double ampersand (&&) if you want to reuse the variable valuewithout prompting the user each time:
U i th C d
-
5/20/2018 Oracle11g Slides
36/319
36
Using the DEFINECommand
Use the UNDEFINE command to remove a variable.
DEFINE order_num = 2458
SELECT order_id, order_date, order_mode, order_total
FROM orders
WHERE order_id = order_num ;
UNDEFINE order_num
Use the DEFINE command to create and assign a value to a
variable.
-
5/20/2018 Oracle11g Slides
37/319
37
SET VERIFY ON
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id = &employee_num;
Using the VERIFYCommand
Use the VERIFY command to toggle the display of the substitution
variable, both before and after SQL Developer replaces
substitution variables with values:
A t F ti
-
5/20/2018 Oracle11g Slides
38/319
38
Aggregate Functions
SQL> SELECT COUNT(*) FROM employee;
SQL> SELECT SUM(salary) FROM employee;
SQL> SELECT AVG(age) FROM employee;
SQL> SELECT MAX(salary) FROM employee;
SQL> SELECT MIN(salary) FROM employee;
SQL> SELECT * FROM employee WHERE salary = (SELECT MIN
(salary) FROM employee);
Th GROUP BY l
-
5/20/2018 Oracle11g Slides
39/319
39
The GROUP BY clause
SQL> SELECT dept_code, sum (salary)
FROM employeeGROUP BYdept_code;
Th HAVING Cl
-
5/20/2018 Oracle11g Slides
40/319
40
The HAVING Clause
SQL> SELECT dept_code, sum (salary) FROM employee
GROUP BY dept_codeHAVINGsum (salary) > 10000;
SQL> SELECT dept_code, sum (salary)
FROM employeeWHERE age > 30
GROUP BY dept_code
HAVINGsum (salary) > 10000
ORDER BY sum (salary) desc;
SQL f A ti
-
5/20/2018 Oracle11g Slides
41/319
41
SQL for Aggregation
ROLLUP calculates aggregations such as SUM, COUNT,
MAX, MIN, and AVG at increasing levels of aggregation,from the most detailed up to a grand total.
To find the product-wise and productgroup-wise total across
regions: select prodgr_name , prod_name ,region,sum (target)
from prodgrup, product
where prodgrup.prodgr_code = product.prodgr_code
group by ROLLUP( prodgr_name, prod_name,region)
SQL f A ti
-
5/20/2018 Oracle11g Slides
42/319
42
SQL for Aggregation
GROUPING Function
Two challenges arise with the use of ROLLUP and CUBE.
First, how can you programmatically determine which result set rows
are subtotals, and how do you find the exact level of aggregation for a
given subtotal
Second, what happens if query results contain both stored NULLvalues and "NULL" values created by a ROLLUP or CUBE? How
can you differentiate between the two
GROUPING handles these problems.
If the NULL indicates the row is a subtotal, GROUPING returns 1. Any othertype of value, including a stored NULL, returns 0.
SQL f A ti
-
5/20/2018 Oracle11g Slides
43/319
43
SQL for Aggregation
For eg.
select prodgr_name, prod_name, region, sum (target),grouping(prod_name) gr_prd_name, grouping(region) gr_region
from prodgrup, product
where prodgrup.prodgr_code = product.prodgr_code
group by ROLLUP( prodgr_name, prod_name,region);
SQL fo Agg egation
-
5/20/2018 Oracle11g Slides
44/319
44
SQL for Aggregation
Thus Grouping function can be used as follows:
select case
when GROUPING(prodgr_name)= 1 and grouping(prod_name) = 1 andGROUPING(region) = 1
then 'GRAND TOTAL'
else prodgr_name end "group",
case when GROUPING(prodgr_name)= 0 and grouping(prod_name) = 1
then 'GROUP TOTAL'
else prod_name end prod_name,case when GROUPING(prodgr_name)= 0 and grouping(prod_name) = 0 andGROUPING(region) = 1
then 'PRODUCT TOTAL'
else region end region,
sum (target)
from prodgrup, productwhere prodgrup.prodgr_code = product.prodgr_code
group by rollup(prodgr_name,prod_name,region);
This replaces all the null values caused by rollup/cube with some meaningfulvalues.
SQL for Aggregation
-
5/20/2018 Oracle11g Slides
45/319
45
SQL for Aggregation
CUBE is an extension similar to ROLLUP, enabling a single
statement to calculate all possible combinations ofaggregations
select prodgr_name, prod_name, region, sum (target),
grouping(prod_name) gr_prd_name, grouping(region) gr_region
from prodgrup, productwhere prodgrup.prodgr_code = product.prodgr_code
group by cube( prodgr_name, prod_name,region);
The CUBE, ROLLUP extension lets you specify just thegroupings needed in the GROUP BY clause. This allows
efficient analysis across multiple dimensions.
SQL for Aggregation
-
5/20/2018 Oracle11g Slides
46/319
46
SQL for Aggregation
Computing a CUBE creates a heavy processing load, so
replacing cubes with grouping sets can significantly increaseperformance.
CUBE(a, b, c) This statement is equivalent to:
GROUPING SETS ((a, b, c), (a, b), (a, c), (b, c), (a), (b), (c), ())
ROLLUP(a, b, c) This statement is equivalent to:
GROUPING SETS ((a, b, c), (a, b), ())
Module Built In Functions
-
5/20/2018 Oracle11g Slides
47/319
47
Module Built-In Functions
Overview
Numeric functions
Character functions
Date functions
Special formats with Date data types
Conversion functions
Functions on Numeric data types
-
5/20/2018 Oracle11g Slides
48/319
48
Functions on Numeric data types
Function Returns Example Result
ceil (n) Nearest whole integer greater
than or equal to n.
SELECT ceil (9.86)
FROM dual;
10
floor (n) Largest integer equal to or less
than n.
SELECT floor (9.86)
FROM dual;
9
mod (m, n) Remainder of m divided by n. If
n = 0, then m is returned.
SELECT mod (11, 4)
FROM dual;
3
power (m, n) Number m raised to the power
of n.
SELECT power (5, 2)
FROM dual;
25
round (n, m) Number n rounded off to m
decimal places.
SELECT round (9.86, 1)
FROM dual;
9.9
sign (n) If n = 0, returns 0.
If n > 0, returns 1.
If n < 0, returns -1.
SELECT sign (9.86)
FROM dual;
1
sqrt (n) Square root of n. SELECT sqrt (25) FROM
dual;
5
Functions on Character data type
-
5/20/2018 Oracle11g Slides
49/319
49
Functions on Character data type
Function Returns Example Result
initcap (x) Changes the first character of each
word to capital letters.
SELECT initcap
( 'inder kumar gujral' )FROM dual;
Inder Kumar
Gujral
lower (x) Converts the entire string to
lowercase.
SELECT lower
( 'Inder Kumar Gujral' )
FROM dual;
inder kumar
gujral
upper (x) Converts the entire string to
uppercase.
SELECT upper ( 'Inder
Kumar Gujral' ) FROMdual;
INDER
KUMARGUJRAL
replace (char,
str1, str2)
Every occurrence of str1 in char is
replaced with str2.
SELECT replace( 'Cap' ,
'C', 'M' ) FROM dual;
Map
soundex (x) Every word that has a similar
phonetic sound, even if it is
spelled differently.
SELECT emp_name FROM
employee WHERE soundex
(emp_name) = soundex
('Sivananda')
Shivanand Joshi
substr (char, m,
n)
Part of char, starting FROM
position m and taking characters.
SELECT substr
('Computer', 1, 4) FROM
dual;
Comp
length (char) Length of char. SELECT length ('Oracle')FROM dual; 6
Functions on Date data types
-
5/20/2018 Oracle11g Slides
50/319
50
Functions on Date data types
Function Returns Example Result
sysdate Current date and time. SELECT sysdateFROM dual;
25-NOV-97
last_day (date) Last day of the month for the
given date.
SELECT last_day
(sysdate) FROM dual;
30-NOV-97
add_months (date,n)
Adds n months to the givendate.
SELECT add_months(sysdate, 2) FROM dual;
25-JAN-98
months_between
(date1, date2)
Difference in months
between date1 and date2.
SELECT
months_between
(sysdate, '01-JAN-99')
FROM dual;
-13.20232
next_day (date,
day)
Date is the specified day of
the week after the given date.
SELECT next_day
(sysdate, 'sunday')
FROM dual;
30-NOV-97
Formats with Date data types
-
5/20/2018 Oracle11g Slides
51/319
51
Formats with Date data types
Format Returns Example Result
Y Last digit of the
year.
SELECT to_char (sysdate, 'Y')
FROM dual;
7
YY Last 2 digits of the
year.
SELECT to_char (sysdate, 'YY')
FROM dual;
97
YYY Last 3 digits of the
year
SELECT to_char (sysdate, 'YYY')
FROM dual;
997
YYYY All 4 digits of the
year
SELECT to_char (sysdate,
'YYYY') FROM dual;
1997
year Year spelled out. SELECT to_char (sysdate, 'year')
FROM dual;
Nineteen
ninety-
seven
Q Quarter of the year
(Jan through Feb is
1).
SELECT to_char (sysdate, 'q')
FROM dual;
4
Formats with Date data types
-
5/20/2018 Oracle11g Slides
52/319
52
Formats with Date data types
MM Month of the year
(01-12).
SELECT to_char
(sysdate, 'mm') FROM dual;
11
RM Roman numeral for
month.
SELECT to_char
(sysdate, 'rm') FROM dual;
XI
month Name of the monthas a nine-character
long string.
SELECT to_char(sysdate, 'month') FROM dual;
november
WW Week of the year SELECT to_char
(sysdate, 'ww') FROM dual;
48
W Week of the month SELECT to_char
(sysdate, 'w') FROM dual;
4
Format with Date data types
-
5/20/2018 Oracle11g Slides
53/319
53
Format with Date data types
Format Returns Example Result
DDD Day of the year; January 01 is
001; December 31 is 365 or 366.
SELECT to_char
(sysdate, 'ddd') FROMdual;
329
DD Day of the month. SELECT to_char
(sysdate, 'dd') FROM dual;
25
D Day of the week. Sunday = 1;
Saturday = 7.
SELECT to_char (sysdate,
'd') FROM dual;
3
DY Abbreviated name of the day. SELECT to_char (sysdate,
'dy') FROM dual;
tue
HH or
HH12
Hour of the day (01-12). SELECT to_char (sysdate,
'hh') FROM dual;
04
HH24 Hour of the day in 24-hourclock.
SELECT to_char(sysdate, 'hh24') FROM
dual;
16
MI Minutes (00-59) SELECT to_char
(sysdate, 'mi') FROM dual;
20
SS Seconds (00-59) SELECT to_chars sdate 'ss' FROM dual
22
Module : Advanced Queries
-
5/20/2018 Oracle11g Slides
54/319
54
Module : Advanced Queries
Overview
Table joins
Sub queries
Set operators
Multi-table insert and delete
MERGE statement
JOINS
-
5/20/2018 Oracle11g Slides
55/319
55
JOINS
Equi Join
SQL> SELECT emp_name, dept_name
FROM EMPLOYEE, DEPT
WHERE dept.dept_code = employee.dept_code;
JOINS
-
5/20/2018 Oracle11g Slides
56/319
56
JOINS
Self Join
SQL> SELECT a.emp_name, b.emp_name
FROM employee A, employee B
WHERE A.reports_to = B.emp_code;
JOINS
-
5/20/2018 Oracle11g Slides
57/319
57
JOINS
Outer Join
SQL> SELECT A.emp_name, B.emp_name
FROM employee A, employee B
WHERE A.reports_to = B.emp_code (+);
JOINS
-
5/20/2018 Oracle11g Slides
58/319
58
JOINS
SQL> SELECT emp_code, dept.dept_code FROM employee CROSS
JOIN dept;
SQL> SELECT emp_code,dept_code,dept_name
FROM employee NATURAL JOINdept ;
SQL> SELECT emp_code, dept_name
FROM employee JOINdept USING(dept_code);
SQL> SELECT emp_code, dept_name
FROM employee a JOINdept bON(a.dept_code=b.dept_code
And a.emp_code
-
5/20/2018 Oracle11g Slides
59/319
59
JOINS
SQL> SELECT a.emp_code, a.dept_code, b.dept_name
FROM employee a RIGHTOUTERJOINdept bON(a.dept_code=b.dept_code);
SQL> SELECT a.emp_code,a.dept_code,b.dept_name
FROM employee a LEFTOUTERJOINdept b
ON (a.dept_code=b.dept_code);
SQL> SELECT a.emp_code, a.dept_code, b.dept_name
FROM employee a FULLOUTERJOINdept b
ON (a.dept_code=b.dept_code);
SUBQUERIES
-
5/20/2018 Oracle11g Slides
60/319
60
SUBQUERIES
SQL> SELECT * FROM orders
WHERE cust_codeIN (SELECT cust_code FROM customerWHERE city_code = 'PUNE');
SQL> SELECT * FROM dept WHERE EXISTS(
SELECT * FROM employee WHERE employee.dept_code =
dept.dept_code);
SQL> SELECT * FROM dept WHERE NOTEXISTS(
SELECT * FROM employee WHERE employee.dept_code =
dept.dept_code);
SET Operators
-
5/20/2018 Oracle11g Slides
61/319
61
SET Operators
SQL> SELECT prod_code, prod_name FROM product
UNIONSELECT prod_code, prod_name FROM old_products;
SQL> SELECT * FROM product
INTERSECT
SELECT * FROM import_product;
SQL> SELECT * FROM product
MINUS
SELECT * FROM import_product;
Module : Creating Tables
-
5/20/2018 Oracle11g Slides
62/319
62
Module : Creating Tables
Overview
Creating a Table
Data Types
Creating Tables
-
5/20/2018 Oracle11g Slides
63/319
63
Creating Tables
SQL> CREATE TABLEdept (dept_code varchar2 (4),
dept_name varchar2 (20) );
CREATE TABLE tablename (
column-name data-type [other clauses]... );
Creating Tables
-
5/20/2018 Oracle11g Slides
64/319
64
Creating Tables
SQL> CREATE TABLEdept (
dept_code varchar2 (4),dept_name varchar2 (20) );
Data Types
-
5/20/2018 Oracle11g Slides
65/319
65
Data Types
Data
Type
Description Example
char (n) Fixed-length character data. Max 2000
bytes
dept_code char (4)
varchar
(n)
Variable-length character data. Max 4000
bytes
dept_code varchar2
(4)
varchar2(n)
Variable-length character data. Max sizeis 4000 bytes
dept_code varchar(4)
number
(p, s)
Numeric data, 'p' is the total length and
sis the number of decimal places.
reading number (5,
2). Maximum value:
99.99
Date Date and time. Range is 01/01/4712 BC
to 31/12/4712 AD.
date_join date
Data Types
-
5/20/2018 Oracle11g Slides
66/319
66
Data Types
Data
Type
Description Example
long Variable-length character data. Max 2 GB remarks long
raw (n) Binary format data. Max size 2000 bytes esc_seqraw (15)
Long raw Same as raw, but maximum size is 2 GB. picture long raw
BLOB Stores binary large objects up to 4GB
CLOB Stores character large objects up to 4GB.
BFILE Enables access to binary file LOBs that
are stored in the file system outside the
Oracle database. Maximum file size up to
4GB.
Module : Inserting, Modifying & Deleting Data
-
5/20/2018 Oracle11g Slides
67/319
67
Module : Inserting, Modifying & Deleting Data
Overview
Inserting Data into a Table
Inserting Data into a Table using Sub query
Modifying Data in a Table
Deleting Data from a Table
Inserting Data into a Table
-
5/20/2018 Oracle11g Slides
68/319
68
Inserting Data into a Table
SQL> desc dept;Name Null? Type
------------- --------------------- ------------------
DEPT_CODE NOT NULL VARCHAR2(4)
DEPT_NAME NOT NULL VARCHAR2(20)
SQL> INSERTINTOdept VALUES('MKTG', 'Marketing');
SQL> INSERTINTOdept VALUES('FIN', 'Finance');
SQL> INSERTINTOdept VALUES('TRNG', 'Training');
INSERT INTO table-name VALUES (value1, value2, ...);
Inserting Data into Table
-
5/20/2018 Oracle11g Slides
69/319
69
Inserting Data into Table
SQL> INSERTINTOemployee (emp_code, age, emp_name)
VALUES(101, 33, 'Sunil');
SQL> INSERTINTOsenior
SELECT * FROM employee WHERE age > 50;
Modifying and Deleting Data
-
5/20/2018 Oracle11g Slides
70/319
70
od y g a d e et g ata
SQL> UPDATEemployee SETsalary = salary + 100;
SQL> UPDATEemployee SETsalary = salary + 200 WHERE sex = 'F';
SQL> DELETEFROM employee;
SQL> DELETEFROM employee WHERE dept_code = 'MKTG';
Multi-Table Insert and Delete
-
5/20/2018 Oracle11g Slides
71/319
71
Multi-table inserts allow a single INSERT INTO .. SELECT
statement to conditionally, or non-conditionally, insert intomultiple tables.
It reduces table scans and PL/SQL code necessary forperforming multiple conditional inserts compared to previousversions.
Prior to Oracle 9i, the only option available was to runseparate insert statements, which was a costly option.
There are four kinds of multi-table insert. Unconditional Pivoting
Conditional
Insert First
Multi-Table Insert and Delete
-
5/20/2018 Oracle11g Slides
72/319
72
Unconditional Insert
Inserts the given data into multiple tables without restrictions.
INSERT ALL
insert Allinto salary_deduction
values(employee_id,ename,tax_ded,pre_tax_ded)
into Salary_pay
values(employee_id,ename,gross_pay,net_pay)
Select a.employee_id,d.ename,gross_pay,a.pre_tax_ded,a.tax_ded,a.net_payfrom extern_pay_amount a,emp d
where a.employee_id = d.empno
/
Multi-Table Insert and Delete
-
5/20/2018 Oracle11g Slides
73/319
73
Pivoting Insert
Is used to insert into the same table multiple times.
INSERT ALL
INTO all_paycheck VALUES (emp_id,'JAN',net_pay_jan)
INTO all_paycheck VALUES (emp_id,'FEB',net_pay_feb)INTO all_paycheck VALUES (emp_id,'MAR',net_pay_mar)
INTO all_paycheck VALUES (emp_id,'APR',net_pay_apr)
INTO all_paycheck VALUES (emp_id,'MAY',net_pay_may)
INTO all_paycheck VALUES (emp_id,'JUN',net_pay_jun)
SELECT emp_id,net_pay_jan, net_pay_feb, net_pay_mar, net_pay_apr,
net_pay_may, net_pay_jun
FROM monthwise_paycheck_report;
Multi-Table Insert and Delete
-
5/20/2018 Oracle11g Slides
74/319
74
Conditional Insert
Used for conditional control of each insert based on establishedspecific criteria.
INSERT ALL
WHEN grade like 'M%' thenINTO manager_pay VALUES (employee_id, gross_pay, net_pay)
WHEN dept_code like 'GEN' then
INTO worker_pay VALUES (employee_id, gross_pay, net_pay)
ELSE
INTO all_pay VALUES (employee_id, gross_pay, net_pay)SELECT employee_id, gross_pay, net_pay,grade,dept_code
FROM extern_pay_amount,employee
where extern_pay_amount.employee_id=employee.emp_code
Multi-Table Insert and Delete
-
5/20/2018 Oracle11g Slides
75/319
75
Insert First
Allows for conditional execution of an insert statement based on aseries of WHEN clause.
INSERT FIRST
WHEN grade like 'M%' then
INTO manager_pay VALUES (employee_id, gross_pay, net_pay)WHEN grade like 'E%' then
INTO worker_pay VALUES (employee_id, gross_pay, net_pay)
else
INTO all_pay VALUES (employee_id, gross_pay, net_pay)
SELECT employee_id, gross_pay, net_pay,grade
FROM extern_pay_amount,employee
where extern_pay_amount.employee_id=employee.emp_code;
MERGE statement
-
5/20/2018 Oracle11g Slides
76/319
76
Meaning
MERGE statement allows you to insert a record into a table if it
doesn't exist, and it allows you to update an existing record in a table
during the execution of the statement.
You can specify conditions to determine whether to update or insert
into the target table or view.
Is a convenient way to combine multiple operations.
It lets you avoid multiple INSERT, UPDATE, and DELETE DML
statements.
MERGE statement
-
5/20/2018 Oracle11g Slides
77/319
77
Example
MERGE INTOall_pay a
USING manager_pay b
on (a.emp_id=b.emp_id)
when matched thenupdate set a.gross_pay=b.gross_pay,a.net_pay=b.net_pay
when not matched then
insert values (b.emp_id,b.gross_pay,b.net_pay);
Module : Modifying Table Structure
-
5/20/2018 Oracle11g Slides
78/319
78
y g
Overview
Altering Table structure
Dropping Column from a Table
Dropping a Table
Modifying a Table Structure
-
5/20/2018 Oracle11g Slides
79/319
79
g
SQL> ALTERtable employee
ADD(age number (2));
SQL> ALTERtable employee
MODIFY(age number (3));
SQL> ALTERtable employee DROPcolumn sex;
SQL> ALTERtable employee DROP(age,married);
Dropping a Table
-
5/20/2018 Oracle11g Slides
80/319
80
SQL> DROPtable dept;
DROP TABLE table-name;
Module : Integrity Constraints
-
5/20/2018 Oracle11g Slides
81/319
81
Overview
Understanding Table and Column Constraints
Creating, Modifying and Dropping Column level constraints
Creating, Modifying and Dropping Table level constraints
Adding Constraints to Columns of an existing table
Enabling and Disabling Constraints
Dropping Columns and Tables having constraints
Integrity Constraints
-
5/20/2018 Oracle11g Slides
82/319
82
Not Null
Unique
Check
Primary Key
Foreign Key
Column Constraints
-
5/20/2018 Oracle11g Slides
83/319
83
SQL> CREATE TABLE employee (
emp_code number (5) NOTNULL,
emp_name varchar2 (25) NOTNULL,
dept_code varchar2 (4) );
Column Constraints
-
5/20/2018 Oracle11g Slides
84/319
84
SQL> CREATE TABLE employee (
emp_code number (5)
CONSTRAINT employee_uq UNIQUE,
emp_name varchar2 (25)
CONSTRAINT employee_null NOTNULL);
SQL> SELECT constraint_name FROM USER_CONSTRAINTS
WHERE table_name = 'EMPLOYEE';
The UNIQUE Constraint
-
5/20/2018 Oracle11g Slides
85/319
85
SQL> CREATE TABLE supplier (
supp_code number (4)
CONSTRAINT code_pk PRIMARY KEY,
supp_name varchar2 (30)
CONSTRAINTname_uq UNIQUE);
SQL> CREATE TABLE supplier (supp_code number (4)
CONSTRAINT code_pk PRIMARY KEY,
supp_name varchar2 (30)
CONSTRAINT name_uq UNIQUECONSTRAINT name_null NOT NULL);
The CHECK Constraint
-
5/20/2018 Oracle11g Slides
86/319
86
SQL> CREATE TABLE employee (
emp_code number (5) PRIMARY KEY,
emp_name varchar2 (25) NOT NULL,
dept_code varchar2 (4) CONSTRAINTcode_check
CHECK(dept_code = upper (dept_code) ));
The PRIMARY KEY Constraint
-
5/20/2018 Oracle11g Slides
87/319
87
SQL> CREATE TABLE employee (
emp_code number (5)
CONSTRAINT code_pk PRIMARYKEY,
emp_name varchar2 (25)
CONSTRAINT name_null NOT NULL,
dept_code varchar2 (4));
The REFERENCES Constraint
-
5/20/2018 Oracle11g Slides
88/319
88
SQL> CREATE TABLE employee (
emp_code number (5)CONSTRAINT code_pk PRIMARY KEY,
emp_name varchar2 (25)
CONSTRAINT name_null NOT NULL,
dept_code varchar2 (4)
CONSTRAINT code_ref
REFERENCESdept (dept_code));
The REFERENCES Constraint
-
5/20/2018 Oracle11g Slides
89/319
89
SQL> CREATE TABLE employee (
emp_code number (5) primary key,emp_name varchar2 (25) not null,
dept_code varchar2 (4) CONSTRAINTcode_ref
REFERENCESdept(dept_code)
ONDELETECASCADE);
The REFERENCES Constraint
-
5/20/2018 Oracle11g Slides
90/319
90
SQL> CREATE TABLE employee (
emp_code number (5) primary key,emp_name varchar2 (25) not null,
dept_code varchar2 (4) CONSTRAINTcode_ref
REFERENCESdept(dept_code)
ONDELETECASCADE);
Table Constraints
-
5/20/2018 Oracle11g Slides
91/319
91
SQL> CREATE TABLE employee(
emp_code number(4) not null,emp_name varchar2(40)not null,
dept_code varchar2(4),
CONSTRAINTemp_uq UNIQUE(emp_code,emp_name)
);
The PRIMARY KEY and CHECK Constraint
-
5/20/2018 Oracle11g Slides
92/319
92
SQL> CREATE TABLE orders (
order_year number (4),order_number number (5),
order_date date,
CONSTRAINTorder_pk PRIMARYKEY(order_year,
order_number));
SQL> CREATE TABLE employee (emp_code number (4),
emp_name varchar2 (20),date_birth date,date_join date,
CONSTRAINTemployee_dates CHECK(date_join >
date_birth));
The FOREIGN KEY Constraint
-
5/20/2018 Oracle11g Slides
93/319
93
SQL> CREATE TABLE ship (
ship_code varchar2 (5),ship_name varchar2 (20) not null,
CONSTRAINTship_pk PRIMARY KEY(ship_code) );
SQL> CREATE TABLE voyage (ship_code varchar2 (5),
voyage_number number (3),
date_arrival date,
CONSTRAINT voyage_pk PRIMARY KEY(ship_code,voyage_number),
CONSTRAINTvoyage_fk FOREIGNKEY(ship_code)
REFERENCESship (ship_code) );
The FOREIGN KEY Constraint
-
5/20/2018 Oracle11g Slides
94/319
94
SQL> CREATE TABLE docket (
docket_number number (5),docket_date date,
ship_code varchar2 (5),
voyage_number number (3),
CONSTRAINT docket_pk PRIMARY KEY
(docket_number),CONSTRAINTdocket_fk FOREIGNKEY(ship_code,
voyage_number)
REFERENCESvoyage (ship_code, voyage_number)
ONDELETECASCADE);
Adding Constraints to Columns of an existing Table
-
5/20/2018 Oracle11g Slides
95/319
95
SQL> ALTER TABLEemployee MODIFY
(date_join constraint emp_dt_join not null);
SQL> ALTER TABLEdept
ADDCONSTRAINT cd_pk PRIMARY KEY (dept_code);
SQL> ALTER TABLEemployee ADD
CONSTRAINT cd_fk FOREIGN KEY(dept_code)
REFERENCES dept (dept_code);
Adding Constraints to Columns of an existing Table
-
5/20/2018 Oracle11g Slides
96/319
96
SQL> ALTER TABLEemployee ADD
CONSTRAINT emp_dates CHECK (date_join > date_birth);
Enabling and Disabling Constraints
-
5/20/2018 Oracle11g Slides
97/319
97
SQL> alter table dept
DISABLECONSTRAINTcd_pk;
SQL> alter table dept
ENABLECONSTRAINTcd_pk;
SQL> alter table deptDISABLECONSTRAINTcd_pk CASCADE;
Cascading Constraints
-
5/20/2018 Oracle11g Slides
98/319
983-98
Example:ALTER TABLE ord2459DROP COLUMN order_id CASCADE CONSTRAINTS;
ALTER TABLE test1
DROP (col1_pk, col2_fk, col1) CASCADE CONSTRAINTS;
Renaming Table Columns and Constraints
-
5/20/2018 Oracle11g Slides
99/319
993-99
Use the RENAME COLUMN clause of the ALTER TABLE statement to
rename table columns.
Use the RENAME CONSTRAINT clause of the ALTER TABLE statement to
rename any existing constraint for a table.
ALTER TABLE marketing RENAME COLUMN team_idTO id;
ALTER TABLE marketing RENAME CONSTRAINT mktg_pk
TO new_mktg_pk;
a
b
Dropping a Constraint
-
5/20/2018 Oracle11g Slides
100/319
100
SQL> alter table employee
DROPCONSTRAINT emp_date;
SQL> alter table employee
DROPCONSTRAINT emp_date CASCADE;
Dropping a Constraint
-
5/20/2018 Oracle11g Slides
101/319
101
SQL> alter table dept
DROP COLUMN dept_code CASCADECONSTRAINTS;
SQL> drop table dept CASCADE CONSTRAINTS;
Module : Sequences & Synonyms
-
5/20/2018 Oracle11g Slides
102/319
102
Overview
Creating, altering, dropping and using Sequences
Creating, dropping and using Synonyms
Querying the data dictionary
Sequences
-
5/20/2018 Oracle11g Slides
103/319
103
CREATE SEQUENCE sequence_name
[INCREMENT BY n1]
[START WITH n2]
[MAXVALUE n3]
[MINVALUE n4]
[CYCLE | NOCYCLE];
Is a database object which is used to generate automatic unique
integer values.
Sequences
-
5/20/2018 Oracle11g Slides
104/319
104
SQL> CREATESEQUENCEEmp_Number
IncrementBy2
StartWith3;
Sequences
-
5/20/2018 Oracle11g Slides
105/319
105
SQL> insert into employee (emp_code, emp_name)
values (EMP_NUMBER.NEXTVAL, 'Satish');
SQL> SELECT EMP_NUMBER.CURRVALFROM dual;
Sequences
-
5/20/2018 Oracle11g Slides
106/319
106
SQL> ALTERSEQUENCEemp_number
maxvalue 250;
SQL> DROPSEQUENCEemp_number;
Synonyms
-
5/20/2018 Oracle11g Slides
107/319
107
Is an alternative name for another object, which may be a
table, view, index or a sequence.
CREATE SYNONYM synonym_name FOR table_name
Synonyms
-
5/20/2018 Oracle11g Slides
108/319
108
SQL> CREATE SYNONYMmyemp for employee;
SQL> SELECT * FROM myemp;
SQL> DROPSYNONYMmyemp;
Querying the Data Dictionary
-
5/20/2018 Oracle11g Slides
109/319
109
For Sequences
desc USER_SEQUENCES SELECT * FROM USER_SEQUENCES;
For Synonyms
desc USER_SYNONYMS
SELECT * FROM USER_SYNONYMS;
Module : Indexes
-
5/20/2018 Oracle11g Slides
110/319
110
Overview
Understanding Indexes
Unique and Non-unique Indexes
Creating and dropping Indexes
Querying the Data Dictionary
Indexes
-
5/20/2018 Oracle11g Slides
111/319
111
Are database objects used to improve the performance of the
database.
Uses the ROWID for search operations.
There are two types of index:
UNIQUENON UNIQUE
SQL> CREATEUNIQUEINDEXcode_idx ONemployee(dept_code);
CREATE [UNIQUE] INDEX index_name ON table_name
(column_name);
Indexes
-
5/20/2018 Oracle11g Slides
112/319
112
SQL> CREATEINDEXcd_idx ONemployee (dept_code);
SQL> CREATEINDEXemp_idx ONemployee (dept_code, emp_code);
SQL> DROP INDEXcd_idx;
Querying the Data Dictionary
-
5/20/2018 Oracle11g Slides
113/319
113
SQL> desc USER_INDEXES
SQL> SELECT index_name, uniqueness FROM USER_INDEXES
WHERE table_name = 'EMPLOYEE';
Module : Views
-
5/20/2018 Oracle11g Slides
114/319
114
Overview
Understanding Views
Creating views
Altering & dropping views
Manipulating data using views
Querying the Data Dictionary
Views
-
5/20/2018 Oracle11g Slides
115/319
115
SQL> CREATEVIEWfin_emp AS
SELECT * FROM employee WHERE dept_code = 'FIN';
SQL> SELECT * FROM fin_emp;
SQL> DELETEfin_emp;
Views
-
5/20/2018 Oracle11g Slides
116/319
116
SQL> insert into fin_emp(emp_code, emp_name, dept_code)
values (111, 'Sunil', 'FIN');
SQL> CREATEORREPLACE VIEWfin_emp AS
SELECT * FROM employee;
Views
-
5/20/2018 Oracle11g Slides
117/319
117
SQL> CREATE OR REPLACE view fin_emp AS
SELECT * FROM employee
withreadonly;
SQL> DROPVIEWfin_emp;
Querying the Data Dictionary
-
5/20/2018 Oracle11g Slides
118/319
118
SQL> desc USER_VIEWS
SQL> SELECT view_name, text FROM USER_VIEWS;
Module :Materialized Views
-
5/20/2018 Oracle11g Slides
119/319
119
Materialized views are special kind of views, which
physically exist inside the database. Their basic purpose is to improve query execution time.
The biggest benefits of using materialized views will be seen
by users of data warehouse.
Oracle makes the task of creating and maintaining summarytables easy, through the concept of materialized views.
You can visualize a materialized view to be like any other
view, but one which is physically created and allocated space
on the disk. Materialized views have values that are stored in them.
How Do Materialized Views Work?
-
5/20/2018 Oracle11g Slides
120/319
120
A materialized view contains the results of a pre-defined
query, such as the sum of sales by region over a period of
time.
There is no limit to the number of materialized views that
may be defined.
When a SQL query is issued, the query rewrite facility within
Oracle will determine whether a suitable materialized view is
available.
If it is, Oracle will transparently rewrite the query to use the
materialized view instead.
Materialized Views & Performance
-
5/20/2018 Oracle11g Slides
121/319
121
They significantly improve performance since the queryaccesses the small set of rows in the materialized view ratherthan all the rows in the tables referenced by the query.
They are an extremely important feature for enhancing theperformance of complex business intelligence queries.
You can set up the materialized views to be automaticallyupdated when the tables that they are based upon, change.
Or when you explicitly issue a command to refresh them.
This makes the management of the materialized viewssimpler.
Materialized Views & Refresh Methods
-
5/20/2018 Oracle11g Slides
122/319
122
Whenever the underlying tables of a materialized view are
updated, Oracle marks the materialized view as stale.
Unless QUERY_REWRITE_INTEGRITY is set to
stale_tolerated, a stale materialized view will not be used by
the query rewrite engine.
Oracle provides a mechanism to keep the materialized view
fresh with respect to the base tables called materialized view
refresh.
Materialized Views & Refresh Methods
-
5/20/2018 Oracle11g Slides
123/319
123
The following types of refresh methods are supported by
Oracle. Complete - build from scratch
Fast - only apply the data changes
Force - try a fast refresh, if that is not possible, do a complete refresh
Never - never refresh the materialized view
Materialized Views
-
5/20/2018 Oracle11g Slides
124/319
124
Consider the following query:
select prodgr_name, prod_name,sum (target) from prodgrup, product
where prodgrup.prodgr_code = product.prodgr_code group by
prodgr_name,prod_name;
A materialized view for the above can be created as follows:
create materialized view product_wise_profit_total
build immediate
refresh on commit
enable query rewrite
as select prodgr_name, prod_name,
sum (target) from prodgrup, product
where prodgrup.prodgr_code = product.prodgr_code group by
prodgr_name,prod_name;
Materialized Views
-
5/20/2018 Oracle11g Slides
125/319
125
In the above command :
build immediate can be replaced by build deferred
refresh on commit can be replaced by refresh on demand
enable query rewrite can be replaced by disable query
rewrite
Module : Transaction Processing
-
5/20/2018 Oracle11g Slides
126/319
126
COMMIT
ROLLBACK
ROLLBACK TO SAVEPOINT
SAVEPOINT
LOCK TABLE
Transaction Processing
-
5/20/2018 Oracle11g Slides
127/319
127
SQL> SAVEPOINT savepointname;
SQL> SAVEPOINT stage1;SQL> ROLLBACK TO savepointname;
SQL> ROLLBACK TO stage1;
Transaction Processing
-
5/20/2018 Oracle11g Slides
128/319
128
lock table table_reference_list in lock_mode [nowait]
SQL> LOCK table emp IN ROW EXCLUSIVE MODE;
SQL> LOCK table emp,dept IN SHARE MODE NOWAIT;
SQL> LOCK table scott.emp@new_york IN SHARE UPDATE MODE;
SQL> update employee
set salary =
(SELECT salary FROM employeeWHERE emp_name = 'Manorama Gupta'
)
WHERE emp_name = 'Neerja Girdhar';
Module : Formatting the Output
-
5/20/2018 Oracle11g Slides
129/319
129
Overview
Setting page layout
Formatting column output and spooling
Computing column values at breaks in SQL * Plus
Setting Page Layout
-
5/20/2018 Oracle11g Slides
130/319
130
SQL> set LINESIZE 60;
SQL> set PAGESIZE 20;
SQL> TTITLE 'List of Employees';
SQL> TTITLE 'Pragati Software|List of Employees';
SQL> BTITLE 'Sample Report';
Formatting Column Output
-
5/20/2018 Oracle11g Slides
131/319
131
SQL> SPOOL c:\mydata\output.txt;
SQL> COLUMN emp_name FORMAT A10 HEADING 'Employee|Name';
SQL> COLUMN salary FORMAT 9,99,999;
SQL> show all;
Formatting the Output
SELECT d
-
5/20/2018 Oracle11g Slides
132/319
132
SQL> SELECT dept_name,
emp_name, salary
FROM employee, deptWHERE employee.dept_code
= dept.dept_code
ORDER BY dept_name;
SQL> BREAK ON dept_name;
SQL> SELECT dept_name,
emp_name, salary
FROM employee, dept
WHERE employee.dept_code
= dept.dept_code
ORDER BY dept_name;
Formatting the Output
-
5/20/2018 Oracle11g Slides
133/319
133
SQL> break on dept_name SKIP 1;
SQL> COMPUTE SUM OF salary
on dept_name;
Formatting the Output
-
5/20/2018 Oracle11g Slides
134/319
134
SQL> break on report skip on dept_name skip 2;
SQL> show all;
MODULE:DROP TABLE PURGE
-
5/20/2018 Oracle11g Slides
135/319
135
DROP TABLE dept80 PURGE ;
MODULE:FLASHBACKTABLEStatement
-
5/20/2018 Oracle11g Slides
136/319
136
Enables you to recover tables to a specified point in time with a single
statement Restores table data along with associated indexes and constraints
Enables you to revert the table and its contents to a certain point in time
or system change number (SCN)
SCN
FLASHBACKTABLEStatement
-
5/20/2018 Oracle11g Slides
137/319
1373-137
Repair tool for accidental table modifications
Restores a table to an earlier point in time
Benefits: Ease of use, availability, and fast execution
Is performed in place
Syntax:
FLASHBACK TABLE[schema.]table[,
[ schema.]table ]...
TO { TIMESTAMP | SCN } expr
[ { ENABLE | DISABLE } TRIGGERS ];
Using the FLASHBACKTABLEStatement
-
5/20/2018 Oracle11g Slides
138/319
138
DROP TABLE emp2 ;
FLASHBACK TABLE emp2 TO BEFORE DROP;
SELECT original_name, operation, droptime FROM recyclebin ;
MODULE:Temporary Tables
-
5/20/2018 Oracle11g Slides
139/319
1393-139
When
session/transaction
completes
Creating a Temporary Table
-
5/20/2018 Oracle11g Slides
140/319
140
CREATE GLOBAL TEMPORARY TABLE cart
ON COMMIT DELETE ROWS ;
CREATE GLOBAL TEMPORARY TABLE today_sales
ON COMMIT PRESERVE ROWS AS
SELECT * FROM orders
WHERE order_date = SYSDATE ;
1
2
MODULE: External Tables
-
5/20/2018 Oracle11g Slides
141/319
141
Creating a Directory for the External Table
-
5/20/2018 Oracle11g Slides
142/319
142
Create a DIRECTORY object that corresponds to the directory on the file
system where the external data source resides.
CREATE OR REPLACE DIRECTORY emp_dir
AS '//emp_dir';
GRANT READ ON DIRECTORY emp_dir TO ora_21;
Creating an External Table
-
5/20/2018 Oracle11g Slides
143/319
1443-144
CREATE TABLE
( , )ORGANIZATION EXTERNAL
(TYPE
DEFAULT DIRECTORY ACCESS PARAMETERS
( ) )LOCATION ('')
REJECT LIMIT [0 | | UNLIMITED];
Creating an External Table by UsingORACLE_LOADER
-
5/20/2018 Oracle11g Slides
144/319
146
CREATE TABLE oldemp (
fname char(25), lname CHAR(25))
ORGANIZATION EXTERNAL
( TYPE ORACLE_LOADER
DEFAULT DIRECTORY emp_dir
ACCESS PARAMETERS
( RECORDS DELIMITED BY NEWLINE
NOBADFILE
NOLOGFILE
FIELDS TERMINATED BY ' , '
( fname POSITION ( 1:20 ) CHAR ,
lname POSITION ( 22:41 ) CHAR ) )
LOCATION ( ' emp.dat ' ) )
PARALLEL 5
REJECT LIMIT 200 ;
Querying External Tables
-
5/20/2018 Oracle11g Slides
145/319
1483-148
SELECT *
FROM oldemp
emp.datOLDEMP
Module : Introduction to PL/SQL
-
5/20/2018 Oracle11g Slides
146/319
149
Overview
Understanding PL/SQL
PL/SQL data types
Declaring variables
Looping and Conditional constructs
Anchored Data types
PL/SQL
Facilities provided by PL/SQL
-
5/20/2018 Oracle11g Slides
147/319
150
Facilities provided by PL/SQL
Row-level processing
Conditional statements (IF...ELSE...END IF, CASE) Looping statements (FOR...NEXT, WHILE...LOOP...END
LOOP, etc.)
Variable declaration and manipulation
Exception handling
User-defined procedures which may be called FROM
anyWHERE
SQL> update employee
set salary = salary + 111WHERE dept_code = 'MKTG';
PL/SQL
SQL> begin
-
5/20/2018 Oracle11g Slides
148/319
151
SQL> begin
update employee
set salary = salary + 111
where dept_code = 'MKTG';
end;
SQL> @pl_sql_filename;
or
SQL> run pl_sql_filename;
PL/SQL
SQL> begin
-
5/20/2018 Oracle11g Slides
149/319
152
SQL> begin
update employee
set salary = salary + 111 WHERE dept_code =&deptval;
end;
SQL> declare
nSalary number (6);begin
SELECT salary into nSalary
FROM employee WHERE emp_code = 11;
if nSalary < 8000 then
update employee
set salary = salary + 101 WHERE emp_code = 11;
end if;
end;
PL/SQL Data Types
Scalar
-
5/20/2018 Oracle11g Slides
150/319
153
Scalar
Composite Reference
LOB
Scalar Types
S l i d h h ld i l l S l
-
5/20/2018 Oracle11g Slides
151/319
154
Scalar type is a data type that holds a single value. Scalar
type includes the following categories: Character / String
Number
Boolean
Date / Time
Scalar Types
Ch / S i
-
5/20/2018 Oracle11g Slides
152/319
155
Character / String
Allows PL/SQL character or string types.
Up to 32 K in size.
Number
Allows integer data types.
Boolean
Allows TRUE, FALSE or NULL values.
Scalar Types
D / Ti
-
5/20/2018 Oracle11g Slides
153/319
156
Date / Time
Include DATE and TIMESTAMP datatypes. DATE type is used to store date.
TIMESTAMP is an extension of DATE type. Includes year, month,
day, hour, minute, seconds and fraction of second.
Scalar Types
Ti t
-
5/20/2018 Oracle11g Slides
154/319
157
Timestamp
Provides date and time with fraction of seconds up to 9 places.
declare
v_date timestamp(9) := systimestamp;
begin
dbms_output.put_line(v_date);end;
Scalar Types
Ti t ith ti
-
5/20/2018 Oracle11g Slides
155/319
158
Timestamp with time zone
Is an extension of TIMESTAMP type in that it stores the local
timestamp relative to UTC.
declare
v_date timestamp(3) with time zone := systimestamp;begin
dbms_output.put_line(v_date);
end;
Scalar Types
Ti t ith l l ti
-
5/20/2018 Oracle11g Slides
156/319
159
Timestamp with local time zone
Returns time corresponding to the location of the client accessing the
database server.
declare
v_date timestamp(5) with local time zone := systimestamp;
begindbms_output.put_line(v_date);
end;
Composite Types
C t i i t l t
-
5/20/2018 Oracle11g Slides
157/319
160
Contain internal components
Are reusable
Are of two types:
PL/SQL Records
PL/SQL Collections
Index By tables
Varrays
Nested tables
Object types
Reference Types and LOB Types
Reference t pes pro ide memor str ct res
-
5/20/2018 Oracle11g Slides
158/319
161
Reference types provide memory structures
They can point to different storage locations through out theprogram
Are of two types:
Ref Cursor
Ref
LOB types are used to work with data types up to 4 GBin size.
PL/SQL IF-ELSE Statements
-
5/20/2018 Oracle11g Slides
159/319
162
if nValue > 40 then
nCount := nCount + 1;end if;
if nValue > 40 then
if nValue < 50 then
nCount := nCount + 1;
end if;
end if;
if nValue between 40 and 50 then
nCount := nCount + 1;
end if;
PL/SQL IF-ELSE Statements
-
5/20/2018 Oracle11g Slides
160/319
163
if nValue > 40 then
nCount1 := nCount1 + 1;else
nCount2 := nCount2 + 1;
end if;
if nSalary < 2000 then
nProfTax := 0;elsif nSalary < 3500 then
nProfTax := 15;
elsif nSalary < 5000 then
nProfTax := 30;else
nProfTax := 50;
end if;
PL/SQL
SQL> declare
-
5/20/2018 Oracle11g Slides
161/319
164
Q
nSalary number (6);
beginSELECT salary intonSalary
FROM employee WHERE emp_code SELECT ename
-
5/20/2018 Oracle11g Slides
162/319
165
SQL SELECT ename,
( casedeptno
when10 then'ACCOUNTS'when20 then'RESEARCH'
when30 then'SALES'
when40 then'OPERATIONS'
else'UNASSIGNED'end
) as Department
FROM emp;
PL/SQL
SQL> SELECT ename,sal,deptno,
-
5/20/2018 Oracle11g Slides
163/319
166
SQL SELECT ename,sal,deptno,
Case
whensal500 and sal=1500 and sal 1500 and sal =2500 then300
Else0
Endbonus
FROM emp;
PL/SQL LOOPS
SQL> declare
-
5/20/2018 Oracle11g Slides
164/319
167
nCode number (5);
beginnCode := 101;
loop
insert into employee (emp_code, emp_name)
values (nCode, 'Somebody');nCode := nCode + 1;
if nCode > 110 then
exit;
end if;
endloop;end;
PL/SQL LOOPS
SQL> declare
nCode number (5);
-
5/20/2018 Oracle11g Slides
165/319
168
nCode number (5);
begin nCode := 101;
whilenCode begin
PL/SQL LOOPS
-
5/20/2018 Oracle11g Slides
166/319
169
Q g
forncode in101..110
loopinsert into employee (emp_code, emp_name)
values (ncode, 'somebody');
endloop;
end;
FOR variable in [REVERSE] lowerbound .. Upperbound
LOOP
statements;
END LOOP;
PL/SQL
SQL> declare
-
5/20/2018 Oracle11g Slides
167/319
170
Q
nSalary employee.salary%type;
beginSELECT salary into nsalary
FROM employee
WHERE emp_code = 11;
if nsalary < 8000 then
update employee
set salary = salary + 101
WHERE emp_code = 11;
end if;
end;
PL/SQL
SQL> declare
-
5/20/2018 Oracle11g Slides
168/319
171
SQL> declare
nRecord employee%rowtype;begin
SELECT * into nRecord
FROM employee
WHERE emp_code = 11;
if nRecord.salary < 8000 thenupdate employee
set salary = salary + 101
WHERE emp_code = 11;
end if;end; recorddatatype.columnname
nRecord.Salary
PL/SQL
SQL> declare
-
5/20/2018 Oracle11g Slides
169/319
172
nRecord employee%rowtype;
nFactor constantnumber (4, 2) := 1.11;begin
SELECT * into nRecord
FROM employee
WHERE emp_code = 11;if nRecord.salary < 8000 then
update employee
set salary = salary * nFactor
WHERE emp_code = 11;
end if;end;
constantname CONST datatype := value;
Module : Cursors
Overview
-
5/20/2018 Oracle11g Slides
170/319
173
Overview
Understanding Cursors
Types of cursors
Cursor operations
Cursor attributes
Parameterized Cursors
Cursor FOR loop
REF Cursors
Cursors
Provide a subset of data, defined by a query, retrieved into
-
5/20/2018 Oracle11g Slides
171/319
174
Provide a subset of data, defined by a query, retrieved into
memory when opened, and stored in memory until the cursor is
closed.
Point to a memory region in the Process Global Area (PGA)
called the context area.
Context area holds:Reference to the rows returned by the query
Number of rows processed by the query
A pointer to the parsed query in the Shared Pool
Pointer is to memory, not to the data directly.
We are guaranteed a consistent view of data throughout thetransaction.
Types of Cursors
Implicit Cursors
-
5/20/2018 Oracle11g Slides
172/319
175
Implicit Cursors
Are implicitly created by PL/SQL, whenever any DML orSELECT....INTO statement is executed in a PL/SQL block.
Explicit Cursors
Are declared and named by the programmer.
The programmer directly controls almost all operations of thecursor.
CURSOR employee_cur IS select * from employee;
OPEN employee_cur;
FETCH employee_cur INTO employee_rec;
CLOSE employee_cur;
Implicit Cursors
SQL> declare
-
5/20/2018 Oracle11g Slides
173/319
176
SQL declare
var1 varchar2(30);begin
SELECT emp_name INTOvar1 FROM employee
WHEREemp_code=34;
dbms_output.put_line('Value of var1 is : '||var1);end;
Implicit Cursor Attributes
SQL%FOUND
-
5/20/2018 Oracle11g Slides
174/319
177
SQL%NOTFOUND
SQL%ROWCOUNT SQL%ISOPEN
Implicit Cursors
SQL> begin
-
5/20/2018 Oracle11g Slides
175/319
178
Q g
update employee set salary = salary + 100where dept_code='TRNG';
dbms_output.put_line(SQL%ROWCOUNT|| 'rows updated');
if SQL%NOTFOUND
thendbms_output.put_line ('Unable to update department
TRNG');
end if;
end;
Explicit Cursors
To use an explicit cursor, we have to perform 4 different
-
5/20/2018 Oracle11g Slides
176/319
179
p , p
operations:
Declare the cursor
Open the cursor
Fetch the cursor
Close the cursor
Explicit Cursors
SQL> declare
-
5/20/2018 Oracle11g Slides
177/319
180
Q
cursorsales is
SELECT
a.salesman_id,a.salesman_name, b.target, c.sales
FROM salesman a, target b, sales c
WHERE a.salesman_id=b.salesman_id
and b.tmonth=c.smonth;begin
..............
end;
Explicit CursorsSQL>declare
/* explicit declaration of a cursor*/
-
5/20/2018 Oracle11g Slides
178/319
181
p
cursoremptyp_cur isSELECT emptyp.type
fromemployee emp, employee_type emptyp
WHERE emp.type_code= emptyp.type_code;
begin
/* check to see if cursor is already open. If not, open it.
checked using %isopen. It is a cursor attribute explained later */if not emptyp_cur%isopen then
openemptyp_cur;
end if;
/* fetch row FROM cursor directly into an oracle forms item*/fetchemptyp_cur into :emp.type_desc;
/* close the cursor*/
closeemptyp_cur;
end;
Explicit Cursor Operations
Cursor Operations
-
5/20/2018 Oracle11g Slides
179/319
182
p
Parse
Bind
Open
Execute
Fetch
Close
Explicit Cursor Attributes
Name Description
-
5/20/2018 Oracle11g Slides
180/319
183
%FOUND Returns TRUE if record was fetched successfully,
FALSE otherwise.
%NOTFOUND Returns TRUE if record was not fetched successfully,
FALSE otherwise.
%ROWCOUNT Returns number of records fetched FROM the cursor at
that point in time.%ISOPEN Returns TRUE if cursor is open, FALSE otherwise
CURSOR caller_cur ISSELECT caller_id, company_id FROM caller;
Explicit CursorsSQL>declare
cursor caller_cur is SELECT caller_id, company_id FROM caller;
-
5/20/2018 Oracle11g Slides
181/319
184
caller_rec caller_cur%rowtype;
begin/*open the cursor if it is not open*/
if not caller_cur%isopenthen open caller_cur;
end if;
fetch caller_cur into caller_rec;
/* keep fetching until no more records are found */
while caller_cur%found
loop
dbms_output.put_line ('Just fetched record number' || to_char
(caller_cur%rowcount));fetch caller_cur into caller_rec;
end loop;
close caller_cur;
end;
Explicit Cursors
SQL> declare
cursor emp cur is SELECT * FROM employee;
-
5/20/2018 Oracle11g Slides
182/319
185
cursor emp_cur is SELECT FROM employee;
emp_rec emp_cur%rowtype;v_rowcount number :=0;
begin
if not emp_cur%isopenthen
open emp_cur;
end if;
loop
fetch emp_cur into emp_rec;
dbms_output.put_line(emp_rec.emp_name);
v_rowcount := emp_cur%rowcount;exit when emp_cur%notfound;
end loop;
Explicit Cursors
dbms_output.put_line('total rows retrieved are : ' ||
-
5/20/2018 Oracle11g Slides
183/319
186
v_rowcount);
close emp_cur;
if emp_cur%isopen=false then
dbms_output.put_line('cursor closed');
elsedbms_output.put_line('the cursor is still open');
end if;
end;
Explicit Cursors
-
5/20/2018 Oracle11g Slides
184/319
187
Explicit Cursors
SQL> open caller_cur;
-
5/20/2018 Oracle11g Slides
185/319
188
loop
fetch caller_cur into caller_rec;
exit when not caller_cur%found;
update caller set caller_id=caller_rec.caller_id;
WHERE call_timestamp< sysdate;
end loop;close caller_cur;
Cursors
Differences Between Implicit and Explicit Cursor Attributes
-
5/20/2018 Oracle11g Slides
186/319
189
If the RDBMS has not opened an SQL cursor in the session,SQL%ROWCOUNT attribute returns NULL. References to other attributes(ISOPEN, FOUND, NOTFOUND) all return FALSE .
The %ISOPEN attribute will always return FALSEbefore and after theSQL statement.
You must reference the SQL% attribute immediately after you execute theSQL statement.
The %FOUND attribute returns TRUE if an UPDATE, DELETE or INSERTaffected at least one record. It will return FALSE if those statements failed toaffect any records.
When an implicit SELECT statement does not return any rows, PL/SQLraises NO_DATA_FOUND exception and if more than one row are returned,PL/SQL raises the TOO_MANY_ROWS exception.
Parameterized Cursors
Provide a way to pass information into and out of a module.
-
5/20/2018 Oracle11g Slides
187/319
190
y p
Makes a cursor more reusable.
Makes the cursor more generalized.
Parameterized Cursors
SQL> declare
CURSOR employee cur(dept desc varchar2)
-
5/20/2018 Oracle11g Slides
188/319
191
CURSOR employee_cur(dept_desc varchar2)
ISSELECT emp_name,salary,dept_code FROM employee
WHERE dept_code= upper(dept_desc);
emp_rec employee_cur%rowtype;
begin open employee_cur('&dept_desc');
fetch employee_cur into emp_rec;
DBMS_OUTPUT.PUT_LINE(emp_rec.emp_name|| '
' ||emp_rec.salary|| ' ' ||emp_rec.dept_code);
end;
Cursor FOR Loop
Is associated with an explicit cursor or a SELECT statement
-
5/20/2018 Oracle11g Slides
189/319
192
embedded directly within a loop.
Does not require an explicit OPEN, FETCH or, CLOSE.
PL/SQL handles its processing.
The variable declared in the FOR loop need not be declared.
Cursor FOR Loop
SQL> declare
-
5/20/2018 Oracle11g Slides
190/319
193
CURSOR c1 IS SELECT emp_name, dept_code FROM
employee WHERE dept_code LIKE '%FI%';
begin
FOR item IN c1
loop
dbms_output.put_line('Name = ' || item.emp_name || ',
Department code = ' || item.dept_code);
end loop;
end;
REF Cursors
REF Cursors offer a dynamic and persistent cursor alternative
-
5/20/2018 Oracle11g Slides
191/319
194
to the static explicit cursors.
Are evaluated at run time instead of compile time.
Can be opened for multiple SELECT statements in the sameblock.
That is, a single cursor variable can be used to fetch fromdifferent result sets.
REF Cursors can be either strongly typedor weakly typed.
REF Cursors
Declaring REF CURSOR types and Cursor Variables:
-
5/20/2018 Oracle11g Slides
192/319
195
TYPE company_curtype is REF CURSOR RETURN
company%rowtype;
TYPE generic_curtype is REF CURSOR ;
TYPE cursor_type_name is REF CURSOR [return return_type];
REF Cursors
SQL> declare
TYPE emp type is REF CURSOR return employee%rowtype;
-
5/20/2018 Oracle11g Slides
193/319
196
TYPE emp_type is REF CURSOR return employee%rowtype;
emp_curv emp_type;v_emp employee%rowtype;
begin
OPEN emp_curv FOR
SELECT * FROM employee WHERE dept_code='FIN';
dbms_output.put_line('-----------------');dbms_output.put_line('Opened the cursor');
dbms_output.put_line('-----------------');
loop
FETCH emp_curv INTO v_emp;
EXIT WHEN emp_curv%NOTFOUND;
dbms_output.put_line(v_emp.emp_name);
end loop;
CLOSE emp_curv;
REF Cursors
OPEN emp_curv FOR
-
5/20/2018 Oracle11g Slides
194/319
197
select * from employee where dept_code='TRNG';
dbms_output.put_line('-----------------------');
dbms_output.put_line('Opened the cursor again');
dbms_output.put_line('-----------------------');
loop
FETCH emp_curv INTO v_emp;
EXIT WHEN emp_curv%NOTFOUND;
dbms_output.put_line(v_emp.emp_name);
end loop;
CLOSE emp_curv;
END;
REF Cursors
-
5/20/2018 Oracle11g Slides
195/319
198
REF CursorsSQL> declare
TYPE emp_type is REF CURSOR;
t
-
5/20/2018 Oracle11g Slides
196/319
199
emp_curv emp_type;
v_emp employee%rowtype;v_dept dept%rowtype;
begin
OPEN emp_curv FOR
SELECT * FROM employee WHERE dept_code='MKTG';
dbms_output.put_line('-------------------------------');
dbms_output.put_line('Opened the cursor for EMP table');
dbms_output.put_line('-------------------------------');
loop
FETCH emp_curv INTO v_emp;EXIT WHEN emp_curv%NOTFOUND;
dbms_output.put_line(v_emp.emp_name);
end loop;
close emp_curv;
REF Cursors
OPEN emp_curv FOR
l t * f d t
-
5/20/2018 Oracle11g Slides
197/319
200
select * from dept;
dbms_output.put_line('--------------------------------');
dbms_output.put_line('Opened the cursor for DEPT table');
dbms_output.put_line('--------------------------------');
loop
FETCH emp_curv INTO v_dept;
EXIT WHEN emp_curv%NOTFOUND;
dbms_output.put_line(v_dept.dept_name);
end loop;
CLOSE emp_curv;
end;
REF Cursors
-
5/20/2018 Oracle11g Slides
198/319
201
Module : Exception Handlers
Overview
-
5/20/2018 Oracle11g Slides
199/319
202
Understanding exceptions
Named system exceptions
Unnamed system exceptions
Named programmer-defined exceptions
Unnamed programmer-defined exceptions
Exception Handlers
Exceptions are errors in a PL/SQL block that are raised during
execution of the block
-
5/20/2018 Oracle11g Slides
200/319
203
Error Type Reported By How Handled
Compile-time PL/SQL Compiler Interactively :compiler reports
errors, and you have to correct
them.
Run-time PL/SQL run-time engine Programmatically : exceptions are
raised and caught by exception
handlers.
execution of the block.
Exceptions can be raised implicitly by the oracle server or
explicitly by the application program.
An exception handler may be specified to handle the raised
exception. Exceptions are raised either at compile time or run time:
Exception Handlers
Types of exceptions:
-
5/20/2018 Oracle11g Slides
201/319
204
Named System exceptions
Named Programmer-defined exceptions
Unnamed System exceptions
Unnamed Programmer-defined exceptions
Exception Handlers
The Exception Section An English Like Translation
-
5/20/2018 Oracle11g Slides
202/319
205
EXCEPTION
WHEN NO_DATA_FOUND
THEN
executable_statements1;
If the NO_DATA_FOUND exception
was raised, then execute the first set
of statements.
WHEN payment_overdue
THEN
executable_statements2;
If the payment is overdue, then
execute the second set of statements
WHEN OTHERS
THEN
executable_statements3;
If any other exception is encountered,
then execute the third set of
statements
Exception Handlers
declare
declarations
-
5/20/2018 Oracle11g Slides
203/319
206
...... declarations ......
begin...... executable statements......
[exception
...... exception handlers......]
end;
exception
whenexception_name
then
end;
Exception Handlers
Named System Exceptions
-
5/20/2018 Oracle11g Slides
204/319
207
Are raised implicitly when its associated Oracle error occurs.
Are declared in the STANDARD package.
SQL> declare
v_emp emp%rowtype;
begin
SELECT * into v_emp FROM emp;
end;
Exception Handlers
Name of Exception
Oracle Error/SQLCODE
Description
-
5/20/2018 Oracle11g Slides
205/319
208
CURSOR_ALREADY_OPEN
ORA-6511 SQLCODE=-6511
You tried to OPEN a cursor that was already OPEN. You must CLOSE a
cursor before you try to OPEN or re-OPEN it.
DUP_VAL_ON_INDEX
ORA-00001 SQLCODE=-1
Your INSERT or UPDATE statement attempted to store duplicate values
in a column or columns in a row, which is restricted by a unique index.
INVALID_CURSOR
ORA-01001 SQLCODE=-1001
You made reference to a cursor that did not exist. This usually happens
when you try to FETCH FROM a cursor or CLOSE a cursor before that
cursor is OPENed.
INVALID_NUMBERORA-01722 SQLCODE=-1722
PL/SQL executes a SQL statement that cannot convert a character stringsuccessfully to a number. This exception is different FROM the
VALUE_ERROR exception, as it is raised only FROM within a SQL
statement.
LOGIN_DENIED
ORA-01017 SQLCODE=-1017
Your program tried to log onto the Oracle RDBMS with an invalid
username-password combination. This exception is usually encountered
when you embed PL/SQL in 3GL language.
NO_DATA_FOUNDORA-01403 SQLCODE=+100
This exception is raised in three different scenarios: (1) You executed aSELECT INTO statement(implicit cursor) that returned no rows. (2) You
referenced an uninitialized row in a local PL/SQL table. (3) You read past
end of file with UTL_FILE package.
Exception Handlers
NOT_LOGGED_ON
ORA-01012 SQLCODE=-1012
Your program tried to execute a call to the database (usually with a
DML statement) before it had logged into the Oracle RDBMS.
-
5/20/2018 Oracle11g Slides
206/319
209
PROGRAM_ERROR
ORA-06501 SQLCODE=-6501
PL/SQL encounters an internal problem. The message text usually also
tells you to ContactOracle Support.
STORAGE_ERROR
ORA-06500 SQLCODE=-6500
Your program ran out of memory or memory in some was corrupted.
TIMEOUT_ON_RESOURCEORA-00051 SQLCODE=-51
A timeout occurred in the RDBMS while waiting for a resource.
Exception Handlers
Name of Exception
Oracle Error/SQLCODE
Description
-
5/20/2018 Oracle11g Slides
207/319
210
TRANSACTION_BACKED_OUT
ORA-00061 SQLCODE=-61
The remote part of a transaction is rolled back, either with an
explicit ROLLBACK command or as a result of some otheraction
VALUE_ERROR
ORA-06502 SQLCODE=-6502
PL/SQL raises a VALUE_ERROR whenever it encounters an
error having to do with the conversion, truncation or invalid
constraining of numeric and character data. This is a very
general and common exception. If this same type of error is
encountered in a SQL DML statement within a PL/SQL block,
then the INVALID_NUMBER exception is raised.
ZERO_DIVIDE
ORA-01476 SQLCODE=-1476
Your program tried to divide by zero.
Exception Handlers
SQL> declare
name varchar2(30);
-
5/20/2018 Oracle11g Slides
208/319
211
name varchar2(30);
begin
SELECT emp_name into name FROM employee WHEREemp_code = &emp_code;
dbms_output.put_line(name);
exceptionwhenno_data_foundthen
dbms_output.put_line ('Such employee does not exists');
when othersthen
dbms_output.put_line (SQLERRM || ' '||SQLCODE);dbms_output.put_line ('Some other error');
end;
Exception Handlers
Named Programmer-Defined ExceptionsSQL> declare
-
5/20/2018 Oracle11g Slides
209/319
212
Q
acbalance number (6);neg_bal exception;
begin
SELECT balance into acbalance FROM accounts
WHERE balance declare
current_sal number;
-
5/20/2018 Oracle11g Slides
210/319
213
emp_id number;sal_null exception;
begin
emp_id:=&empno;
SELECT salary into current_sal FROM employee
WHERE emp_code=emp_id;if current_sal is null then
raise sal_null;
else
update employeeset salary = current_sal+1000
WHERE emp_code = emp_id;end if;
Exception Handlers
exception
when sal null then
-
5/20/2018 Oracle11g Slides
211/319
214
when sal_null then
dbms_output.put_line('Salary is missing');
end;
Exception Handlers
Unnamed System Exceptions
-
5/20/2018 Oracle11g Slides
212/319
215
Are standard Oracle server errors but, are not defined.Also known as non-predefined Oracle errors.
Can be trapped by explicitly declaring it first with the
PRAGMA EXCEPTION_INIT keyword.
Exception Handlers
declare
exception name exception;
-
5/20/2018 Oracle11g Slides
213/319
216
exception_name exception;
pragma exception_init(exception_name,error_code_literal);
begin
........... executable statements ...........
raise exception_name;exception
when exception_name then
........... executable statements ...........
end;
Exception Handlers
SQL> declare
e missing exception;
-
5/20/2018 Oracle11g Slides
214/319
217
e_missing exception;
pragma exception_init (e_missing,-1400);
begin
insert into new1(empno) values (null);
exceptionwhen e_missing then
dbms_output.put_line('ora-1400 occurred');
end;
Exception Handlers
Unnamed Programmer-Defined Exceptions
-
5/20/2018 Oracle11g Slides
215/319
218
raise_application_error(error_number, message[, {true | false}]);
The final type of exception is the unnamed programmer-defined exception.
This kind of exception occurs when you need to raise an
application specific error FROM within the server and
communicate this error back to the client applicationprocess.
The special procedure RAISE_APPLICATION_ERROR
lets us issue user-defined error messages FROM stored
subprograms
Exception Handlers
SQL> declare
current_sal number;
-
5/20/2018 Oracle11g Slides
216/319
219
emp_id number;begin
emp_id:=&empno;
SELECT salary into current_sal FROM employee WHEREemp_code=emp_id;
if current_sal is null then
raise_application_error(-20102,'salary is missing');
else
update employee set salary=current_sal+1000
WHERE emp_code=emp_id;end if;
end;
Module : Stored Procedures and Functions
Overview
-
5/20/2018 Oracle11g Slides
217/319
220
Understanding Stored Procedures
Creating Stored Procedures
Parameter modes
Understanding Stored Functions
Creating Stored Functions
Stored Procedures
Stored Procedures
-
5/20/2018 Oracle11g Slides
218/319
221
When a procedure is created, the Oracle engine automatically performsthe following steps
Compiles the procedure or function.
Stores the procedure or function in the database.
The Oracle engine performs the following steps to execute a procedureor function
Verifies the user access.
Verifies procedure or function validity.
Executes the procedure or function.
Stored Procedures
CREATE OR REPLACE PROCEDURE [ schema] procedurename
-
5/20/2018 Oracle11g Slides
219/319
222
(argument {IN, OUT, INOUT} datatype,.){IS ,AS}
variable declarations;
constant declarations;
BEGIN PL/SQL subprogram body;
EXCEPTION
Exception pl/sql block;
END;
Stored Procedures
Procedure parameter modes
-
5/20/2018 Oracle11g Slides
220/319
223
TheINparameter mode is used to pass values to the procedure when
invoked.
The OUTparameter mode is used to return a values to the caller of
the procedure.
The IN OUTparameter is used to pass initial values to the procedurewhen invoked and it also returns updated values to the caller.
Stored Procedures
SQL> create or replace procedure get_emp_data (
eno in number,
-
5/20/2018 Oracle11g Slides
221/319
224
ename out varchar2,esal out number)
as
cursor mycursor (eno number) is
SELECT emp_name, salary FROM employee
WHERE emp_code = eno;begin
open mycursor (eno);
fetch mycursor into ename, esal;
close mycursor;end;
Stored Procedures
SQL> create or replace procedure raise_salary (emp_id number,
increase number)
-
5/20/2018 Oracle11g Slides
222/319
225
ascurrent_salary number;
begin
SELECT salary into current_salary FROM employee
WHERE emp_code = emp_id;
if current_salary is null then
raise_application_error(-20101, 'salary is missing');
else
update employee set salary = current_salary +increase
WHERE emp_code = emp_id;end if;
end raise_salary;
Stored Procedures
SQL> create or replace procedure update_dept
(deptno in varchar2,
-
5/20/2018 Oracle11g Slides
223/319
226
( p
dname in out varchar2)
as
begin
update dept set dept_name=dname wheredept_code=deptno;
dbms_output.put_line(deptno ||' ' ||dname);
end update_dept;
Stored Functions
Stored Functions
Is similar to stored procedures except that a function returns
-
5/20/2018 Oracle11g Slides
224/319
227
only a single values.
SQL> create or replace function insert_dept (
dcode varchar2, dname varchar2)
return booleanas
begin
insert into dept values (dcode, dname);
return true;
exceptionwhen others then
return false;
end;
Stored Functions
SQL> declare
-
5/20/2018 Oracle11g Slides
225/319
228
dummy boolean;begin
dummy := insert_dept('XYZ', 'Dept XYZ');
end;
Stored Functions
SQL> create or replace function compute_tax
(empno number,
-
5/20/2018 Oracle11g Slides
226/319
229
( p ,
tax in out number)
return number
is
beginselect salary into tax from employee where
emp_code=empno;
tax := tax * .3;
return tax;end;
Stored Functions
SQL> declare
var1 number;
-
5/20/2018 Oracle11g Slides
227/319
230
;
var2 number;
begin
var1 := compute_tax(40,var2);
dbms_output.put_line('Tax value is: '||var2);end;
Module : Packages
Overview
Introduction to Packages
-
5/20/2018 Oracle11g Slides
228/319
231
g
Package Specification and Body
Creating Packages
Package Overloading
Altering and Dropping Packages
Advantages of Packages
Introduction to Packages
Packages
-
5/20/2018 Oracle11g Slides
229/319
232
Is a named PL/SQL block that groups logically relatedPL/SQL constructs such as:
Procedures
Functions
Cursors Variables and constants
Exception definitions
PL/SQL Types
Packages cannot be called, passed parameters, or nested.
Package Specification and Body
PACKAGE name IS -- specification (visible part)
-- public type and object declarations
-
5/20/2018 Oracle11g Slides
230/319
233
-- subprogram specificationsEND [name];
PACKAGE BODY name IS -- body (hidden part)-- private type and object declarations
-- subprogram bodies
[BEGIN
-- initialization statements]
END [name];
Creating Packages
SQL> create package emp_actions
as
-
5/20/2018 Oracle11g Slides
231/319
234
procedure hire_employee(empid number,
ename varchar2,
dept varchar2,
grade varchar2,
sal number
);
procedure fire_employee (empid number);
end emp_actions;
Creating PackagesSQL> create or replace package body emp_actions
as
procedure hire_employee
-
5/20/2018 Oracle11g Slides
232/319
235
(empid number,ename varchar2,
dept varchar2,
grade varchar2,
sal number)
is
begin
insert into employee(emp_code, emp_name,
dept_code, grade, salary)
values(empid,ename,dept,grade,sal);
end hire_employee;
Creating Packages
procedure fire_employee(empid number)
is
-
5/20/2018 Oracle11g Slides
233/319
236
begin
delete from employee where emp_code = empid;
end fire_employee;
end emp_actions;
Creating Packages
create or replace package emp_data as
procedure open_cv (generic_cv in out sys_refcursor, choice
-
5/20/2018 Oracle11g Slides
234/319
237
in number);
end emp_data;
create or replace package body emp_data as
procedure open_cv (generic_cv in out sys_refcursor, choice
in number) is
begin
if choice = 1 thenopen generic_cv for SELECT * FROM employee;
Creating Packages
elsif choice = 2 then
open generic_cv for SELECT * FROM dept;
-
5/20/2018 Oracle11g Slides
235/319
238
elsif choice = 3 thenopen generic_cv for SELECT * FROM salgrade;
end if;
endopen_cv;
end emp_data;
/
variable x refcursor;
exec emp_data.open_cv(:x,1);
Print x;
Creating Packages
Package which has functions for random number generation.
-
5/20/2018 Oracle11g Sl