working with oracle

55
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 10-1 David M. Kroenke’s Chapter Ten: Managing Databases with Oracle Database Processing: Fundamentals, Design, and Implementation

Upload: tranhieu5959

Post on 11-Dec-2015

216 views

Category:

Documents


0 download

DESCRIPTION

Working With Oracle

TRANSCRIPT

Page 1: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-1

David M. Kroenke’s

Chapter Ten:

Managing Databases with

Oracle

Database Processing:Fundamentals, Design, and Implementation

Page 2: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-2

Introduction

• Oracle is the world’s most popular DBMS - It is a powerful and robust DBMS that runs on many different operating systems

• Oracle DBMS engine available is several versions:– The Personal Edition of Oracle is available with this tex and

can also be downloaded from Oracle

• Example of Oracle products:– SQL*Plus: a utility for processing SQL and creating components

like stored procedures and triggers:• PL/SQL is a programming language that adds programming

constructs to the SQL language

– Oracle Developer (Forms & Reports Builder)

• Also third-party products - Quest Software’s TOAD

Page 3: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-3

View Ridge Gallery

• View Ridge Gallery is a small art gallery that has been in business for 30 years

• It sells contemporary European and North American fine art

• View Ridge has one owner, three salespeople, and two workers

• View Ridge owns all of the art that it sells; it holds no items on a consignment basis

Page 4: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-4

Application Requirements

• View Ridge application requirements:– Track customers and their artist interests– Record gallery's purchases– Record customers' art purchases– List the artists and works that have appeared

in the gallery– Report how fast an artist's works have sold

and at what margin– Show current inventory in a Web page

Page 5: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-5

View Ridge Gallery Database Design

Page 6: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-6

SQL*Plus

• Oracle SQL*Plus or the Oracle Enterprise Manager Console may be used to manage an Oracle database

• SQL*Plus is a text editor available in all Oracle• Except inside quotation marks of strings, Oracle

commands are case-insensitive• The semicolon (;) terminates a SQL statement• The right-leaning slash (/) executes SQL statement

stored in Oracle buffer• SQL*Plus can be used to:

– Enter SQL statements– Submit SQL files created by text editors, e.g., notepad, to Oracle

Page 7: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-7

SQL*Plus Buffer

• SQL*Plus keeps the current statements in a multi-line buffer without executing it

• LIST is used to see the contents of the buffer:– LIST {line_number} is used to change the current line

• CHANGE/astring/bstring/ is used to change the contents of the current line:– astring = the string you want to change– bstring = what you want to change it to

• Example: change/Table_Name/*/– ‘Table_Name’ is replaced with ‘*’

Page 8: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-8

SQL*Plus LIST Command

Page 9: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-9

SQL*Plus:Changing a Line in the Buffer

Page 10: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-10

Creating Tables

• Some of the SQL-92 CREATE TABLE statements we have studied need to be modified for Oracle– Oracle does not support a CASCADE UPDATE constraint– Money or currency is defined in Oracle using the NUMBER

data type

• Oracle sequences must be used for surrogate keys• The DESCRIBE or DESC command is used to view

table status

Page 11: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-11

Oracle Data Types

Page 12: Working With Oracle

10-12

Oracle CREATE TABLE Statements for the View Ridge Schema

Page 13: Working With Oracle

10-13

Oracle CREATE TABLE Statements for the View Ridge Schema

Page 14: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-14

Oracle Sequences

• A sequence is an object that generates a sequential series of unique numbers:

Create Sequence CustID Increment by 1 start with 1000;

• It is the best way to work with surrogate keys in Oracle• Two sequence methods:

– NextVal provides the next value in a sequence.– CurrVal provides the current value in a sequence.

• Using sequences does not guarantee valid surrogate key values because it is possible to have missing, duplicate, or wrong sequence value in the table

Page 15: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-15

Using Sequences

• Creating a sequence:CREATE SEQUENCE CustID INCREMENT BY 1 START WITH 1000;

• Entering data using a sequence:INSERT INTO CUSTOMER

(CustomerID, Name, AreaCode, PhoneNumber)

VALUES(

CustID.NextVal, 'Mary Jones', '350', '555–1234');

• Retrieving the row just inserted:SELECT *

FROM CUSTOMER

WHERE CustomerID = CustID.CurrVal;

Page 16: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-16

The DROP and ALTER Statements

• SQL DROP statements may be used to remove structures from the database– DROP TABLE Command:

• Any data in the MYTABLE table will be lost

DROP TABLE MyTable;

– DROP SEQUENCE Command:DROP SEQUENCE MySequence;

• SQL ALTER statements may be used to drop (add) a column:ALTER TABLE MYTABLE DROP COLUMN MyColumn;

ALTER TABLE MYTABLE ADD C1 NUMBER(4);

Page 17: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-17

The TO_DATE Function

• Oracle requires dates in a particular format.• Default format is DD-Mon-YY or DD-Mon-YYYY

– e.g., November 12, 2002 is ‘12-NOV-02’ or ‘12-NOV-2002’

• TO_DATE function may be used to identify the format: TO_DATE('11/12/2002', 'MM/DD/YYYY')

• 11/12/2002 is the date value

• MM/DD/YYYY is the pattern to be used when interpreting the date

• The TO_DATE function can be used with the INSERT and UPDATE statements to enter data:

INSERT INTO T1 VALUES(

100, TO_DATE ('01/05/02', 'DD/MM/YY');

Page 18: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-18

Creating Indexes

• Indexes are created to: – Enforce uniqueness on columns– Facilitate sorting– Enable fast retrieval by column values

• Good candidates for indexes are columns that are frequently used with equal conditions in WHERE clause or in a join

• Examples: CREATE INDEX CustNameIdx ON CUSTOMER(Name); CREATE UNIQUE INDEX WorkUniqueIndex ON WORK(Title, Copy, ArtistID);

Page 19: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-19

Restrictions On Column Modifications

• A column may be dropped at any time and all data will be lost

• A column may be added at any time as long as it is a NULL column

• To add a NOT NULL column:– Add a NULL column– Fill the new column in every row with data– Change its structure to NOT NULL:

ALTER TABLE T1 MODIFY C1 NOT NULL;

Page 20: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-20

Creating Views

• SQL-92 CREATE VIEW command can be used to create views in Oracle

• Unlike SQL-92, Oracle allows the ORDER BY clause in view definitions

• Oracle 9i and newer verions support the JOIN…ON syntax• Example:

CREATE VIEW CustomerInterests AS

SELECT C.Name as Customer, A.Name as Artist

FROM ART_CUSTOMER C JOIN CUSTOMER_ARTIST_INT I

ON C.CustomerID = I.CustomerID JOIN ARTIST A

ON I.ArtistID = A.ArtistID;

Page 21: Working With Oracle

10-21

Customer Interests View

Page 22: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-22

Application Logic

• Oracle database application can be processed using:– Programming language to invoke Oracle DBMS

commands– Stored procedures– The SQL*Plus Start (or @) command to invoke

database commands stored in .sql files– Triggers

Page 23: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-23

Oracle Errors

• Oracle error codes are cryptic

• For error explication:

http://otn.oracle.com/pls/db92/db92.error_search

Page 24: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-24

Stored Procedures

• A stored procedure is a PL/SQL or Java program stored within the database

• Stored procedures are programs that can: – Have parameters– Invoke other procedures and functions– Return values– Raise exceptions

• A stored procedure must be compiled and stored in the database

• The Execute or Exec command is used to invoke a stored procedure:Exec Customer_Insert ('Michael Bench', '203',

'555-2014', 'US');

Page 25: Working With Oracle

10-25

PL/SQL Block Structure[DECLARE

constants, variables, cursors, user-defined exceptions <name> <type><name> <columnName%TYPE>]

BEGINexecutable statementsassignment operator is :=

[EXCEPTIONactions to be taken when errors occur WHEN <exceptionName> THEN

. . . ;WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE( 'Exception occurred' ); DBMS_OUTPUT.PUT_LINE( 'Error code: ' || SQLCODE); DBMS_OUTPUT.PUT_LINE( SQLERRM );

ROLLBACK;]

END;

Page 26: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-26

IN signifies an input parameter;OUT signifies an output parameter;IN OUT is used for parameters with both functions

Variables are declared after the keyword AS

Page 27: Working With Oracle

10-27

A more complete stored procedure

• sp_VR_RecordSale.sql• The setup:

– update transaction set • salesprice = null, • customerid = null • where workid = 504;

– SQL> VARIABLE vReturn VarChar2(100);

• To execute:– SQL> exec Record_sale('Jack Jones', 'Chagall',

'Northwest by Night', '37/50', 70000, :vReturn);– SQL> print vReturn;

• success

Page 28: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-28

PL/SQL Exceptions• Standard exceptions:

– NO_DATA_FOUND– TOO_MANY_ROWS– INVALID_CURSOR

• Exception block: EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE( 'No data found' ); v_Return := 'Exception: No data found'; ROLLBACK; WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE( 'Too many rows found' ); v_Return := 'Exception: Too many rows found'; ROLLBACK; WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE( 'Exception occurred' ); DBMS_OUTPUT.PUT_LINE( 'Error code: ' || SQLCODE); DBMS_OUTPUT.PUT_LINE( SQLERRM ); v_Return := ( 'Exception: ' || SQLERRM ); ROLLBACK;END;

Page 29: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-29

User-defined Exceptions

DECLARE no_such_customer EXCEPTION; . .BEGIN SELECT count(*) INTO v_rows WHERE . . . IF v_rows < 1 THEN RAISE no_such_customer; . .EXCEPTION WHEN no_such_customer THEN DBMS_OUTPUT.PUT_LINE(‘No such customer in the database’); ROLLBACK; WHEN OTHERS THEN . . .END

Page 30: Working With Oracle

10-30

A note on Oracle’s table ‘DUAL’DUAL is a table owned by SYS that has only 1 row, and only 1 column called ‘dummy’. The single field contains the single character X.

To understand the SQL, note the following:SQL> select * from tab1;

ENO----------101102103

Now if you select an expression, say 1, from tab1SQL> select 1 from tab1;

1----------111

If you select an expression a+b from tab1SQL> select 'a+b' from tab1;

'A+---a+ba+ba+b

Since DUAL has only 1 row, we can convenientlyUse it to return single values:

SQL> select SYSDATE from DUAL;

SYSDATE---------08-APR-05

SQL> select 25000*.25 from DUAL;

25000*.25--------- 6250

SQL> select CustomerID.nextVal from DUAL;

NEXTVAL--------- 1020

Adapted from Indira Aramandla on http://forums1.itrc.hp.com/service/forums

Page 31: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-31

Triggers

• An Oracle trigger is a PL/SQL or Java procedures that is invoked when a specified database activity occurs

• Triggers can be used to: – Set default values– Enforce a Data Constraint– Update a view– Enforce referential integrity action– Handle exceptions

Page 32: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-32

Triggers

• Trigger types:– A command trigger will be fired once per SQL

command– A row trigger will be fired once for every row involved

in the processing of a SQL command:– There are three types of triggers: BEFORE, AFTER,

and INSTEAD OF• BEFORE and AFTER triggers are placed on tables while

INSTEAD OF triggers are placed on views• Each trigger can be fired on INSERT, UPDATE, or DELETE

commands

Page 33: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-33

This is a BEFORE trigger on INSERT on the table TRANSACTION.It is will set a default value on AskingPrice.

Note the “FOR EACH ROW” phrase; it makes this a row trigger.

Page 34: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-34

Triggers:Enforcing a Required Child Constraint

There is a Mandatory-Mandatory relationship between WORK and TRANSACTION:

Page 35: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-35

Triggers:Enforcing a Required Child Constraint

• The hard way using two triggers – this one enforces the required child:

Page 36: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-36

Triggers:Enforcing a Required Child Constraint

• The hard way using two triggers – this one deletes any duplicate transaction:

(In case the application added a record to TRANSACTION, as well as the after-insert-on-WORK trigger on the previous slide.)

Error: this should be an ‘after’ trigger.

Page 37: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-37

Triggers:Enforcing a Required Child Constraint

CREATE VIEW Work_Trans AS

SELECT Title, Description, Copy,ArtistID, DateAcquired, AcquisitionPrice

FROM WORK W JOIN TRANSACTION T

ON W.WorkID = T.WorkID;

A better way - Create the Work_Trans view:

Page 38: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-38

Triggers:Enforcing a Required Child Constraint

• A better way using one trigger – this one works with the Work_Trans view:

Page 39: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-39

The OracleData Dictionary

• Oracle maintains a data dictionary of metadata.• The metadata of the dictionary itself are stored

in the table DICT:SELECT Table_Name, Comments

FROM DICT

WHERE Table_Name LIKE ('%TABLES%');

• USER_TABLES contains information about user or system tables:

DESC USER_TABLES;

Page 40: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-40

Example Oracle Metadata

Page 41: Working With Oracle

10-41

Finding the text of a trigger

Page 42: Working With Oracle

10-42

Likewise for a stored procedure

Page 43: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-43

Transaction isolation problems

• Lost updates – Last one in, wins• Dirty read – T reads a changed record that

is not yet committed. (What if the change is rolled back?)

• Nonrepeatable read – T reads the same data a 2nd time, and finds changes due to the commitment of another transaction.

• Phantom read – upon re-read of a table, T finds rows that were not there before.

Page 44: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-44

Transaction Isolation Level

The more restrictive the isolation level, the lower the throughput.

Page 45: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-45

Concurrency Control

• Oracle processes database changes by maintaining a System Change Number (SCN)– SCN is a database-wide value that is incremented by Oracle

when database changes are made

• With SCN, SQL statements always read a consistent set of values; those that were committed at or before the time the statement was started

• Oracle only reads committed changes; it will never read dirty data

Page 46: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-46

Oracle Transaction Isolation

Page 47: Working With Oracle

10-47

Setting transaction isolation level in Oracle

• Oracle’s Multiversion Read Consistency (MVRC) scheme never locks for reads.– Reads never block for writes– Writes never wait for reads

• SET TRANSACTION ISOLATION LEVEL READ COMMITTED– The default setting – statement level consistency– Oracle waits for locked resources, and then retries– Dirty reads are impossible, but nonrepeatable reads and phantom reads

are possible.

• SET TRANSACTION ISOLATION LEVEL SERIALIZABLE– Transaction level consistency– Oracle waits for locked resource, and if blocking process commits,

statement fails with “Cannot Serialize” exception.• ORA-08177 can't serialize access for this transaction• Application must be prepared to handle the error

• SET TRANSACTION ISOLATION LEVEL READ ONLY– Transaction-level read consistency – reads will only see changes

committed before the transaction began.

Page 48: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-48

Oracle Security

• Oracle security components:– An ACCOUNT is a user account

– A PROFILE is a set of system resource maximums that are assigned to an account

– A SYSTEM PRIVILEGE is the right to perform a task

– A ROLE consists of groups of PRIVILEGEs and other ROLEs

Page 49: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-49

Account System Privileges

• Each ACCOUNT can be allocated many SYSTEM PRIVILEGEs and many ROLEs

• An ACCOUNT has all the PRIVILEGEs:– That have been assigned directly.– Of all of its ROLEs– Of all of its ROLEs that are inherited through ROLE connections

• A ROLE can have many SYSTEM PRIVILEGEs and it may also have a relationship to other ROLEs

• ROLEs simplify the administration of the database:– A set of privileges can be assigned to or removed from a ROLE

just once

Page 50: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-50

Account Authentication

• Accounts can be authenticated by:– Passwords– The host operating system

• Password management can be specified via PROFILEs

Page 51: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-51

Oracle Recovery Facilities

• Three file types for Oracle recovery: – Datafiles contain user and system data– ReDo log files contain logs of database changes:

• OnLine ReDo files are maintained on disk and contain the rollback segments from recent database changes

• Offline or Archive ReDo files are backups of the OnLine ReDo files

– Control files describe the name, contents, and locations of various files used by Oracle

Page 52: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-52

Oracle Recovery Facilities

• Oracle can operate in either ARCHIVELOG or NOARCHIVELOG mode:– If running in ARCHIVELOG mode, Oracle logs all

changes to the database– When the OnLine ReDo files fill up, they are copied to

the Archive ReDo files

• The Oracle Recovery Manager (RMAN) is a utility program used to create backups and to perform recovery.

Page 53: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-53

Types of Failure

• Oracle recovery techniques depend on the type of failure:– An application failure due to application logic errors– An instance failure occurs when Oracle itself fails due to an

operating system or computer hardware failure• Oracle can recover from application and instance failure

without using the archived log file– A media failure occurs when Oracle is unable to write to a

physical file because of a disk failure or corrupted files• The database is restored from a backup

Page 54: Working With Oracle

DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall

10-54

Oracle Backup Facilities

• Two kinds of backups:– A consistent backup: Database activity must be stopped and

all uncommitted changes have been removed from the datafiles• Cannot be done if the database supports 24/7 operations

– An inconsistent backup: Backup is made while Oracle is processing the database

• An inconsistent backup can be made consistent by processing an archive log file

Page 55: Working With Oracle

10-55

Oracle Misc.• Looking up errors:

http://otn.oracle.com/pls/db92/db92.error_search

• SQL*Plus guide:https://www-rohan.sdsu.edu/doc/oracle/server803/A53718_01/ch1.htm– set linesize xx– set pagesize xx– COLUMN <columnName> FORMAT <formatType>

• Null value conversionNVL( <column>, <value> )Select name, salary + NVL( Commission, 0) as “Total Salary” from employee;

• Printing in SQL*Plus1. Set ServerOutput On

2. DBMS_OUTPUT.PUT_LINE( ‘This will be printed’ );