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: raja-kumar

Post on 24-Nov-2015

27 views

Category:

Documents


1 download

DESCRIPTION

Oracle Commands

TRANSCRIPT

  • David M. KroenkesChapter Ten:Managing Databases withOracleDatabase Processing:Fundamentals, Design, and Implementation

  • IntroductionOracle is the worlds most popular DBMS - It is a powerful and robust DBMS that runs on many different operating systemsOracle DBMS engine available is several versions:The Personal Edition of Oracle is available with this tex and can also be downloaded from OracleExample 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 languageOracle Developer (Forms & Reports Builder)Also third-party products - Quest Softwares TOAD

  • View Ridge GalleryView Ridge Gallery is a small art gallery that has been in business for 30 yearsIt sells contemporary European and North American fine artView Ridge has one owner, three salespeople, and two workersView Ridge owns all of the art that it sells; it holds no items on a consignment basis

  • Application RequirementsView Ridge application requirements:Track customers and their artist interestsRecord gallery's purchasesRecord customers' art purchasesList the artists and works that have appeared in the galleryReport how fast an artist's works have sold and at what marginShow current inventory in a Web page

  • View Ridge Gallery Database Design

  • SQL*PlusOracle SQL*Plus or the Oracle Enterprise Manager Console may be used to manage an Oracle databaseSQL*Plus is a text editor available in all OracleExcept inside quotation marks of strings, Oracle commands are case-insensitiveThe semicolon (;) terminates a SQL statementThe right-leaning slash (/) executes SQL statement stored in Oracle bufferSQL*Plus can be used to:Enter SQL statementsSubmit SQL files created by text editors, e.g., notepad, to Oracle

  • SQL*Plus Buffer SQL*Plus keeps the current statements in a multi-line buffer without executing itLIST is used to see the contents of the buffer:LIST {line_number} is used to change the current lineCHANGE/astring/bstring/ is used to change the contents of the current line:astring = the string you want to changebstring = what you want to change it toExample: change/Table_Name/*/Table_Name is replaced with *

  • SQL*Plus LIST Command

  • SQL*Plus:Changing a Line in the Buffer

  • Creating TablesSome of the SQL-92 CREATE TABLE statements we have studied need to be modified for OracleOracle does not support a CASCADE UPDATE constraintMoney or currency is defined in Oracle using the NUMBER data typeOracle sequences must be used for surrogate keysThe DESCRIBE or DESC command is used to view table status

  • Oracle Data Types

  • Oracle CREATE TABLE Statements for the View Ridge Schema

  • Oracle CREATE TABLE Statements for the View Ridge Schema

  • 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 OracleTwo 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

  • Using SequencesCreating 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', '5551234');Retrieving the row just inserted:SELECT *FROM CUSTOMERWHERE CustomerID = CustID.CurrVal;

  • The DROP and ALTER Statements SQL DROP statements may be used to remove structures from the databaseDROP TABLE Command:Any data in the MYTABLE table will be lostDROP 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);

  • The TO_DATE FunctionOracle requires dates in a particular format.Default format is DD-Mon-YY or DD-Mon-YYYYe.g., November 12, 2002 is 12-NOV-02 or 12-NOV-2002TO_DATE function may be used to identify the format: TO_DATE('11/12/2002', 'MM/DD/YYYY')11/12/2002 is the date valueMM/DD/YYYY is the pattern to be used when interpreting the dateThe 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');

  • Creating IndexesIndexes are created to: Enforce uniqueness on columnsFacilitate sortingEnable fast retrieval by column valuesGood candidates for indexes are columns that are frequently used with equal conditions in WHERE clause or in a joinExamples: CREATE INDEX CustNameIdx ON CUSTOMER(Name); CREATE UNIQUE INDEX WorkUniqueIndex ON WORK(Title, Copy, ArtistID);

  • Restrictions On Column Modifications A column may be dropped at any time and all data will be lostA column may be added at any time as long as it is a NULL columnTo add a NOT NULL column:Add a NULL columnFill the new column in every row with dataChange its structure to NOT NULL: ALTER TABLE T1 MODIFY C1 NOT NULL;

  • Creating ViewsSQL-92 CREATE VIEW command can be used to create views in OracleUnlike SQL-92, Oracle allows the ORDER BY clause in view definitionsOracle 9i and newer verions support the JOINON syntaxExample: CREATE VIEW CustomerInterests ASSELECT C.Name as Customer, A.Name as ArtistFROM ART_CUSTOMER C JOIN CUSTOMER_ARTIST_INT ION C.CustomerID = I.CustomerID JOIN ARTIST AON I.ArtistID = A.ArtistID;

  • Customer Interests View

  • Application LogicOracle database application can be processed using:Programming language to invoke Oracle DBMS commandsStored proceduresThe SQL*Plus Start (or @) command to invoke database commands stored in .sql filesTriggers

  • Oracle ErrorsOracle error codes are crypticFor error explication:

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

  • Stored ProceduresA stored procedure is a PL/SQL or Java program stored within the databaseStored procedures are programs that can: Have parametersInvoke other procedures and functionsReturn valuesRaise exceptionsA stored procedure must be compiled and stored in the databaseThe Execute or Exec command is used to invoke a stored procedure:Exec Customer_Insert ('Michael Bench', '203', '555-2014', 'US');

  • PL/SQL Block Structure[DECLARE constants, variables, cursors, user-defined exceptions ]

    BEGINexecutable statementsassignment operator is :=

    [EXCEPTIONactions to be taken when errors occur WHEN THEN . . . ;WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE( 'Exception occurred' ); DBMS_OUTPUT.PUT_LINE( 'Error code: ' || SQLCODE); DBMS_OUTPUT.PUT_LINE( SQLERRM );ROLLBACK;]

    END;

  • IN signifies an input parameter;OUT signifies an output parameter;IN OUT is used for parameters with both functionsVariables are declared after the keyword AS

  • A more complete stored proceduresp_VR_RecordSale.sqlThe 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

  • PL/SQL ExceptionsStandard exceptions:NO_DATA_FOUNDTOO_MANY_ROWSINVALID_CURSORException 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;

  • User-defined ExceptionsDECLARE 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

  • A note on Oracles table DUALDUAL 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 ---------- 101 102 103 Now if you select an expression, say 1, from tab1 SQL> select 1 from tab1; 1 ---------- 1 1 1 If you select an expression a+b from tab1 SQL> select 'a+b' from tab1; 'A+ --- a+b a+b a+bSince 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

  • TriggersAn Oracle trigger is a PL/SQL or Java procedures that is invoked when a specified database activity occursTriggers can be used to: Set default valuesEnforce a Data ConstraintUpdate a viewEnforce referential integrity actionHandle exceptions

  • TriggersTrigger types:A command trigger will be fired once per SQL commandA 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 OFBEFORE and AFTER triggers are placed on tables while INSTEAD OF triggers are placed on viewsEach trigger can be fired on INSERT, UPDATE, or DELETE commands

  • 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.

  • Triggers:Enforcing a Required Child ConstraintThere is a Mandatory-Mandatory relationship between WORK and TRANSACTION:

  • Triggers:Enforcing a Required Child ConstraintThe hard way using two triggers this one enforces the required child:

  • Triggers:Enforcing a Required Child ConstraintThe 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.

  • Triggers:Enforcing a Required Child ConstraintCREATE VIEW Work_Trans ASSELECT Title, Description, Copy, ArtistID, DateAcquired, AcquisitionPriceFROMWORK W JOIN TRANSACTION TONW.WorkID = T.WorkID;A better way - Create the Work_Trans view:

  • Triggers:Enforcing a Required Child ConstraintA better way using one trigger this one works with the Work_Trans view:

  • The OracleData DictionaryOracle maintains a data dictionary of metadata.The metadata of the dictionary itself are stored in the table DICT:SELECT Table_Name, CommentsFROM DICTWHERE Table_Name LIKE ('%TABLES%');USER_TABLES contains information about user or system tables:DESC USER_TABLES;

  • Example Oracle Metadata

  • Finding the text of a trigger

  • Likewise for a stored procedure

  • Transaction isolation problemsLost updates Last one in, winsDirty 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.

  • Transaction Isolation LevelThe more restrictive the isolation level, the lower the throughput.

  • Concurrency ControlOracle 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 madeWith SCN, SQL statements always read a consistent set of values; those that were committed at or before the time the statement was startedOracle only reads committed changes; it will never read dirty data

  • Oracle Transaction Isolation

  • Setting transaction isolation level in OracleOracles Multiversion Read Consistency (MVRC) scheme never locks for reads.Reads never block for writesWrites never wait for readsSET TRANSACTION ISOLATION LEVEL READ COMMITTEDThe default setting statement level consistencyOracle waits for locked resources, and then retriesDirty reads are impossible, but nonrepeatable reads and phantom reads are possible.SET TRANSACTION ISOLATION LEVEL SERIALIZABLETransaction level consistencyOracle waits for locked resource, and if blocking process commits, statement fails with Cannot Serialize exception.ORA-08177 can't serialize access for this transactionApplication must be prepared to handle the errorSET TRANSACTION ISOLATION LEVEL READ ONLYTransaction-level read consistency reads will only see changes committed before the transaction began.

  • Oracle SecurityOracle security components:An ACCOUNT is a user accountA PROFILE is a set of system resource maximums that are assigned to an accountA SYSTEM PRIVILEGE is the right to perform a taskA ROLE consists of groups of PRIVILEGEs and other ROLEs

  • Account System PrivilegesEach ACCOUNT can be allocated many SYSTEM PRIVILEGEs and many ROLEsAn ACCOUNT has all the PRIVILEGEs:That have been assigned directly.Of all of its ROLEsOf all of its ROLEs that are inherited through ROLE connectionsA ROLE can have many SYSTEM PRIVILEGEs and it may also have a relationship to other ROLEsROLEs simplify the administration of the database:A set of privileges can be assigned to or removed from a ROLE just once

  • Account AuthenticationAccounts can be authenticated by:PasswordsThe host operating systemPassword management can be specified via PROFILEs

  • Oracle Recovery FacilitiesThree file types for Oracle recovery: Datafiles contain user and system dataReDo log files contain logs of database changes:OnLine ReDo files are maintained on disk and contain the rollback segments from recent database changesOffline or Archive ReDo files are backups of the OnLine ReDo filesControl files describe the name, contents, and locations of various files used by Oracle

  • Oracle Recovery FacilitiesOracle can operate in either ARCHIVELOG or NOARCHIVELOG mode:If running in ARCHIVELOG mode, Oracle logs all changes to the databaseWhen the OnLine ReDo files fill up, they are copied to the Archive ReDo filesThe Oracle Recovery Manager (RMAN) is a utility program used to create backups and to perform recovery.

  • Types of FailureOracle recovery techniques depend on the type of failure:An application failure due to application logic errorsAn instance failure occurs when Oracle itself fails due to an operating system or computer hardware failureOracle can recover from application and instance failure without using the archived log fileA media failure occurs when Oracle is unable to write to a physical file because of a disk failure or corrupted filesThe database is restored from a backup

  • Oracle Backup FacilitiesTwo kinds of backups:A consistent backup: Database activity must be stopped and all uncommitted changes have been removed from the datafilesCannot be done if the database supports 24/7 operationsAn inconsistent backup: Backup is made while Oracle is processing the databaseAn inconsistent backup can be made consistent by processing an archive log file

  • Oracle Misc.Looking up errors:http://otn.oracle.com/pls/db92/db92.error_searchSQL*Plus guide:https://www-rohan.sdsu.edu/doc/oracle/server803/A53718_01/ch1.htmset linesize xxset pagesize xxCOLUMN FORMAT Null value conversionNVL( , )Select name, salary + NVL( Commission, 0) as Total Salary from employee;Printing in SQL*PlusSet ServerOutput OnDBMS_OUTPUT.PUT_LINE( This will be printed );