• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Chinabankppt
 

Chinabankppt

on

  • 2,396 views

PL SQL topics

PL SQL topics

Statistics

Views

Total Views
2,396
Views on SlideShare
2,395
Embed Views
1

Actions

Likes
5
Downloads
0
Comments
0

1 Embed 1

http://www.docseek.net 1

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Chinabankppt Chinabankppt Presentation Transcript

  • Introduction
  • Lesson Objectives
    • After completing this lesson, you should be able to do the following:
      • List the features of Oracle10 g
      • Discuss the theoretical and physical aspects of a relational database
      • Describe the Oracle implementation of RDBMS and ORDBMS
      • Understand the goals of the course
  • Retrieving Data Using the SQL SELECT Statement
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • List the capabilities of SQL SELECT statements
      • Execute a basic SELECT statement
      • Differentiate between SQL statements and i SQL*Plus commands
  • Capabilities of SQL SELECT Statements Selection Projection Table 1 Table 2 Table 1 Table 1 Join
  • Basic SELECT Statement
      • SELECT identifies the columns to be displayed.
      • FROM identifies the table containing those columns.
    SELECT *|{[DISTINCT] column | expression [ alias ],...} FROM table;
  • Selecting All Columns SELECT * FROM departments;
  • Selecting Specific Columns SELECT department_id, location_id FROM departments;
  • Writing SQL Statements
      • SQL statements are not case sensitive.
      • SQL statements can be on one or more lines.
      • Keywords cannot be abbreviated or split across lines.
      • Clauses are usually placed on separate lines.
      • Indents are used to enhance readability.
      • In i SQL*Plus, SQL statements can optionally be terminated by a semicolon (;). Semicolons are required if you execute multiple SQL statements.
      • In SQL*Plus, you are required to end each SQL statement with a semicolon (;).
  • Column Heading Defaults
      • i SQL*Plus:
        • Default heading alignment: Center
        • Default heading display: Uppercase
      • SQL*Plus:
        • Character and Date column headings are left-aligned
        • Number column headings are right-aligned
        • Default heading display: Uppercase
  • Arithmetic Expressions
    • Create expressions with number and date data by using arithmetic operators.
    Multiply * Divide
      • /
    Subtract
      • -
    Add
      • +
    Description Operator
  • Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM employees; …
  • Operator Precedence SELECT last_name, salary, 12*salary+100 FROM employees; SELECT last_name, salary, 12*(salary+100)‏ FROM employees; 1 2 … …
  • Defining a Null Value
      • A null is a value that is unavailable, unassigned, unknown, or inapplicable.
      • A null is not the same as a zero or a blank space.
    SELECT last_name, job_id, salary, commission_pct FROM employees; … …
  • Null Values in Arithmetic Expressions
    • Arithmetic expressions containing a null value evaluate to null.
    SELECT last_name, 12*salary*commission_pct FROM employees; … …
  • Defining a Column Alias
    • A column alias:
      • Renames a column heading
      • Is useful with calculations
      • Immediately follows the column name (There can also be the optional AS keyword between the column name and alias.)‏
      • Requires double quotation marks if it contains spaces or special characters or if it is case sensitive
  • Using Column Aliases SELECT last_name "Name" , salary*12 "Annual Salary" FROM employees; SELECT last_name AS name, commission_pct comm FROM employees; … …
  • Concatenation Operator
    • A concatenation operator:
      • Links columns or character strings to other columns
      • Is represented by two vertical bars (||)‏
      • Creates a resultant column that is a character expression
    SELECT last_name||job_id AS "Employees" FROM employees; …
  • Literal Character Strings
      • A literal is a character, a number, or a date that is included in the SELECT statement.
      • Date and character literal values must be enclosed by single quotation marks.
      • Each character string is output once for each row returned.
  • Using Literal Character Strings … SELECT last_name ||' is a '||job_id AS "Employee Details" FROM employees;
  • Alternative Quote ( q ) Operator
      • Specify your own quotation mark delimiter
      • Choose any delimiter
      • Increase readability and usability
    SELECT department_name || q'[, it's assigned Manager Id: ]' || manager_id AS "Department and Manager" FROM departments; …
  • Duplicate Rows
    • The default display of queries is all rows, including duplicate rows.
    SELECT department_id FROM employees; SELECT DISTINCT department_id FROM employees; … 1 2 …
  • Displaying Table Structure
    • Use the i SQL*Plus DESCRIBE command to display the structure of a table:
    DESC[RIBE] tablename
  • Displaying Table Structure DESCRIBE employees
  • Summary
    • In this lesson, you should have learned how to:
      • Write a SELECT statement that:
        • Returns all rows and columns from a table
        • Returns specified columns from a table
        • Uses column aliases to display more descriptive column headings
      • Use the i SQL*Plus environment to write, save, and execute SQL statements and i SQL*Plus commands
    SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table;
  • Restricting and Sorting Data
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Limit the rows that are retrieved by a query
      • Sort the rows that are retrieved by a query
      • Use ampersand substitution in i SQL*Plus to restrict and sort output at run time
  • Limiting Rows Using a Selection “ retrieve all employees in department 90” EMPLOYEES …
  • Limiting the Rows That Are Selected
      • Restrict the rows that are returned by using the WHERE clause:
      • The WHERE clause follows the FROM clause.
    SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table [WHERE condition(s) ];
  • Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ;
  • Character Strings and Dates
      • Character strings and date values are enclosed in single quotation marks.
      • Character values are case sensitive, and date values are format sensitive.
      • The default date format is DD-MON-RR.
    SELECT last_name, job_id, department_id FROM employees WHERE last_name = 'Whalen' ;
  • Comparison Conditions Not equal to
      • <>
    Between two values (inclusive)‏ BETWEEN ...AND... Match any of a list of values IN(set)‏ Match a character pattern LIKE Is a null value IS NULL Less than
      • <
    Less than or equal to
      • <=
    Greater than or equal to >= Greater than
      • >
    Equal to
      • =
    Meaning Operator
  • Using Comparison Conditions SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
  • Using the BETWEEN Condition
    • Use the BETWEEN condition to display rows based on a range of values:
    SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500 ; Lower limit Upper limit
  • Using the IN Condition
    • Use the IN membership condition to test for values in a list:
    SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN (100, 101, 201) ;
  • Using the LIKE Condition
      • Use the LIKE condition to perform wildcard searches of valid search string values.
      • Search conditions can contain either literal characters or numbers:
        • % denotes zero or many characters.
        • _ denotes one character.
    SELECT first_name FROM employees WHERE first_name LIKE 'S%' ;
      • You can combine pattern-matching characters:
      • You can use the ESCAPE identifier to search for the actual % and _ symbols.
    Using the LIKE Condition SELECT last_name FROM employees WHERE last_name LIKE '_o%' ;
  • Using the NULL Conditions
    • Test for nulls with the IS NULL operator.
    SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
  • Logical Conditions Returns TRUE if the following condition is false NOT Returns TRUE if either component condition is true
      • OR
    Returns TRUE if both component conditions are true
      • AND
    Meaning Operator
  • Using the AND Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 AND job_id LIKE '%MAN%' ; AND requires both conditions to be true:
  • Using the OR Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 OR job_id LIKE '%MAN%' ;
      • OR requires either condition to be true:
  • Using the NOT Operator SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
  • Rules of Precedence You can use parentheses to override rules of precedence. Not equal to
      • 6
    NOT logical condition
      • 7
    AND logical condition
      • 8
    OR logical condition
      • 9
    IS [NOT] NULL , LIKE , [NOT] IN
      • 4
    [NOT] BETWEEN
      • 5
    Comparison conditions
      • 3
    Concatenation operator
      • 2
    Arithmetic operators
      • 1
    Meaning Operator
  • Rules of Precedence SELECT last_name, job_id, salary FROM employees WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000; SELECT last_name, job_id, salary FROM employees WHERE ( job_id = 'SA_REP' OR job_id = 'AD_PRES' )‏ AND salary > 15000; 1 2
  • Using the ORDER BY Clause
      • Sort retrieved rows with the ORDER BY clause:
        • ASC : ascending order, default
        • DESC : descending order
      • The ORDER BY clause comes last in the SELECT statement:
    SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date ; …
  • Sorting
      • Sorting in descending order:
      • Sorting by column alias:
      • Sorting by multiple columns:
    SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC ; 1 SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY annsal ; 2 SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC; 3
  • Summary
    • In this lesson, you should have learned how to:
      • Use the WHERE clause to restrict rows of output:
        • Use the comparison conditions
        • Use the BETWEEN , IN , LIKE , and NULL conditions
        • Apply the logical AND , OR , and NOT operators
      • Use the ORDER BY clause to sort rows of output:
      • Use ampersand substitution in i SQL*Plus to restrict and sort output at run time
    SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table [WHERE condition(s) ] [ORDER BY { column, expr, alias } [ASC|DESC]] ;
  • Displaying Data from Multiple Tables
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Write SELECT statements to access data from more than one table using equijoins and nonequijoins
      • Join a table to itself by using a self-join
      • View data that generally does not meet a join condition by using outer joins
      • Generate a Cartesian product of all rows from two or more tables
  • Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
  • Types of Joins
    • 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
  • Joining Tables Using SQL:1999 Syntax
    • Use a join to query data from more than one table:
    SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2 ] | [JOIN table2 USING ( column_name )] | [JOIN table2 ON ( table1.column_name = table2.column_name )]| [LEFT|RIGHT|FULL OUTER JOIN table2 ON ( table1.column_name = table2.column_name )]| [CROSS JOIN table2 ];
  • Creating Natural Joins
      • The NATURAL JOIN clause is based on all columns in the two tables that have the same name.
      • It selects rows from the two tables that have equal values in all matched columns.
      • If the columns having the same names have different data types, an error is returned.
  • Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ;
  • Creating Joins with the USING Clause
      • If several columns have the same names but the 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.
  • Joining Column Names EMPLOYEES DEPARTMENTS Foreign key Primary key … …
  • Retrieving Records with the USING Clause SELECT employees.employee_id, employees.last_name, departments.location_id, department_id FROM employees JOIN departments USING (department_id) ; …
  • Qualifying Ambiguous Column Names
      • Use table prefixes to qualify column names that are in multiple tables.
      • 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.
  • Using Table Aliases
      • Use table aliases to simplify queries.
      • Use table aliases to improve performance.
    SELECT e.employee_id, e.last_name, d.location_id, department_id FROM employees e JOIN departments d USING (department_id) ;
  • Creating Joins with the ON Clause
      • The join condition for the natural join is basically an equijoin of all columns with the same name.
      • Use the ON clause to specify arbitrary conditions or specify columns to join.
      • The join condition is separated from other search conditions.
      • The ON clause makes code easy to understand.
  • Retrieving Records with the ON Clause SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id); …
  • Self-Joins Using the ON Clause MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … …
  • Self-Joins Using the ON Clause SELECT e.last_name emp, m.last_name mgr FROM employees e JOIN employees m ON (e.manager_id = m.employee_id); …
  • Applying Additional Conditions to a Join SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id) AND e.manager_id = 149 ;
  • Creating Three-Way Joins with the ON Clause SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; …
  • Nonequijoins EMPLOYEES JOB_GRADES Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADES table. …
  • Retrieving Records with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal; …
  • Outer Joins EMPLOYEES DEPARTMENTS There are no employees in department 190. …
  • INNER Versus OUTER Joins
      • In SQL:1999, the join of two tables returning only matched rows is called an inner join.
      • 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.
  • LEFT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • RIGHT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
  • Cartesian Products
      • A Cartesian product is formed when:
        • A join condition is omitted
        • A join condition is invalid
        • All rows in the first table are joined to all rows in the second table
      • To avoid a Cartesian product, always include a valid join condition.
  • Generating a Cartesian Product Cartesian product: 20 x 8 = 160 rows EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … …
  • Creating Cross Joins
      • The CROSS JOIN clause produces the cross-product of two tables.
      • This is also called a Cartesian product between the two tables.
    SELECT last_name, department_name FROM employees CROSS JOIN departments ; …
  • Summary
    • In this lesson, you should have learned how to use joins to display data from multiple tables by using:
      • Equijoins
      • Nonequijoins
      • Outer joins
      • Self-joins
      • Cross joins
      • Natural joins
      • Full (or two-sided) outer joins
  • Manipulating Data
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Describe each data manipulation language (DML) statement
      • Insert rows into a table
      • Update rows in a table
      • Delete rows from a table
      • Control transactions
  • Data Manipulation Language
      • A DML statement is executed when you:
        • Add new rows to a table
        • Modify existing rows in a table
        • Remove existing rows from a table
      • A transaction consists of a collection of DML statements that form a logical unit of work.
  • Adding a New Row to a Table DEPARTMENTS New row Insert new row into the DEPARTMENTS table
  • INSERT Statement Syntax
      • Add new rows to a table by using the INSERT statement:
      • With this syntax, only one row is inserted at a time.
    INSERT INTO table [( column [ , column... ])] VALUES (value [ , value... ]);
  • Inserting New Rows
      • Insert a new row containing values for each column.
      • List values in the default order of the columns in the table.
      • Optionally, list the columns in the INSERT clause.
      • Enclose character and date values in single quotation marks.
    INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); 1 row created.
  • Inserting Rows with Null Values
      • Implicit method: Omit the column from the column list.
    INSERT INTO departments VALUES (100, 'Finance', NULL, NULL); 1 row created. INSERT INTO departments (department_id, department_name ) VALUES (30, 'Purchasing'); 1 row created.
    • Explicit method: Specify the NULL keyword in the VALUES clause.
  • Inserting Special Values
    • The SYSDATE function records the current date and time.
    INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) VALUES (113, 'Louis', 'Popp', 'LPOPP', '515.124.4567', SYSDATE, 'AC_ACCOUNT', 6900, NULL, 205, 100); 1 row created.
      • Add a new employee.
      • Verify your addition.
    Inserting Specific Date Values INSERT INTO employees VALUES (114, 'Den', 'Raphealy', 'DRAPHEAL', '515.127.4561', TO_DATE('FEB 3, 1999', 'MON DD, YYYY'), 'AC_ACCOUNT', 11000, NULL, 100, 30); 1 row created.
  • Copying Rows from Another Table
      • Write your INSERT statement with a subquery:
      • Do not use the VALUES clause.
      • Match the number of columns in the INSERT clause to those in the subquery.
    INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE job_id LIKE '%REP%'; 4 rows created.
  • Changing Data in a Table EMPLOYEES Update rows in the EMPLOYEES table:
      • Modify existing rows with the UPDATE statement:
      • Update more than one row at a time (if required).
    UPDATE Statement Syntax UPDATE table SET column = value [, column = value, ... ] [WHERE condition ];
      • Specific row or rows are modified if you specify the WHERE clause:
      • All rows in the table are modified if you omit the WHERE clause:
    Updating Rows in a Table UPDATE employees SET department_id = 70 WHERE employee_id = 113; 1 row updated. UPDATE copy_emp SET department_id = 110; 22 rows updated.
  • Removing a Row from a Table Delete a row from the DEPARTMENTS table: DEPARTMENTS
  • DELETE Statement
    • You can remove existing rows from a table by using the DELETE statement:
    DELETE [FROM] table [WHERE condition ];
  • Deleting Rows from a Table
      • Specific rows are deleted if you specify the WHERE clause:
      • All rows in the table are deleted if you omit the WHERE clause:
    DELETE FROM departments WHERE department_name = 'Finance'; 1 row deleted. DELETE FROM copy_emp; 22 rows deleted.
  • Database Transactions
    • A database transaction consists of one of the following:
      • DML statements that constitute one consistent change to the data
      • One DDL statement
      • One data control language (DCL) statement
  • Database Transactions
      • Begin when the first DML SQL statement is executed
      • End with one of the following events:
        • A COMMIT or ROLLBACK statement is issued.
        • A DDL or DCL statement executes (automatic commit).
        • The user exits i SQL*Plus.
        • The system crashes.
  • Advantages of COMMIT and ROLLBACK Statements
    • With COMMIT and ROLLBACK statements, you can:
      • Ensure data consistency
      • Preview data changes before making changes permanent
      • Group logically related operations
  • Controlling Transactions SAVEPOINT B SAVEPOINT A DELETE INSERT UPDATE INSERT COMMIT Time Transaction ROLLBACK to SAVEPOINT B ROLLBACK to SAVEPOINT A ROLLBACK
  • Rolling Back Changes to a Marker
      • Create a marker in a current transaction by using the SAVEPOINT statement.
      • Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.
    UPDATE... SAVEPOINT update_done; Savepoint created. INSERT... ROLLBACK TO update_done; Rollback complete.
  • Implicit Transaction Processing
      • An automatic commit occurs under the following circumstances:
        • DDL statement is issued
        • DCL statement is issued
        • Normal exit from i SQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements
      • An automatic rollback occurs under an abnormal termination of i SQL*Plus or a system failure.
  •  
  • State of the Data Before COMMIT or ROLLBACK
      • The previous state of the data can be recovered.
      • The current user can review the results of the DML operations by using the SELECT statement.
      • Other users cannot view the results of the DML statements by the current user.
      • The affected rows are locked ; other users cannot change the data in the affected rows.
  • State of the Data After COMMIT
      • Data changes are made permanent in the database.
      • The previous state of the data is permanently lost.
      • All users can view the results.
      • Locks on the affected rows are released; those rows are available for other users to manipulate.
      • All savepoints are erased.
  • Committing Data
      • Make the changes:
      • Commit the changes:
    COMMIT; Commit complete. DELETE FROM employees WHERE employee_id = 99999; 1 row deleted. INSERT INTO departments VALUES (290, 'Corporate Tax', NULL, 1700); 1 row created.
  • State of the Data After ROLLBACK
    • Discard all pending changes by using the ROLLBACK statement:
      • Data changes are undone.
      • Previous state of the data is restored.
      • Locks on the affected rows are released.
    DELETE FROM copy_emp; 20 rows deleted. ROLLBACK ; Rollback complete.
  • State of the Data After ROLLBACK DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE id = 100; 1 row deleted. SELECT * FROM test WHERE id = 100; No rows selected. COMMIT; Commit complete.
  • Statement-Level Rollback
      • If a single DML statement fails during execution, only that statement is rolled back.
      • The Oracle server implements an implicit savepoint.
      • All other changes are retained.
      • The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement.
  • Summary
    • In this lesson, you should have learned how to use the following statements:
    Adds a new row to the table INSERT Modifies existing rows in the table UPDATE Removes existing rows from the table DELETE Makes all pending changes permanent COMMIT Discards all pending data changes ROLLBACK Is used to roll back to the savepoint marker SAVEPOINT Description Function
  • Using DDL Statements to Create and Manage Tables
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Categorize the main database objects
      • Review the table structure
      • List the data types that are available for columns
      • Create a simple table
      • Explain how constraints are created at the time of table creation
      • Describe how schema objects work
  • Database Objects Logically represents subsets of data from one or more tables View Generates numeric values Sequence Basic unit of storage; composed of rows Table Gives alternative names to objects Synonym Improves the performance of some queries Index Description Object
  • Naming Rules
    • Table names and column names:
      • Must begin with a letter
      • Must be 1–30 characters long
      • Must contain only A–Z, a–z, 0–9, _, $, and #
      • Must not duplicate the name of another object owned by the same user
      • Must not be an Oracle server – reserved word
      • You must have:
        • CREATE TABLE privilege
        • A storage area
      • You specify:
        • Table name
        • Column name, column data type, and column size
    CREATE TABLE Statement CREATE TABLE [ schema .] table ( column datatype [DEFAULT expr ][, ...]);
  • Referencing Another User’s Tables
      • Tables belonging to other users are not in the user’s schema.
      • You should use the owner’s name as a prefix to those tables.
    USERB USERA SELECT * FROM userB.employees; SELECT * FROM userA.employees;
      • Specify a default value for a column during an insert.
      • Literal values, expressions, or SQL functions are legal values.
      • Another column’s name or a pseudocolumn are illegal values.
      • The default data type must match the column data type.
    DEFAULT Option ... hire_date DATE DEFAULT SYSDATE, ... CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT SYSDATE ); Table created.
  • Creating Tables
      • Create the table.
      • Confirm table creation.
    DESCRIBE dept CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE ); Table created.
  • Data Types Raw binary data RAW and LONG RAW Binary data (up to 4 GB) BLOB Binary data stored in an external file (up to 4 GB) BFILE Date and time values DATE Variable-length character data (up to 2 GB) LONG Character data (up to 4 GB) CLOB A base-64 number system representing the unique address of a row in its table ROWID Fixed-length character data CHAR( size ) Variable-length numeric data NUMBER( p , s) Variable-length character data VARCHAR2( size ) Description Data Type
  •  
  • Datetime Data Types
    • You can use several datetime data types:
    Stored as an interval of years and months INTERVAL YEAR TO MONTH Stored as an interval of days, hours, minutes, and seconds INTERVAL DAY TO SECOND Date with fractional seconds TIMESTAMP Description Data Type
  • Datetime Data Types
      • The TIMESTAMP data type is an extension of the DATE data type.
      • It stores the year, month, and day of the DATE data type plus hour, minute, and second values as well as the fractional second value.
      • You can optionally specify the time zone.
    TIMESTAMP[(fractional_seconds_precision)] TIMESTAMP[(fractional_seconds_precision)] WITH TIME ZONE TIMESTAMP[(fractional_seconds_precision)] WITH LOCAL TIME ZONE
  •  
  • Datetime Data Types
      • The INTERVAL YEAR TO MONTH data type stores a period of time using the YEAR and MONTH datetime fields:
      • The INTERVAL DAY TO SECOND data type stores a period of time in terms of days, hours, minutes, and seconds:
    INTERVAL YEAR [(year_precision)] TO MONTH INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]
  •  
  • INTERVAL DAY TO SECOND Data Type
    • INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and seconds.
    INTERVAL '4 5:12:10.222' DAY TO SECOND(3) Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second. INTERVAL '4 5:12' DAY TO MINUTE Indicates 4 days, 5 hours and 12 minutes. INTERVAL '400 5' DAY(3) TO HOUR Indicates 400 days 5 hours. INTERVAL '11:12:10.2222222' HOUR TO SECOND(7) indicates 11 hours, 12 minutes, and 10.2222222 seconds.
  • Including Constraints
      • Constraints enforce rules at the table level.
      • Constraints prevent the deletion of a table if there are dependencies.
      • The following constraint types are valid:
        • NOT NULL
        • UNIQUE
        • PRIMARY KEY
        • FOREIGN KEY
        • CHECK
  • Constraint Guidelines
      • You can name a constraint, or the Oracle server generates a name by using the SYS_C n format.
      • Create a constraint at either of the following times:
        • At the same time as the table is created
        • After the table has been created
      • Define a constraint at the column or table level.
      • View a constraint in the data dictionary.
      • Syntax:
      • Column-level constraint:
      • Table-level constraint:
    Defining Constraints CREATE TABLE [ schema .] table ( column datatype [DEFAULT expr ] [ column_constraint ], ... [ table_constraint ][,...] ); column,... [CONSTRAINT constraint_name ] constraint_type ( column , ...), column [CONSTRAINT constraint_name ] constraint_type ,
  • Defining Constraints
      • Column-level constraint:
      • Table-level constraint:
    CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...); CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID) ); 1 2
  • NOT NULL Constraint
    • Ensures that null values are not permitted for the column:
    NOT NULL constraint (No row can contain a null value for this column.) Absence of NOT NULL constraint (Any row can contain a null value for this column.) NOT NULL constraint …
  • UNIQUE Constraint EMPLOYEES UNIQUE constraint INSERT INTO Not allowed: already exists Allowed …
  • UNIQUE Constraint
    • Defined at either the table level or the column level:
    CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... CONSTRAINT emp_email_uk UNIQUE(email));
  • PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed (50 already exists) …
  • FOREIGN KEY Constraint DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …
  • FOREIGN KEY Constraint
    • Defined at either the table level or the column level:
    CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
  • FOREIGN KEY Constraint: Keywords
      • FOREIGN KEY : Defines the column in the child table at the table-constraint level
      • REFERENCES : Identifies the table and column in the parent table
      • ON DELETE CASCADE : Deletes the dependent rows in the child table when a row in the parent table is deleted
      • ON DELETE SET NULL : Converts dependent foreign key values to null
  • CHECK Constraint
      • Defines a condition that each row must satisfy
      • The following expressions are not allowed:
        • References to CURRVAL , NEXTVAL , LEVEL , and ROWNUM pseudocolumns
        • Calls to SYSDATE , UID , USER , and USERENV functions
        • Queries that refer to other values in other rows
    ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
  • CREATE TABLE : Example CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id));
  • Violating Constraints
    • Department 55 does not exist.
    UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found UPDATE employees SET department_id = 55 WHERE department_id = 110;
  • Violating Constraints
    • You cannot delete a row that contains a primary key that is used as a foreign key in another table.
    DELETE FROM departments WHERE department_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
  • Creating a Table by Using a Subquery
      • Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option.
      • Match the number of specified columns to the number of subquery columns.
      • Define columns with column names and default values.
    CREATE TABLE table [( column , column ...)] AS subquery;
  • Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; Table created. DESCRIBE dept80
  • ALTER TABLE Statement
    • Use the ALTER TABLE statement to:
      • Add a new column
      • Modify an existing column
      • Define a default value for the new column
      • Drop a column
  • Dropping a Table
      • All data and structure in the table are deleted.
      • Any pending transactions are committed.
      • All indexes are dropped.
      • All constraints are dropped.
      • You cannot roll back the DROP TABLE statement.
    DROP TABLE dept80; Table dropped.
  • Summary
    • In this lesson, you should have learned how to use the CREATE TABLE statement to create a table and include constraints.
      • Categorize the main database objects
      • Review the table structure
      • List the data types that are available for columns
      • Create a simple table
      • Explain how constraints are created at the time of table creation
      • Describe how schema objects work
  • Introduction to PL/SQL
  • Lesson Objectives
    • After completing this lesson, you should be able to do the following:
      • Explain the need for PL/SQL
      • Explain the benefits of PL/SQL
      • Identify the different types of PL/SQL blocks
      • Use i SQL*Plus as a development environment for PL/SQL
      • Output messages in PL/SQL
  • What Is PL/SQL?
    • PL/SQL:
      • Stands for Procedural Language extension to SQL
      • Is Oracle Corporation’s standard data access language for relational databases
      • Seamlessly integrates procedural constructs with SQL
  • About PL/SQL
    • PL/SQL:
      • Provides a block structure for executable units of code. Maintenance of code is made easier with such a well-defined structure.
      • Provides procedural constructs such as:
        • Variables, constants, and types
        • Control structures such as conditional statements and loops
        • Reusable program units that are written once and executed many times
  • PL/SQL Environment PL/SQL Engine Oracle Database Server SQL Statement Executor Procedural Statement Executor procedural SQL PL/SQL Block
  • Benefits of PL/SQL SQL IF...THEN SQL ELSE SQL END IF; SQL
      • Integration of procedural constructs with SQL
      • Improved performance
    SQL 1 SQL 2 …
  • Benefits of PL/SQL
      • Modularized program development
      • Integration with Oracle tools
      • Portability
      • Exception handling
  • Benefits of PL/SQL
  • PL/SQL Block Structure
    • DECLARE (Optional)
      • Variables, cursors, user-defined exceptions
    • BEGIN (Mandatory)
      • - SQL statements
      • - PL/SQL statements
    • EXCEPTION (Optional)
      • Actions to perform when errors occur
    • END ; (Mandatory)
  • PL/SQL Block Structure
  • Block Types
    • Anonymous Procedure Function
    [DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS BEGIN --statements [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
  • Block Types
  • Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs Object types
  • Program Constructs
  • Create an Anonymous Block
    • Type the anonymous block in the i SQL*Plus workspace:
  • Execute an Anonymous Block
    • Click the Execute button to execute the anonymous block:
    PLSQL procedure successfully completed.
  • Test the Output of a PL/SQL Block
      • Enable output in i SQL*Plus with the command SET SERVEROUTPUT ON
      • Use a predefined Oracle package and its procedure:
        • DBMS_OUTPUT.PUT_LINE
    SET SERVEROUTPUT ON … DBMS_OUTPUT.PUT_LINE( ' The First Name of the Employee is ' || f_name); …
  • Summary
    • In this lesson, you should have learned how to:
      • Integrate SQL statements with PL/SQL program constructs
      • Identify the benefits of PL/SQL
      • Differentiate different PL/SQL block types
      • Use i SQL*Plus as the programming environment for PL/SQL
      • Output messages in PL/SQL
  • Declaring PL/SQL Variables
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Identify valid and invalid identifiers
      • List the uses of variables
      • Declare and initialize variables
      • List and describe various data types
      • Identify the benefits of using %TYPE attribute
      • Declare, use, and print bind variables
  • Use of Variables
    • Variables can be used for:
      • Temporary storage of data
      • Manipulation of stored values
      • Reusability
    SELECT first_name, department_id INTO emp_fname, emp_deptno FROM … emp_fname emp_deptno Jennifer 10
  • Identifiers
    • Identifiers are used for:
      • Naming a variable
      • Providing a convention for variable names:
        • Must start with a letter
        • Can include letters or numbers
        • Can include special characters such as dollar sign, underscore, and pound sign
        • Must limit the length to 30 characters
        • Must not be reserved words
  • Handling Variables in PL/SQL
    • Variables are:
      • Declared and initialized in the declarative section
      • Used and assigned new values in the executable section
      • Passed as parameters to PL/SQL subprograms
      • Used to hold the output of a PL/SQL subprogram
  • Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ]; DECLARE emp_hiredate DATE; emp_deptno NUMBER(2) NOT NULL := 10; location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
  • Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); Myname := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20):= 'John'; BEGIN Myname := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / 1 2
  • Delimiters in String Literals SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '||event); event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '||event); END; /
  • Types of Variables
      • PL/SQL variables:
        • Scalar
        • Composite
        • Reference
        • Large objects (LOB)
      • Non-PL/SQL variables: Bind variables
  • Types of Variables TRUE 25-JAN-01 Atlanta 256120.08 The soul of the lazy man desires, and has nothing; but the soul of the diligent shall be made rich.
  • Guidelines for Declaring and Initializing PL/SQL Variables
      • Follow naming conventions.
      • Use meaningful names for variables.
      • Initialize variables designated as NOT NULL and CONSTANT .
      • Initialize variables with the assignment operator (:=) or the DEFAULT keyword:
      • Declare one identifier per line for better readability and code maintenance.
    Myname VARCHAR2(20):='John'; Myname VARCHAR2(20) DEFAULT 'John';
  • Guidelines for Declaring PL/SQL Variables
      • Avoid using column names as identifiers.
    DECLARE employee_id NUMBER(6); BEGIN SELECT employee_id INTO employee_id FROM employees WHERE last_name = 'Kochhar'; END; /
      • Use the NOT NULL constraint when the variable must hold a value.
  • Scalar Data Types
      • Hold a single value
      • Have no internal components
    Atlanta TRUE 25-JAN-01 256120.08 The soul of the lazy man desires, and has nothing; but the soul of the diligent shall be made rich.
  • Base Scalar Data Types
      • CHAR [(maximum_length)]
      • VARCHAR2 (maximum_length)
      • LONG
      • LONG RAW
      • NUMBER [(precision, scale)]
      • BINARY_INTEGER
      • PLS_INTEGER
      • BOOLEAN
      • BINARY_FLOAT
      • BINARY_DOUBLE
  •  
  • Base Scalar Data Types
      • DATE
      • TIMESTAMP
      • TIMESTAMP WITH TIME ZONE
      • TIMESTAMP WITH LOCAL TIME ZONE
      • INTERVAL YEAR TO MONTH
      • INTERVAL DAY TO SECOND
  •  
  • BINARY_FLOAT and BINARY_DOUBLE
      • Represent floating point numbers in IEEE (Institute of Electrical and Electronics Engineers) 754 format
      • Offer better interoperability and operational speed
      • Store values beyond the values that the data type NUMBER can store
      • Offer benefits of closed arithmetic operations and transparent rounding
  • BINARY_FLOAT and BINARY_DOUBLE
  • Declaring Scalar Variables
    • Examples:
    DECLARE emp_job VARCHAR2(9); count_loop BINARY_INTEGER := 0; dept_total_sal NUMBER(9,2) := 0; orderdate DATE := SYSDATE + 7; c_tax_rate CONSTANT NUMBER(3,2) := 8.25; valid BOOLEAN NOT NULL := TRUE; ...
  • The %TYPE Attribute
    • The %TYPE attribute
      • Is used to declare a variable according to:
        • A database column definition
        • Another declared variable
      • Is prefixed with:
        • The database table and column
        • The name of the declared variable
  • The %TYPE Attribute
  • Declaring Variables with the %TYPE Attribute
    • Syntax:
    • Examples:
    ... emp_lname employees.last_name%TYPE; balance NUMBER(7,2); min_balance balance%TYPE := 1000; ... identifier table.column_name%TYPE;
  • Declaring Boolean Variables
      • Only the values TRUE , FALSE , and NULL can be assigned to a Boolean variable.
      • Conditional expressions use logical operators AND , OR , and unary operator NOT to check the variable values.
      • The variables always yield TRUE , FALSE , or NULL .
      • Arithmetic, character, and date expressions can be used to return a Boolean value.
  • Bind Variables
    • Bind variables are:
      • Created in the environment
      • Also called host variables
      • Created with the VARIABLE keyword
      • Used in SQL statements and PL/SQL blocks
      • Accessed even after the PL/SQL block is executed
      • Referenced with a preceding colon
  •  
  • Printing Bind Variables
    • Example:
    VARIABLE emp_salary NUMBER BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178; END; / PRINT emp_salary SELECT first_name, last_name FROM employees WHERE salary=:emp_salary;
  • Printing Bind Variables
    • Example:
    VARIABLE emp_salary NUMBER SET AUTOPRINT ON BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178; END; /
  • Substitution Variables
      • Are used to get user input at run time
      • Are referenced within a PL/SQL block with a preceding ampersand
      • Are used to avoid hard coding values that can be obtained at run time
    VARIABLE emp_salary NUMBER SET AUTOPRINT ON DECLARE empno NUMBER(6):=&empno; BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno; END; /
  • Substitution Variables 1 2 3
  • Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid employee number: ' SET AUTOPRINT ON DECLARE empno NUMBER(6):= &empno; BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno; END; /
  • Using DEFINE for User Variable
    • Example:
    SET VERIFY OFF DEFINE lname= Urman DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname FROM employees WHERE last_name='&lname'; END; /
  • Composite Data Types TRUE 23-DEC-98 ATLANTA 1 5000 2 2345 3 12 4 3456 1 SMITH 2 JONES 3 NANCY 4 TIM PL/SQL table structure PL/SQL table structure PLS_INTEGER VARCHAR2 PLS_INTEGER NUMBER
  • LOB Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
  • Summary
    • In this lesson, you should have learned how to:
      • Identify valid and invalid identifiers
      • Declare variables in the declarative section of a PL/SQL block
      • Initialize variables and utilize them in the executable section
      • Differentiate between scalar and composite data types
      • Use the %TYPE attribute
      • Make use of bind variables
  • Interacting with the Oracle Server
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Decide which SQL statements can be directly included in a PL/SQL executable block
      • Manipulate data with DML statements in PL/SQL
      • Use transaction control statements in PL/SQL
      • Make use of the INTO clause to hold the values returned by a SQL statement
      • Differentiate between implicit cursors and explicit cursors
      • Use SQL cursor attributes
  • SQL Statements in PL/SQL
      • Retrieve a row from the database by using the SELECT command.
      • Make changes to rows in the database by using DML commands.
      • Control a transaction with the COMMIT , ROLLBACK , or SAVEPOINT command.
  • SQL Statements in PL/SQL
  • SELECT Statements in PL/SQL
    • Retrieve data from the database with a SELECT statement.
    • Syntax:
    SELECT select_list INTO { variable_name [, variable_name ] ... | record_name } FROM table [WHERE condition ];
  •  
  • SELECT Statements in PL/SQL
      • The INTO clause is required.
      • Queries must return only one row.
    • Example:
    SET SERVEROUTPUT ON DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||fname); END; /
  • SELECT Statements in PL/SQL
  • Retrieving Data in PL/SQL
    • Retrieve the hire_date and the salary for the specified employee.
    • Example:
    DECLARE emp_hiredate employees.hire_date%TYPE; emp_salary employees.salary%TYPE; BEGIN SELECT hire_date, salary INTO emp_hiredate, emp_salary FROM employees WHERE employee_id = 100; END; /
  • Retrieving Data in PL/SQL
    • Return the sum of the salaries for all the employees in the specified department.
    • Example:
    SET SERVEROUTPUT ON DECLARE sum_sal NUMBER(10,2); deptno NUMBER NOT NULL := 60; BEGIN SELECT SUM(salary) -- group function INTO sum_sal FROM employees WHERE department_id = deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || sum_sal); END; /
  • Naming Conventions
    • DECLARE
    • hire_date employees.hire_date%TYPE;
    • sysdate hire_date%TYPE;
    • employee_id employees.employee_id%TYPE := 176;
    • BEGIN
    • SELECT hire_date, sysdate
    • INTO hire_date, sysdate
    • FROM employees
    • WHERE employee_id = employee_id;
    • END;
    • /
  • Naming Conventions
      • Use a naming convention to avoid ambiguity in the WHERE clause.
      • Avoid using database column names as identifiers.
      • Syntax errors can arise because PL/SQL checks the database first for a column in the table.
      • The names of local variables and formal parameters take precedence over the names of database tables .
      • The names of database table columns take precedence over the names of local variables.
  • Manipulating Data Using PL/SQL
    • Make changes to database tables by using DML commands:
      • INSERT
      • UPDATE
      • DELETE
      • MERGE
    INSERT UPDATE DELETE MERGE
  • Inserting Data
    • Add new employee information to the EMPLOYEES table.
    • Example:
    BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',sysdate, 'AD_ASST', 4000); END; /
  • Updating Data
    • Increase the salary of all employees who are stock clerks.
    • Example:
    DECLARE sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'; END; /
  • Deleting Data
    • Delete rows that belong to department 10 from the employees table.
    • Example:
    DECLARE deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = deptno; END; /
  • Merging Rows
    • Insert or update rows in the copy_emp table to match the employees table.
    DECLARE empno employees.employee_id%TYPE := 100; BEGIN MERGE INTO copy_emp c USING employees e ON (e.employee_id = empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id); END; /
  •  
  • SQL Cursor
      • A cursor is a pointer to the private memory area allocated by the Oracle server.
      • There are two types of cursors:
        • Implicit cursors: Created and managed internally by the Oracle server to process SQL statements
        • Explicit cursors: Explicitly declared by the programmer
  •  
  • SQL Cursor Attributes for Implicit Cursors
    • Using SQL cursor attributes, you can test the outcome of your SQL statements.
    Boolean attribute that evaluates to TRUE if the most recent SQL statement did not return even one row. SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at least one row. SQL%FOUND An integer value that represents number of rows affected by the most recent SQL statement. SQL%ROWCOUNT
  • SQL Cursor Attributes for Implicit Cursors
    • Delete rows that have the specified employee ID from the employees table. Print the number of rows deleted.
    • Example:
    VARIABLE rows_deleted VARCHAR2(30) DECLARE empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = empno; :rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); END; / PRINT rows_deleted
  • Summary
    • In this lesson, you should have learned how to:
      • Embed DML statements, transaction control statements, and DDL statements in PL/SQL
      • Use the INTO clause, which is mandatory for all SELECT statements in PL/SQL
      • Differentiate between implicit cursors and explicit cursors
      • Use SQL cursor attributes to determine the outcome of SQL statements
  • Writing Control Structures
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Identify the uses and types of control structures
      • Construct an IF statement
      • Use CASE statements and CASE expressions
      • Construct and identify different loop statements
      • Make use of guidelines while using the conditional control structures
  • Controlling Flow of Execution for loop while
  • IF Statements
    • Syntax:
    IF condition THEN statements ; [ELSIF condition THEN statements ;] [ELSE statements ;] END IF;
  • IF Statements
  • Simple IF Statement DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF; END; /
  • IF THEN ELSE Statement SET SERVEROUTPUT ON DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
  • IF ELSIF ELSE Clause DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF; END; /
  • NULL Values in IF Statements DECLARE myage number; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
  • CASE Expressions
      • A CASE expression selects a result and returns it.
      • To select the result, the C ASE expression uses expressions. The value returned by these expressions is used to select one of several alternatives.
    CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1] END; /
  • CASE Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
  • Searched CASE Expressions DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
  • CASE Statement DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 108; BEGIN CASE mngid WHEN 108 THEN SELECT department_id, department_name INTO deptid, deptname FROM departments WHERE manager_id=108; SELECT count(*) INTO emps FROM employees WHERE department_id=deptid; WHEN 200 THEN ... END CASE; DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname|| ' department. There are '||emps ||' employees in this department'); END; /
  • Handling Nulls
    • When working with nulls, you can avoid some common mistakes by keeping in mind the following rules:
      • Simple comparisons involving nulls always yield NULL .
      • Applying the logical operator NOT to a null yields NULL .
      • In conditional control statements, if the condition yields NULL , its associated sequence of statements is not executed.
  • Logic Tables
    • Build a simple Boolean condition with a comparison operator.
    AND TRUE FALSE NULL TRUE FALSE NULL TRUE NULL NULL NULL FALSE FALSE FALSE FALSE FALSE NOT TRUE FALSE NULL FALSE TRUE NULL TRUE NULL OR TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE NULL NULL NULL FALSE
  • Boolean Conditions
    • What is the value of flag in each case?
    REORDER_FLAG AVAILABLE_FLAG FLAG TRUE TRUE TRUE FALSE NULL TRUE NULL FALSE flag := reorder_flag AND available_flag; ? ? ? ?
  • Iterative Control: LOOP Statements
      • Loops repeat a statement or sequence of statements multiple times.
      • There are three loop types:
        • Basic loop
        • FOR loop
        • WHILE loop
  • Basic Loops
    • Syntax:
    LOOP statement1 ; . . . EXIT [WHEN condition ]; END LOOP;
  • Basic Loops
    • Example:
    DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; counter NUMBER(2) := 1; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; EXIT WHEN counter > 3; END LOOP; END; /
  • WHILE Loops
    • Syntax:
    • Use the WHILE loop to repeat statements while a condition is TRUE .
    WHILE condition LOOP statement1; statement2; . . . END LOOP;
  • WHILE Loops
    • Example:
    DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; new_city locations.city%TYPE := 'Montreal'; counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; WHILE counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; END LOOP; END; /
  • FOR Loops
      • Use a FOR loop to shortcut the test for the number of iterations.
      • Do not declare the counter; it is declared implicitly.
      • ' lower_bound .. upper_bound ' is required syntax.
    FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • FOR Loops
  • FOR Loops
    • Example:
    DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + i), new_city, countryid ); END LOOP; END; /
  • FOR Loops
    • Guidelines
      • Reference the counter within the loop only; it is undefined outside the loop.
      • Do not reference the counter as the target of an assignment.
      • Neither loop bound should be NULL .
  • Guidelines While Using Loops
      • Use the basic loop when the statements inside the loop must execute at least once.
      • Use the WHILE loop if the condition has to be evaluated at the start of each iteration.
      • Use a FOR loop if the number of iterations is known.
  • Nested Loops and Labels
      • Nest loops to multiple levels.
      • Use labels to distinguish between blocks and loops.
      • Exit the outer loop with the EXIT statement that references the label.
  • Nested Loops and Labels ... BEGIN <<Outer_loop>> LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_ done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop ; ... END LOOP Outer_loop ; END; /
  • Summary
    • In this lesson, you should have learned how to:
    • Change the logical flow of statements by using the following control structures.
      • Conditional ( IF statement)
      • CASE expressions and CASE statements
      • Loops:
        • Basic loop
        • FOR loop
        • WHILE loop
      • EXIT statements
  • Working with Composite Data Types
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Create user-defined PL/SQL records
      • Create a record with the %ROWTYPE attribute
      • Create an INDEX BY table
      • Create an INDEX BY table of records
      • Describe the difference between records, tables, and tables of records
  • Composite Data Types
      • Can hold multiple values, unlike scalar types
      • Are of two types:
        • PL/SQL records
        • PL/SQL collections
            • INDEX BY tables or associative arrays
            • Nested table
            • VARRAY
  • Composite Data Types
      • Use PL/SQL records when you want to store values of different data types but only one occurrence at a time.
      • Use PL/SQL collections when you want to store values of same data type.
  • PL/SQL Records
      • Must contain one or more components of any scalar, RECORD , or INDEX BY table data type, called fields
      • Are similar to structures in most 3GL languages including C and C++
      • Are user defined and can be a subset of a row in a table
      • Treat a collection of fields as a logical unit
      • Are convenient for fetching a row of data from a table for processing
  • Creating a PL/SQL Record
    • Syntax:
    TYPE type_name IS RECORD ( field_declaration[, field_declaration]…); field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr ] identifier type_name; 1 2 field_declaration :
  • Creating a PL/SQL Record
    • Declare variables to store the name, job, and salary of a new employee.
    • Example:
    ... TYPE emp_record_type IS RECORD (last_name VARCHAR2(25), job_id VARCHAR2(10), salary NUMBER(8,2)); emp_record emp_record_type; ...
  • PL/SQL Record Structure Example: 100 King AD_PRES employee_id number(6) last_name varchar2(25) job_id varchar2(10) Field2 (data type) Field3 (data type) Field1 (data type) Field2 (data type) Field3 (data type) Field1 (data type)
  • The %ROWTYPE Attribute
      • Declare a variable according to a collection of columns in a database table or view.
      • Prefix %ROWTYPE with the database table or view.
      • Fields in the record take their names and data types from the columns of the table or view.
    DECLARE identifier reference%ROWTYPE; Syntax:
  • The %ROWTYPE Attribute
      • Declare a variable according to a collection of columns in a database table or view.
      • Prefix %ROWTYPE with the database table.
      • Fields in the record take their names and data types from the columns of the table or view.
  • Advantages of Using %ROWTYPE
      • The number and data types of the underlying database columns need not be known.
      • The number and data types of the underlying database column may change at run time.
      • The attribute is useful when retrieving a row with the SELECT * statement.
  • The %ROWTYPE Attribute ... DEFINE employee_number = 124 DECLARE emp_rec employees%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps(empno, ename, job, mgr, hiredate, leavedate, sal, comm, deptno) VALUES (emp_rec.employee_id, emp_rec.last_name, emp_rec.job_id,emp_rec.manager_id, emp_rec.hire_date, SYSDATE, emp_rec.salary, emp_rec.commission_pct, emp_rec.department_id); END; /
  • Inserting a Record Using %ROWTYPE ... DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id, hire_date, hire_date, salary, commission_pct, department_id INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps VALUES emp_rec; END; / SELECT * FROM retired_emps;
  • Updating a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM retired_emps; emp_rec.leavedate:=SYSDATE; UPDATE retired_emps SET ROW = emp_rec WHERE empno=&employee_number; END; / SELECT * FROM retired_emps;
  • INDEX BY Tables or Associative Arrays
      • Are PL/SQL structures with two columns:
        • Primary key type integer or string
        • Column of scalar or record data type
      • Are unconstrained in size. However the size depends on the values the key data type can hold.
  • Creating an INDEX BY Table
    • Syntax:
    TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] | table%ROWTYPE [INDEX BY PLS_INTEGER | BINARY_INTEGER | VARCHAR2(< size >)]; identifier type_name; ... TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY PLS_INTEGER; ... ename_table ename_table_type; Declare an INDEX BY table to store the last names of employees.
  • Creating an INDEX BY Table
  • INDEX BY Table Structure Unique Key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
  • Creating an INDEX BY Table
    • DECLARE
    • TYPE ename_table_type IS TABLE OF
    • employees.last_name%TYPE
    • INDEX BY PLS_INTEGER;
    • TYPE hiredate_table_type IS TABLE OF DATE
    • INDEX BY PLS_INTEGER;
    • ename_table ename_table_type;
    • hiredate_table hiredate_table_type;
    • BEGIN
    • ename_table(1) := 'CAMERON';
    • hiredate_table(8) := SYSDATE + 7;
    • IF ename_table.EXISTS(1) THEN
    • INSERT INTO ...
    • ...
    • END;
    • /
  • Using INDEX BY Table Methods
    • The following methods make INDEX BY tables easier to use:
      • NEXT
      • TRIM
      • DELETE
      • EXISTS
      • COUNT
      • FIRST and LAST
      • PRIOR
  • INDEX BY Table of Records
    • Define an INDEX BY table variable to hold an entire row from a table.
    • Example:
    DECLARE TYPE dept_table_type IS TABLE OF departments%ROWTYPE INDEX BY PLS_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record
  • INDEX BY Table of Records
  • Example of INDEX BY Table of Records SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):= 104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; /
  • Summary
    • In this lesson, you should have learned how to:
      • Define and reference PL/SQL variables of composite data types:
        • PL/SQL records
        • INDEX BY tables
        • INDEX BY table of records
      • Define a PL/SQL record by using the %ROWTYPE attribute
  • Using Explicit Cursors
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Distinguish between an implicit and an explicit cursor
      • Discuss when and why to use an explicit cursor
      • Declare and control explicit cursors
      • Use simple loop and cursor FOR loop to fetch data
      • Declare and use cursors with parameters
      • Lock rows using the FOR UPDATE clause
      • Reference the current row with the WHERE CURRENT clause
  • About Cursors
    • Every SQL statement executed by the Oracle Server has an individual cursor associated with it:
      • Implicit cursors: Declared and managed by PL/SQL for all DML and PL/SQL SELECT statements
      • Explicit cursors: Declared and managed by the programmer
  • Explicit Cursor Operations Active set Table 100 King AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP . . . . . . . . . 139 Seo ST_CLERK 140 Patel ST_CLERK . . .
  • Controlling Explicit Cursors
    • Load the current row into variables
    FETCH
    • Test for existing rows
    EMPTY?
    • Return to FETCH if rows are found
    No
    • Release the active set
    CLOSE Yes
    • Create a named SQL area
    DECLARE
    • Identify the active set
    OPEN
  • Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor pointer Open the cursor. 1 2 3 Cursor pointer Cursor pointer
  • Declaring the Cursor
    • Syntax:
    CURSOR cursor_name IS select_statement; Examples: DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; DECLARE locid NUMBER:= 1700; CURSOR dept_cursor IS SELECT * FROM departments WHERE location_id = locid; ...
  • Declaring the Cursor
  • Opening the Cursor DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; ... BEGIN OPEN emp_cursor;
  • Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO empno, lname; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); ... END; /
  • Fetching Data from the Cursor
  • Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND ; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; ... END; /
  • Closing the Cursor ... LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; CLOSE emp_cursor; END; /
  • Cursors and Records
    • Process the rows of the active set by fetching values into a PL/SQL RECORD .
    DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; ...
  • Cursor FOR Loops
    • Syntax:
      • The cursor FOR loop is a shortcut to process explicit cursors.
      • Implicit open, fetch, exit, and close occur.
      • The record is implicitly declared.
    FOR record_name IN cursor_name LOOP statement1 ; statement2 ; . . . END LOOP;
  • Cursor FOR Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; BEGIN FOR emp_record IN emp_cursor LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' ' || emp_record.last_name ); END LOOP; END; /
  • Explicit Cursor Attributes
    • Obtain status information about a cursor.
    Boolean Evaluates to TRUE if the cursor is open Evaluates to TRUE if the most recent fetch does not return a row Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND Evaluates to the total number of rows returned so far Boolean Boolean Number %ISOPEN %NOTFOUND %FOUND %ROWCOUNT Attribute Type Description
  • The %ISOPEN Attribute
      • Fetch rows only when the cursor is open.
      • Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open.
    • Example:
    IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...
  • Example of %ROWCOUNT and %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno) ||' '|| ename); END LOOP; CLOSE emp_cursor; END ; /
  • Cursor FOR Loops Using Subqueries
    • No need to declare the cursor.
    • Example:
    SET SERVEROUTPUT ON BEGIN FOR emp_record IN (SELECT employee_id, last_name FROM employees WHERE department_id =30) LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' '||emp_record.last_name); END LOOP; END; /
  • Cursors with Parameters
    • Syntax:
      • Pass parameter values to a cursor when the cursor is opened and the query is executed.
      • Open an explicit cursor several times with a different active set each time.
    CURSOR cursor_name [( parameter_name datatype , ...)] IS select_statement ; OPEN cursor_name(parameter_value ,.....) ;
  • Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor (deptno NUMBER) IS SELECT employee_id, last_name FROM employees WHERE department_id = deptno; dept_id NUMBER; lname VARCHAR2(15); BEGIN OPEN emp_cursor (10); ... CLOSE emp_cursor; OPEN emp_cursor (20); ...
  • The FOR UPDATE Clause
    • Syntax:
      • Use explicit locking to deny access to other sessions for the duration of a transaction.
      • Lock the rows before the update or delete.
    SELECT ... FROM ... FOR UPDATE [OF column_reference ][NOWAIT | WAIT n ];
  • The FOR UPDATE Clause
  • The WHERE CURRENT OF Clause
    • Syntax:
      • Use cursors to update or delete the current row.
      • Include the FOR UPDATE clause in the cursor query to lock the rows first.
      • Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.
    WHERE CURRENT OF cursor ; UPDATE employees SET salary = ... WHERE CURRENT OF emp_cursor;
  • Cursors with Subqueries DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name, t2.staff FROM departments t1, (SELECT department_id, COUNT(*) AS STAFF FROM employees GROUP BY department_id) t2 WHERE t1.department_id = t2.department_id AND t2.staff >= 3; ... Example:
  • Summary
    • In this lesson you should have learned how to:
      • Distinguish cursor types:
        • Implicit cursors: Used for all DML statements and single-row queries
        • Explicit cursors: Used for queries of zero, one, or more rows
      • Create and handle explicit cursors
      • Use simple loops and cursor FOR loops to handle multiple rows in the cursors
      • Evaluate the cursor status by using the cursor attributes
      • Use the FOR UPDATE and WHERE CURRENT OF clauses to update or delete the current fetched row
  • Handling Exceptions
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Define PL/SQL exceptions
      • Recognize unhandled exceptions
      • List and use different types of PL/SQL exception handlers
      • Trap unanticipated errors
      • Describe the effect of exception propagation in nested blocks
      • Customize PL/SQL exception messages
  • Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); END; /
  • Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement retrieved multiple rows. Consider using a cursor.'); END; /
  • Handling Exceptions with PL/SQL
      • An exception is an error PL/SQL that is raised during program execution.
      • An exception can be raised:
        • Implicitly by the Oracle server
        • Explicitly by the program
      • An exception can be handled:
        • By trapping it with a handler
        • By propagating it to the calling environment
  • Handling Exceptions Exception raised Is the exception trapped? yes Execute statements in the EXCEPTION section Terminate gracefully no Terminate abruptly Propagate the exception
  • Exception Types
      • Predefined Oracle Server
      • Non-predefined Oracle Server
      • User-defined
    } Implicitly raised Explicitly raised
  • Trapping Exceptions
    • Syntax:
    EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1 ; statement2 ; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1 ; statement2 ; . . .] [WHEN OTHERS THEN statement1 ; statement2 ; . . .]
  • Trapping Exceptions
  • Guidelines for Trapping Exceptions
      • The EXCEPTION keyword starts the exception handling section.
      • Several exception handlers are allowed.
      • Only one handler is processed before leaving the block.
      • WHEN OTHERS is the last clause.
  • Trapping Predefined Oracle Server Errors
      • Reference the predefined name in the exception handling routine.
      • Sample predefined exceptions:
        • NO_DATA_FOUND
        • TOO_MANY_ROWS
        • INVALID_CURSOR
        • ZERO_DIVIDE
        • DUP_VAL_ON_INDEX
  •  
  •  
  • Trapping Non-Predefined Oracle Server Errors Declarative section Name the exception Code PRAGMA EXCEPTION_INIT EXCEPTION section Handle the raised exception Associate Reference Declare
  • Non-Predefined Error
    • Trap Oracle server error number –01400, cannot insert NULL .
    SET SERVEROUTPUT ON DECLARE insert_excep EXCEPTION; PRAGMA EXCEPTION_INIT (insert_excep, -01400); BEGIN INSERT INTO departments (department_id, department_name) VALUES (280, NULL); EXCEPTION WHEN insert_excep THEN DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED'); DBMS_OUTPUT.PUT_LINE(SQLERRM); END; / 1 2 3
  • Functions for Trapping Exceptions
      • SQLCODE : Returns the numeric value for the error code
      • SQLERRM : Returns the message associated with the error number
  • Functions for Trapping Exceptions
    • Example:
    DECLARE error_code NUMBER; error_message VARCHAR2(255); BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; error_code := SQLCODE ; error_message := SQLERRM ; INSERT INTO errors (e_user, e_date, error_code, error_message) VALUES(USER,SYSDATE,error_code, error_message); END; /
  • Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the RAISE statement. Exception -handling section Handle the raised exception. Raise Reference Declare
  • Trapping User-Defined Exceptions ... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION; name VARCHAR2(20):='&name'; deptno NUMBER :=&deptno; BEGIN UPDATE departments SET department_name = name WHERE department_id = deptno; IF SQL%NOTFOUND THEN RAISE invalid_department; END IF; COMMIT; EXCEPTION WHEN invalid_department THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3
  • Calling Environments Traps exception in exception-handling routine of enclosing block An enclosing PL/SQL block Accesses exception number through the SQLCA data structure Precompiler application Accesses error number and message in an ON-ERROR trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Oracle Developer Forms Displays error number and message to screen Procedure Builder Displays error number and message to screen i SQL*Plus
  • Propagating Exceptions in a Subblock DECLARE . . . no_rows exception; integrity exception; PRAGMA EXCEPTION_INIT (integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE no_rows; END IF; END; END LOOP; EXCEPTION WHEN integrity THEN ... WHEN no_rows THEN ... END; / Subblocks can handle an exception or pass the exception to the enclosing block.
  • The RAISE_APPLICATION_ERROR Procedure
    • Syntax:
      • You can use this procedure to issue user-defined error messages from stored subprograms.
      • You can report errors to your application and avoid returning unhandled exceptions.
    raise_application_error ( error_number, message [, {TRUE | FALSE}]);
  • The RAISE_APPLICATION_ERROR Procedure
      • Used in two different places:
        • Executable section
        • Exception section
      • Returns error conditions to the user in a manner consistent with other Oracle server errors.
  • RAISE_APPLICATION_ERROR
    • Exception section:
    BEGIN ... DELETE FROM employees WHERE manager_id = v_mgr; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'This is not a valid manager'); END IF; ... Executable section: ... EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201, 'Manager is not a valid employee.'); END; /
  • Summary
    • In this lesson, you should have learned how to:
      • Define PL/SQL exceptions
      • Add an EXCEPTION section to the PL/SQL block to deal with exceptions at run time
      • Handle different types of exceptions:
        • Predefined exceptions
        • Non-predefined exceptions
        • User-defined exceptions
      • Propagate exceptions in nested blocks and call applications
  • Creating Stored Procedures and Functions
  • Objectives
    • After completing this lesson, you should be able to do the following:
      • Differentiate between anonymous blocks and subprograms
      • Create a simple procedure and invoke it from an anonymous block
      • Create a simple function
      • Create a simple function that accepts a parameter
      • Differentiate between procedures and functions
  • Procedures and Functions
      • Are named PL/SQL blocks
      • Are called PL/SQL subprograms
      • Have block structures similar to anonymous blocks:
        • Optional declarative section (without DECLARE keyword)
        • Mandatory executable section
        • Optional section to handle exceptions
  • Differences Between Anonymous Blocks and Subprograms Can take parameters Cannot take parameters Subprograms called functions must return values Do not return values They are named and therefore can be invoked by other applications Cannot be invoked by other applications Stored in the database Not stored in the database Compiled only once Compiled every time Named PL/SQL blocks Unnamed PL/SQL blocks Subprograms Anonymous Blocks
  • Procedure: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] IS|AS procedure_body;
  • Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE add_dept IS dept_id dept.department_id%TYPE; dept_name dept.department_name%TYPE; BEGIN dept_id:=280; dept_name:= ' ST-Curriculum ' ; INSERT INTO dept(department_id,department_name) VALUES(dept_id,dept_name); DBMS_OUTPUT.PUT_LINE( ' Inserted ' || SQL%ROWCOUNT || ' row ' ); END; /
  • Procedure: Example
  • Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
  • Function: Syntax C REATE [OR REPLACE] FUNCTION function_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] RETURN datatype IS|AS function_body;
  • Function: Example CREATE FUNCTION check_sal RETURN Boolean IS dept_id employees.department_id%TYPE; empno employees.employee_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN empno:=205; SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id= empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END; /
  • Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; END; /
  • Passing Parameter to the Function DROP FUNCTION check_sal; / CREATE FUNCTION check_sal (empno employees.employee_id%TYPE) RETURN Boolean IS dept_id employees.department_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id=empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION ... ...
  • Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(205)) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70'); IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(70)) THEN ... END IF; END; /
  • Summary
    • In this lesson, you should have learned how to:
      • Create a simple procedure
      • Invoke the procedure from an anonymous block
      • Create a simple function
      • Create a simple function that accepts parameters
      • Invoke the function from an anonymous block
  • Goals of the Course
    • After completing this course, you should be able to do the following:
      • Identify the major structural components of Oracle Database 10 g
      • Retrieve row and column data from tables with the SELECT statement.
      • Process database record with DML codes.
      • Appreciate that PL/SQL provides programming extensions to SQL
      • Write PL/SQL code to interface with the database
      • Design PL/SQL program units that execute efficiently
      • Use PL/SQL programming constructs and conditional control statements
      • Handle run-time errors
      • Describe stored procedures and functions
  • Oracle10 g Single development model Common skillsets Reliability Unified management Scalability One vendor
  • Oracle10 g
  • Oracle Database 10 g Multimedia Object-relational data Messages Documents
  • Oracle Application Server 10 g Application development framework Application server Business intelligence Portals Integration Transactional applications
  • Oracle Enterprise Manager 10 g Grid Control
      • Software provisioning
      • Application service level monitoring
  • Relational and Object Relational Database Management Systems
      • Relational model and object relational model
      • User-defined data types and objects
      • Fully compatible with relational database
      • Support of multimedia and large objects
      • High-quality database server features
  • Oracle Internet Platform System management Network services Databases Application servers Internet applications Any browser Any FTP client Any mail client SQL PL/SQL Java Clients Presentation and business logic Business logic and data Development tools
  • System Development Life Cycle Strategy and analysis Design Build and document Transition Production
  • System Development Life Cycle Strategy and analysis Design Build and document Transition Production
  • Data Storage on Different Media Electronic spreadsheet Filing cabinet Database
  • Relational Database Concept
      • Dr. E. F. Codd proposed the relational model for database systems in 1970.
      • It is the basis for the relational database management system (RDBMS).
      • The relational model consists of the following:
        • Collection of objects or relations
        • Set of operators to act on the relations
        • Data integrity for accuracy and consistency
  • Definition of a Relational Database
    • A relational database is a collection of relations or two-dimensional tables.
    Oracle server Table name: EMPLOYEES Table name: DEPARTMENTS … …
  • Data Models Model of system in client’s mind Entity model of client’s model Tables on disk Oracle server Table model of entity model
      • Create an entity relationship diagram from business specifications or narratives:
      • Scenario
        • “. . . Assign one or more employees to a department . . .”
        • “. . . Some departments do not yet have assigned employees . . .”
    Entity Relationship Model EMPLOYEE #* number * name o job title DEPARTMENT #* number * name o location assigned to composed of
  •  
  • Entity Relationship Modeling Conventions Unique identifier (UID)‏ Primary marked with “#” Secondary marked with “(#)” EMPLOYEE #* number * name o job title DEPARTMENT #* number * name o location
    • Attribute
      • Singular name
      • Lowercase
      • Mandatory marked with *
      • Optional marked with “o”
    assigned to composed of
    • Entity
      • Singular, unique name
      • Uppercase
      • Soft box
      • Synonym in parentheses
  • Entity Relationship Modeling Conventions
    • Entity
      • Singular, unique name
      • Uppercase
      • Soft box
      • Synonym in parentheses
    • Attribute
      • Singular name
      • Lowercase
      • Mandatory marked with *
      • Optional marked with “o”
    EMPLOYEE #* number * name o job title DEPARTMENT #* number * name o location assigned to composed of Unique identifier (UID)‏ Primary marked with “#” Secondary marked with “(#)”
  • Relating Multiple Tables
      • Each row of data in a table is uniquely identified by a primary key (PK).
      • You can logically relate data from multiple tables using foreign keys (FK).
    Table name: EMPLOYEES Table name: DEPARTMENTS Primary key Primary key Foreign key …
  •  
  • Relational Database Terminology 1 2 3 4 6 5
  •  
  • Relational Database Properties
    • A relational database:
      • Can be accessed and modified by executing structured query language (SQL) statements
      • Contains a collection of tables with no physical pointers
      • Uses a set of operators
  • Communicating with an RDBMS Using SQL SQL statement is entered. Statement is sent to Oracle server. Oracle server SELECT department_name FROM departments;
  • Oracle’s Relational Database Management System User tables Data dictionary Oracle server
  • SQL Statements SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMENT GRANT REVOKE COMMIT ROLLBACK SAVEPOINT Data manipulation language (DML)‏ Data definition language (DDL)‏ Transaction control Data control language (DCL)‏
  • Tables Used in the Course EMPLOYEES DEPARTMENTS JOB_GRADES
  • Summary
      • Oracle Database 10 g is the database for grid computing.
      • The database is based on the object relational database management system.
      • Relational databases are composed of relations, managed by relational operations, and governed by data integrity constraints.
      • With the Oracle server, you can store and manage information by using the SQL language and PL/SQL engine.