SQL 31 69
SQL 31 69
3-30 Copyright © 2004, Oracle. All rights reserved. 3-32 Copyright © 2004, Oracle. All rights reserved.
Elements of the Date Format Model Elements of the Date Format Model
Element Result • Time elements format the time portion of the date:
YYYY Full year in numbers
HH24:MI:SS AM 15:45:32 PM
YEAR Year spelled out (in English)
MM Two-digit value for month • Add character strings by enclosing them in double
MONTH Full name of the month quotation marks:
MON Three-letter abbreviation of the month DD "of" MONTH 12 of OCTOBER
DY Three-letter abbreviation of the day of the
week • Number suffixes spell out numbers:
DAY Full name of the day of the week
ddspth fourteenth
DD Numeric day of the month
3-33 Copyright © 2004, Oracle. All rights reserved. 3-34 Copyright © 2004, Oracle. All rights reserved.
Using the TO_CHAR Function with Dates Using the TO_CHAR Function with Numbers
3-35 Copyright © 2004, Oracle. All rights reserved. 3-36 Copyright © 2004, Oracle. All rights reserved.
Using the TO_CHAR Function with Numbers Using the TO_NUMBER and TO_DATE
Functions
Current Year Specified Date RR Format YY Format To find employees hired prior to 1990, use the RR date
1995 27-OCT-95 1995 1995 format, which produces the same results whether the
1995 27-OCT-17 2017 1917
command is run in 1999 or now:
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095 SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')
FROM employees
If the specified two-digit year is: WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');
0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one
3-40 Copyright © 2004, Oracle. All rights reserved. 3-41 Copyright © 2004, Oracle. All rights reserved.
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
3-42 Copyright © 2004, Oracle. All rights reserved. 3-43 Copyright © 2004, Oracle. All rights reserved.
The following functions work with any data type and Converts a null value to an actual value:
pertain to using nulls: • Data types that can be used are date, character,
• NVL (expr1, expr2) and number.
• NVL2 (expr1, expr2, expr3) • Data types must match:
• NULLIF (expr1, expr2) – NVL(commission_pct,0)
• COALESCE (expr1, expr2, ..., exprn) – NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')
3-44 Copyright © 2004, Oracle. All rights reserved. 3-45 Copyright © 2004, Oracle. All rights reserved.
1 2 1 2
32
3-46 Copyright © 2004, Oracle. All rights reserved. 3-47 Copyright © 2004, Oracle. All rights reserved.
Using the NULLIF Function Using the COALESCE Function
1
SELECT first_name, LENGTH(first_name) "expr1", • The advantage of the COALESCE function over the
last_name, LENGTH(last_name) "expr2", 2 NVL function is that the COALESCE function can
NULLIF(LENGTH(first_name), LENGTH(last_name)) result 3
FROM employees; take multiple alternate values.
• If the first expression is not null, the COALESCE
function returns that expression; otherwise, it
does a COALESCE of the remaining expressions.
…
1 2 3
3-48 Copyright © 2004, Oracle. All rights reserved. 3-49 Copyright © 2004, Oracle. All rights reserved.
3-50 Copyright © 2004, Oracle. All rights reserved. 3-51 Copyright © 2004, Oracle. All rights reserved.
Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of
an IF-THEN-ELSE statement: an IF-THEN-ELSE statement:
SELECT last_name, job_id, salary,
CASE expr WHEN comparison_expr1 THEN return_expr1 CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
[WHEN comparison_expr2 THEN return_expr2 WHEN 'ST_CLERK' THEN 1.15*salary
WHEN comparison_exprn THEN return_exprn WHEN 'SA_REP' THEN 1.20*salary
ELSE else_expr] ELSE salary END "REVISED_SALARY"
END FROM employees;
3-52 Copyright © 2004, Oracle. All rights reserved. 3-53 Copyright © 2004, Oracle. All rights reserved.
Facilitates conditional inquiries by doing the work of a SELECT last_name, job_id, salary,
CASE expression or an IF-THEN-ELSE statement: DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
DECODE(col|expression, search1, result1 'SA_REP', 1.20*salary,
[, search2, result2,...,] salary)
[, default]) REVISED_SALARY
FROM employees;
33
3-54 Copyright © 2004, Oracle. All rights reserved. 3-55 Copyright © 2004, Oracle. All rights reserved.
Using the DECODE Function Summary
Display the applicable tax rate for each employee in In this lesson, you should have learned how to:
department 80: • Perform calculations on data using functions
SELECT last_name, salary, • Modify individual data items using functions
DECODE (TRUNC(salary/2000, 0),
0, 0.00, • Manipulate output for groups of rows using
1, 0.09, functions
2, 0.20, • Alter date formats for display using functions
3, 0.30,
4, 0.40, • Convert column data types using functions
5, 0.42, • Use NVL functions
6, 0.44,
0.45) TAX_RATE • Use IF-THEN-ELSE logic
FROM employees
WHERE department_id = 80;
3-56 Copyright © 2004, Oracle. All rights reserved. 3-57 Copyright © 2004, Oracle. All rights reserved.
3-58 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.
4-2 Copyright © 2004, Oracle. All rights reserved. 4-3 Copyright © 2004, Oracle. All rights reserved.
34
4-4 Copyright © 2004, Oracle. All rights reserved. 4-5 Copyright © 2004, Oracle. All rights reserved.
Using the AVG and SUM Functions Using the MIN and MAX Functions
You can use AVG and SUM for numeric data. You can use MIN and MAX for numeric, character, and
date data types.
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary) SELECT MIN(hire_date), MAX(hire_date)
FROM employees FROM employees;
WHERE job_id LIKE '%REP%';
4-6 Copyright © 2004, Oracle. All rights reserved. 4-7 Copyright © 2004, Oracle. All rights reserved.
COUNT(*) returns the number of rows in a table: • COUNT(DISTINCT expr) returns the number of
SELECT COUNT(*) distinct non-null values of the expr.
1 FROM employees • To display the number of distinct department
WHERE department_id = 50;
values in the EMPLOYEES table:
SELECT COUNT(DISTINCT department_id)
FROM employees;
COUNT(expr) returns the number of rows with non-
null values for the expr:
SELECT COUNT(commission_pct)
2 FROM employees
WHERE department_id = 80;
4-8 Copyright © 2004, Oracle. All rights reserved. 4-9 Copyright © 2004, Oracle. All rights reserved.
3500 Average
salary in
The NVL function forces group functions to include EMPLOYEES
null values: 6400 table for each
SELECT AVG(NVL(commission_pct, 0)) department
2 FROM employees; 10033
4-10 Copyright © 2004, Oracle. All rights reserved. 4-11 Copyright © 2004, Oracle. All rights reserved.
SELECT column, group_function(column) All columns in the SELECT list that are not in group
FROM table functions must be in the GROUP BY clause.
[WHERE condition]
[GROUP BY group_by_expression] SELECT department_id, AVG(salary)
[ORDER BY column]; FROM employees
GROUP BY department_id ;
You can divide rows in a table into smaller groups by
using the GROUP BY clause.
35
4-12 Copyright © 2004, Oracle. All rights reserved. 4-13 Copyright © 2004, Oracle. All rights reserved.
Using the GROUP BY Clause Grouping by More Than One Column
4-14 Copyright © 2004, Oracle. All rights reserved. 4-15 Copyright © 2004, Oracle. All rights reserved.
SELECT department_id dept_id, job_id, SUM(salary) Any column or expression in the SELECT list that is not
FROM employees an aggregate function must be in the GROUP BY clause:
GROUP BY department_id, job_id ;
SELECT department_id, COUNT(last_name)
FROM employees;
4-16 Copyright © 2004, Oracle. All rights reserved. 4-17 Copyright © 2004, Oracle. All rights reserved.
4-18 Copyright © 2004, Oracle. All rights reserved. 4-19 Copyright © 2004, Oracle. All rights reserved.
When you use the HAVING clause, the Oracle server SELECT department_id, MAX(salary)
restricts groups as follows: FROM employees
GROUP BY department_id
1. Rows are grouped. HAVING MAX(salary)>10000 ;
2. The group function is applied.
3. Groups matching the HAVING clause are
displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
36
4-20 Copyright © 2004, Oracle. All rights reserved. 4-21 Copyright © 2004, Oracle. All rights reserved.
Using the HAVING Clause Nesting Group Functions
4-22 Copyright © 2004, Oracle. All rights reserved. 4-23 Copyright © 2004, Oracle. All rights reserved.
In this lesson, you should have learned how to: This practice covers the following topics:
• Use the group functions COUNT, MAX, MIN, and AVG • Writing queries that use the group functions
• Write queries that use the GROUP BY clause • Grouping by rows to achieve more than one result
• Write queries that use the HAVING clause • Restricting groups by using the HAVING clause
4-24 Copyright © 2004, Oracle. All rights reserved. 4-25 Copyright © 2004, Oracle. All rights reserved.
Objectives
Copyright © 2004, Oracle. All rights reserved. 5-2 Copyright © 2004, Oracle. All rights reserved.
EMPLOYEES DEPARTMENTS Joins that are compliant with the SQL:1999 standard
include the following:
• Cross joins
…
• Natural joins
• USING clause
• Full (or two-sided) outer joins
• Arbitrary join conditions for outer joins
37
5-3 Copyright © 2004, Oracle. All rights reserved. 5-4 Copyright © 2004, Oracle. All rights reserved.
Joining Tables Using SQL:1999 Syntax Creating Natural Joins
Use a join to query data from more than one table: • The NATURAL JOIN clause is based on all columns
in the two tables that have the same name.
SELECT table1.column, table2.column
FROM table1 • It selects rows from the two tables that have equal
[NATURAL JOIN table2] | values in all matched columns.
[JOIN table2 USING (column_name)] |
• If the columns having the same names have
[JOIN table2
ON (table1.column_name = table2.column_name)]| different data types, an error is returned.
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)]|
[CROSS JOIN table2];
5-5 Copyright © 2004, Oracle. All rights reserved. 5-6 Copyright © 2004, Oracle. All rights reserved.
Select e.empno,e.Ename,d.Dname,e.Deptno
From EMP e,DEPT d
Where e.deptno=d.deptno;
5-7 Copyright © 2004, Oracle. All rights reserved. 5-8 Copyright © 2004, Oracle. All rights reserved.
• If several columns have the same names but the EMPLOYEES DEPARTMENTS
data types do not match, the NATURAL JOIN clause
can be modified with the USING clause to specify
the columns that should be used for an equijoin.
• Use the USING clause to match only one column
when more than one column matches.
• Do not use a table name or alias in the referenced
columns.
• The NATURAL JOIN and USING clauses are
mutually exclusive.
… …
Foreign key Primary key
5-9 Copyright © 2004, Oracle. All rights reserved. 5-10 Copyright © 2004, Oracle. All rights reserved.
SELECT employees.employee_id, employees.last_name, • Use table prefixes to qualify column names that
departments.location_id, department_id are in multiple tables.
FROM employees JOIN departments
USING (department_id) ; • Use table prefixes to improve performance.
• Use column aliases to distinguish columns that
have identical names but reside in different tables.
• Do not use aliases on columns that are identified
in the USING clause and listed elsewhere in the
SQL statement.
38
5-11 Copyright © 2004, Oracle. All rights reserved. 5-12 Copyright © 2004, Oracle. All rights reserved.
Using Table Aliases Creating Joins with the ON Clause
• Use table aliases to simplify queries. • The join condition for the natural join is basically
• Use table aliases to improve performance. an equijoin of all columns with the same name.
• Use the ON clause to specify arbitrary conditions
SELECT e.employee_id, e.last_name,
d.location_id, department_id or specify columns to join.
FROM employees e JOIN departments d • The join condition is separated from other search
USING (department_id) ; conditions.
• The ON clause makes code easy to understand.
5-13 Copyright © 2004, Oracle. All rights reserved. 5-14 Copyright © 2004, Oracle. All rights reserved.
… …
5-15 Copyright © 2004, Oracle. All rights reserved. 5-16 Copyright © 2004, Oracle. All rights reserved.
5-17 Copyright © 2004, Oracle. All rights reserved. 5-18 Copyright © 2004, Oracle. All rights reserved.
…
… There are no employees in
department 190.
5-21 Copyright © 2004, Oracle. All rights reserved. 5-22 Copyright © 2004, Oracle. All rights reserved.
• In SQL:1999, the join of two tables returning only SELECT e.last_name, e.department_id, d.department_name
matched rows is called an inner join. FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
• A join between two tables that returns the results
of the inner join as well as the unmatched rows
from the left (or right) tables is called a left (or
right) outer join. …
• A join between two tables that returns the results
of an inner join as well as the results of a left and
right join is a full outer join.
5-23 Copyright © 2004, Oracle. All rights reserved. 5-24 Copyright © 2004, Oracle. All rights reserved.
…
…
5-25 Copyright © 2004, Oracle. All rights reserved. 5-26 Copyright © 2004, Oracle. All rights reserved.
Cartesian product:
20 x 8 = 160 rows
… 40
5-27 Copyright © 2004, Oracle. All rights reserved. 5-28 Copyright © 2004, Oracle. All rights reserved.
Creating Cross Joins Summary
• The CROSS JOIN clause produces the cross- In this lesson, you should have learned how to use
product of two tables. joins to display data from multiple tables by using:
• This is also called a Cartesian product between • Equijoins
the two tables. • Non-equijoins
SELECT last_name, department_name
• Outer joins
FROM employees • Self-joins
CROSS JOIN departments ;
• Cross joins
• Natural joins
• Full (or two-sided) outer joins
5-29 Copyright © 2004, Oracle. All rights reserved. 5-30 Copyright © 2004, Oracle. All rights reserved.
Practice 5: Overview
5-31 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.
After completing this lesson, you should be able to do Who has a salary greater than Abel’s?
the following:
• Define subqueries Main query:
6-2 Copyright © 2004, Oracle. All rights reserved. 6-3 Copyright © 2004, Oracle. All rights reserved.
41
6-4 Copyright © 2004, Oracle. All rights reserved. 6-5 Copyright © 2004, Oracle. All rights reserved.
Guidelines for Using Subqueries Types of Subqueries
6-6 Copyright © 2004, Oracle. All rights reserved. 6-7 Copyright © 2004, Oracle. All rights reserved.
6-8 Copyright © 2004, Oracle. All rights reserved. 6-9 Copyright © 2004, Oracle. All rights reserved.
SELECT last_name, job_id, salary • The Oracle server executes subqueries first.
FROM employees 2500
• The Oracle server returns results into the HAVING
WHERE salary =
(SELECT MIN(salary) clause of the main query.
FROM employees);
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id 2500
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
6-10 Copyright © 2004, Oracle. All rights reserved. 6-11 Copyright © 2004, Oracle. All rights reserved.
What Is Wrong with This Statement? Will This Statement Return Rows?
no rows selected
ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row Subquery returns no values.
42
6-12 Copyright © 2004, Oracle. All rights reserved. 6-13 Copyright © 2004, Oracle. All rights reserved.
Multiple-Row Subqueries Using the ANY Operator
in Multiple-Row Subqueries
• Return more than one row SELECT employee_id, last_name, job_id, salary
FROM employees
•
9000, 6000, 4200
Use multiple-row comparison operators
WHERE salary < ANY
(SELECT salary
Operator Meaning FROM employees
IN Equal to any member in the list WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
ANY (OR) Compare value to each value returned by the
subquery
ALL Compare value to every value returned by
the subquery
…
6-14 Copyright © 2004, Oracle. All rights reserved. 6-15 Copyright © 2004, Oracle. All rights reserved.
6-16 Copyright © 2004, Oracle. All rights reserved. 6-17 Copyright © 2004, Oracle. All rights reserved.
In this lesson, you should have learned how to: This practice covers the following topics:
• Identify when a subquery can help solve a • Creating subqueries to query values based on
question unknown criteria
• Write subqueries when a query is based on • Using subqueries to find out which values exist in
unknown values one set of data and not in another
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
6-18 Copyright © 2004, Oracle. All rights reserved. 6-19 Copyright © 2004, Oracle. All rights reserved.
Objectives
43
Copyright © 2004, Oracle. All rights reserved. 7-2 Copyright © 2004, Oracle. All rights reserved.
Set Operators Tables Used in This Lesson
A B A B
A B
MINUS
7-3 Copyright © 2004, Oracle. All rights reserved. 7-4 Copyright © 2004, Oracle. All rights reserved.
…
…
The UNION operator returns results from both
queries after eliminating duplications.
7-5 Copyright © 2004, Oracle. All rights reserved. 7-6 Copyright © 2004, Oracle. All rights reserved.
7-7 Copyright © 2004, Oracle. All rights reserved. 7-8 Copyright © 2004, Oracle. All rights reserved.
…
The MINUS operator returns rows in the first query
that are not present in the second query.
7-11 Copyright © 2004, Oracle. All rights reserved. 7-12 Copyright © 2004, Oracle. All rights reserved.
• The expressions in the SELECT lists must match in • Duplicate rows are automatically eliminated
number and data type. except in UNION ALL.
• Parentheses can be used to alter the sequence of • Column names from the first query appear in the
execution. result.
• The ORDER BY clause: • The output is sorted in ascending order by default
– Can appear only at the very end of the statement except in UNION ALL.
– Will accept the column name, aliases from the first
SELECT statement, or the positional notation
7-13 Copyright © 2004, Oracle. All rights reserved. 7-14 Copyright © 2004, Oracle. All rights reserved.
…
…
7-15 Copyright © 2004, Oracle. All rights reserved. 7-16 Copyright © 2004, Oracle. All rights reserved.
45
7-17 Copyright © 2004, Oracle. All rights reserved. 7-18 Copyright © 2004, Oracle. All rights reserved.
Practice 7: Overview
46
Enhanced Guide to Oracle 10g Forms
Application with a graphical user
Chapter 5: interface that looks like a paper
form
Introduction To Form Builder
Used to insert, update, delete and
1 2
3 4
11 12
13 14
48
15 16
Form Components Form Components
Canvas Window
Surface that displays form items Name Canvas
Default Canvas type is Content Canvas.
Other types are Tab Canvas, Stacked, … Cash Block of items
Block
Check
Credit Card
20
49
23 24
Configuring Form Windows Modifying Form Properties
Every form object has a Property
Palette that allows you to configure
form properties
Property
Nodes Property List
Window Minimize/ Window
Title Maximize buttons size
25 26
27 28
33 34
Master-Detail
Relationship Example Master-Detail Relationship
You can check that the Master Detail relationship is
correct using two methods:
Method2
Run The form
Click ENTER QUERY
Go to the primary key in the Master Block(Department_ID) in
Departments.
Write an existing number (20 for example)
Click EXECUTE QUERY
You will see that data is retrieved in the two blocks.
35 36
37 38
45 46
new page.
Block order
Name: Item name.
Item Type: Used to convert to list, image, radio, check, …
convert into a list. Conceal Data: If yes, data will be displayed like ***. Used for
Password fields.
Click F4 for properties. Iconic: If yes, button will be iconic.
Icon Filename
Set Item Type to List Item
Previous Navigation Item: Which item leads to this item when
using keyboard.
Use Elements In List to insert the Next Navigation Item: Which is the next item when using
values that will be displayed and will keyboard.
Required: If yes, you need to insert a value in the field before
be inserted into the database.
leaving it.
Enabled: If no, You can not select the item by the mouse.
List of Values: Is there a list of value related to the item.
Hint: to display a hint
Display Hint Automatically: yes or no
Tooltip: to display a tooltip
Tooltip
Hint
17
18 19
55
20 21
Check Boxes Check Box Example
Used to represent fields that can
have one of two values
Check box caption is interpreted as
TRUE or FALSE
If checked, caption is true
If cleared, caption is false
22 23
2. Open the item Property Palette, and Value when Checked: data
26 27
30 31
DEFAULT&SMARTBAR to C:\Module5.mmx
Run this form and you will see the new menu.
34 35
57
36 37
Format Mask Examples Report Builder
Value Format Mask Result Used to facilitate creating professional
7945 999 ### reports based on the database.
7945 9999$ 7945$ From Developer Suite Report
7945 99”-”99 79-45 Builder.
34.28 99.9 34.3
Select ‘Use the Report Wizard’.
34.28 99.999 34.280
SYSDATE Day-MON-YY Friday-NOV-06
38 39
40 41
42 43
58
44 45
Report Builder Report Builder
Move all fields to the right
46 47
48 49
50 51
54 55
56 57
58 59
62 63
66
61
About PL/SQL
PL/SQL
Declaring Variables PL/SQL is an extension to SQL with design
features of programming languages.
Writing Executable Statements
It includes SQL statements plus additional
Interacting with the Oracle Server instructions.
Writing Control Structures
Cursors
Handling Exceptions
Examples
Guidelines
Follow naming conventions. v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
Initialize variables designated as NOT NULL v_total_sal NUMBER(9,2) := 0;
and CONSTANT. v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
Declare at most one identifier per line. v_valid BOOLEAN NOT NULL := TRUE;
62
Manipulating Data Using
PL/SQL
Make changes to database tables by using
DML commands:
Writing Executable
INSERT
UPDATE INSERT
Statements DELETE
UPDATE
DELETE
Naming Conventions
DECLARE
orderdate ord.orderdate%TYPE;
shipdate ord.shipdate%TYPE;
ordid ord.ordid%TYPE := 601;
BEGIN
SELECT orderdate, shipdate
INTO
FROM
orderdate, shipdate
ord
Writing Control
Structures
WHERE ordid = ordid;
END;
SQL> /
DECLARE
*
ERROR at line 1:
ORA-01422: exact fetch returns more than
requested
number of rows 63
ORA-06512: at line 6
Controlling PL/SQL Flow IF Statements
of Execution Syntax
IF condition THEN
statements;
You can change the logical flow of [ELSIF condition THEN
statements;]
statements using conditional IF [ELSE
statements;]
statements and loop control structures. END IF;
64
DECLARE
v_grade NUMBER(3); FOR Loop
v_status Varchar2(30);
BEGIN Syntax
v_grade :=10;
FOR counter in [REVERSE]
loop lower_bound..upper_bound LOOP
if v_grade>80 then statement1;
v_status :='Excellent'; statement2;
elsif v_grade>60 then . . .
END LOOP;
v_status :='Good';
else Use a FOR loop to shortcut the test for the
v_status :='Bad'; number of iterations.
end if;
Do not declare the counter; it is declared
insert into stgrades values(v_grade, v_status);
v_grade := v_grade+10; implicitly.
exit when v_grade>99;
end loop;
END;
/
65
%ROWTYPE Example
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
d dept%ROWTYPE;
BEGIN
SELECT deptno,dname,loc INTO d FROM dept Cursors
WHERE deptno=10;
DBMS_OUTPUT.PUT_LINE(d.dname);
END;
/
ACCOUNTING
SQL Cursor
A cursor is a private SQL work area. Database Server Memory
There are two types of cursors:
Implicit cursors
Cursor
Explicit cursors
The Oracle Server uses implicit cursors to Number of Parsed
parse and execute your SQL statements. rows
processed
command
statement
Context Area
Explicit cursors are explicitly declared by the CID CALLID CNAME CCREDIT
66
About Cursors Explicit Cursor Functions
Yes Cursor
DECLARE OPEN FETCH EMPTY? CLOSE Fetch a row from the cursor.
Pointer
• Create a • Identify • Load the • Test for • Release Cursor
named the active current existing the active Continue until empty.
SQL area set row into rows set
variables • Return to Pointer
FETCH if
Cursor
rows
found Close the cursor.
67
Fetching Data from the Cursor Fetching Data from the Cursor
Syntax
Examples
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
FETCH emp_cursor INTO v_empno, v_ename;
Retrieve the current row values into variables. ...
OPEN defined_cursor;
Include the same number of variables. LOOP
FETCH defined_cursor INTO defined_variables
Match each variable to correspond to the EXIT WHEN ...;
...
columns positionally. -- Process the retrieved data
...
Test to see if the cursor contains rows. END;
Reopen the cursor, if required. %FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
Do not attempt to fetch data from a cursor complement of %NOTFOUND
once it has been closed. %ROWCOUNT Number Evaluates to the total number of
rows returned so far
68
Explicit Cursor %ISOPEN Example Explicit Cursor %ROWCOUNT
Cont. Example
LOOP SQL> DECLARE
v_name emp.ename%TYPE;
FETCH my_cursor INTO v_num,v_name; r NUMBER;
EXIT WHEN my_cursor%NOTFOUND; c NUMBER:=1;
END LOOP; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900;
CLOSE my_cursor; BEGIN
OPEN my_cursor;
r:=my_cursor%ISOPEN; LOOP
IF r THEN FETCH my_cursor INTO v_name;
DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); EXIT WHEN my_cursor%NOTFOUND;
r:=my_cursor%ROWCOUNT;
ELSE DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r);
DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); c:=c+1;
END IF; END LOOP;
END; CLOSE my_cursor;
END;
/ /
The Cursor is opened after the open statement After fetch number 1 ROWCOUNT has the value 1
The Cursor is closed after the close statement After fetch number 2 ROWCOUNT has the value 2
Exception
is trapped END;
69
ORA-01722 INVALID_NUMBER Invalid numeric conversion
ORA-06502 VALUE_ERROR Error in arithmetic or numeric function operation